88 lines
2.3 KiB
PHP
88 lines
2.3 KiB
PHP
<?php
|
|
namespace App\CMS\Shortcodes;
|
|
|
|
use App\Models\Widgets\Widget as WidgetModel;
|
|
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
|
|
|
|
class Widget
|
|
{
|
|
protected static $widgets = [];
|
|
protected static $initialized = false;
|
|
|
|
protected function getRenderedWidget(WidgetModel $widget)
|
|
{
|
|
$widget->settings = json_decode($widget->settings);
|
|
|
|
$handler = $widget->widget_type_handler;
|
|
$presenter = call_user_func([$handler, 'getPresenter']);
|
|
|
|
return call_user_func([$presenter, 'render'], $widget);
|
|
}
|
|
|
|
/**
|
|
* Load one widget from database
|
|
*
|
|
* @param $containerId
|
|
*/
|
|
protected function loadWidget($containerId)
|
|
{
|
|
$widget = WidgetModel::where('container_id', $containerId)
|
|
->first();
|
|
|
|
if (!$widget) {
|
|
return;
|
|
}
|
|
|
|
$widget->timestamps = false;
|
|
$widget->viewed++;
|
|
$widget->save();
|
|
$widget->timestamps = true;
|
|
|
|
self::$widgets[$containerId] = $this->getRenderedWidget($widget);
|
|
}
|
|
|
|
/**
|
|
* Load all frequently used widgets
|
|
*
|
|
* Frequency of loaded widgets is counted only using direct loading, widgets displayed in widget areas are omitted
|
|
*/
|
|
protected function initWidgets()
|
|
{
|
|
if (self::$initialized) {
|
|
return;
|
|
}
|
|
|
|
$widgets = WidgetModel::where('viewed', '>=', setting('preloadFrequentedWidgetsTreshold', 10))
|
|
->where('language', LaravelLocalization::getCurrentLocale())
|
|
->get();
|
|
|
|
foreach ($widgets as $widget) {
|
|
self::$widgets[$widget->container_id] = $this->getRenderedWidget($widget);
|
|
}
|
|
|
|
self::$initialized = true;
|
|
}
|
|
|
|
/**
|
|
* Register new shortcode
|
|
*
|
|
* Initfrequently used widgets and if not presented yet - load desired widget specified as content of shortcode
|
|
*
|
|
* @param $shortcode
|
|
* @param $containerId
|
|
* @param $compiler
|
|
* @param $name
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function register($shortcode, $containerId, $compiler, $name)
|
|
{
|
|
$this->initWidgets();
|
|
|
|
if (!isset(self::$widgets[$containerId])) {
|
|
$this->loadWidget($containerId);
|
|
}
|
|
|
|
return self::$widgets[$containerId];
|
|
}
|
|
} |