Files
core/app/CMS/Helpers/WidgetAreas.php

84 lines
2.2 KiB
PHP

<?php
namespace App\CMS\Helpers;
use App\CMS\Repositories\Widgets\WidgetArea as WidgetAreaRepository;
use Illuminate\Support\Facades\Cache;
class WidgetAreas
{
/**
* @var array list of inicialized widget areas
*/
protected static $widgetAreas = [];
protected static $initialized = false;
protected static function saveRenderedWidgetArea($widgets)
{
foreach ($widgets as $widget) {
if (!isset(self::$widgetAreas[$widget->widget_area_code])) {
self::$widgetAreas[$widget->widget_area_code] = '';
}
self::$widgetAreas[$widget->widget_area_code] .= Widget::render($widget);
}
}
protected static function loadWidgetArea($uniqueCode)
{
$widgets = Cache::remember('widget-area-' . $uniqueCode, setting('widgetCacheLifetime', 5), function () use ($uniqueCode) {
$widgetArea = app(\App\CMS\Repositories\Widgets\WidgetArea::class);
return $widgetArea->getWidgets($uniqueCode)
->get();
});
self::saveRenderedWidgetArea($widgets);
}
protected static function initWidgetAreas()
{
if (self::$initialized) {
return;
}
$widgets = Cache::remember('widgets', setting('widgetCacheLifetime', 5), function () {
$widgetArea = app(WidgetAreaRepository::class);
return $widgetArea->getWidgets()
->get();
});
self::saveRenderedWidgetArea($widgets);
self::$initialized = true;
}
/**
* Renderer for whole widget area.
*
* @param $uniqueCode
*
* @return void
*/
public static function render($uniqueCode)
{
if (!self::$initialized) {
self::initWidgetAreas();
}
if (!isset(self::$widgetAreas[$uniqueCode])) {
self::loadWidgetArea($uniqueCode);
}
echo isset(self::$widgetAreas[$uniqueCode]) ? self::$widgetAreas[$uniqueCode] : null;
}
/**
* Get list of loaded widgets and areas
*
* @return array
*/
public static function getLoadedWidgets()
{
return ['areas' => array_keys(self::$widgetAreas)];
}
}