From 8f4e6268a4cb1c70e75caa88a25c545277f66869 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Kv=C3=A1=C4=8Dek?= Date: Sun, 25 Sep 2016 12:42:26 +0200 Subject: [PATCH] FEATURE: move widget and template dir installation into middleware, optimize middleware groups --- .../Registrators/TemplateRegistrator.php | 39 +++++++++---- .../Registrators/WidgetRegistrator.php | 58 +++++++++++-------- app/Helpers/CurrentTemplate.php | 7 ++- app/Helpers/Settings.php | 1 + app/Http/Kernel.php | 26 ++++++--- app/Http/Middleware/TemplatePathInstaller.php | 31 ++++++++++ app/Http/Middleware/WidgetInstaller.php | 30 ++++++++++ app/Http/routes.php | 2 +- app/Providers/AppServiceProvider.php | 20 +------ app/Providers/TemplateServiceProvider.php | 51 ++++------------ .../Providers/StaticPagesServiceProvider.php | 8 +-- templates/Base/OnePage/Handlers/OnePage.php | 34 ++++++----- 12 files changed, 184 insertions(+), 123 deletions(-) create mode 100644 app/Http/Middleware/TemplatePathInstaller.php create mode 100644 app/Http/Middleware/WidgetInstaller.php diff --git a/app/Handlers/Registrators/TemplateRegistrator.php b/app/Handlers/Registrators/TemplateRegistrator.php index 1d0f5257..5a8a74f1 100644 --- a/app/Handlers/Registrators/TemplateRegistrator.php +++ b/app/Handlers/Registrators/TemplateRegistrator.php @@ -28,6 +28,10 @@ class TemplateRegistrator * @var int ID of module */ protected $moduleId; + /** + * @var array list of all registered template paths + */ + protected $paths = []; /** * Set base path @@ -80,24 +84,39 @@ class TemplateRegistrator * Registers new template path. * This method registeres given path itself with all subdirectories * + * @param $baseDirectory * @param string $path path relatively to root of the project * @param string $name human readable identification of given template path * * @throws \Exception */ - public function register($path, $name) + public function register($baseDirectory, $path, $name) { - // check if base directory was set - if (!$this->baseDirectory || !is_dir($this->baseDirectory)) { - throw new \Exception('Set $baseDirectory before registering template path.'); + $this->paths[] = [ + 'namespace' => $this->namespace, + 'moduleId' => $this->moduleId, + 'baseDirectory' => $baseDirectory, + 'path' => $this->baseDirectory . DIRECTORY_SEPARATOR . $path, + 'name' => $name + ]; + $this->unsetNamespace(); + } + + public function saveTemplates() + { + if (!is_array($this->paths) || empty($this->paths)) { + return; } - $this->registeredPath = $this->baseDirectory . DIRECTORY_SEPARATOR . $path; + foreach ($this->paths as $path) { + $this->setNamespace($path['namespace']); + $this->setModuleId($path['moduleId']); + $this->setBaseDirectory($path['baseDirectory']); - // register path - $this->registerPath($this->registeredPath, $name); - - $this->unsetNamespace(); + $this->registeredPath = $this->baseDirectory . DIRECTORY_SEPARATOR . $path['path']; + // register path + $this->registerPath($this->registeredPath, $path['name']); + } } /** @@ -146,7 +165,7 @@ class TemplateRegistrator Template::ASSETS_DIRECTORY, Template::MODULES_DIRECTORY ]; - + if (in_array($dirName, $ignoredDirectories)) { return; } diff --git a/app/Handlers/Registrators/WidgetRegistrator.php b/app/Handlers/Registrators/WidgetRegistrator.php index d3b68a3a..f97aaef4 100644 --- a/app/Handlers/Registrators/WidgetRegistrator.php +++ b/app/Handlers/Registrators/WidgetRegistrator.php @@ -3,17 +3,11 @@ namespace App\Handlers\Registrators; use App\Enumerations\WidgetTypesWithHandlers; use App\Models\WidgetType; -use App\Widgets\Contracts\PublicWidget; -use Symfony\Component\Process\Exception\InvalidArgumentException; class WidgetRegistrator { - protected $widgets; + protected $registeredWidgets = []; - function __construct() - { - $this->widgets = WidgetTypesWithHandlers::getSimple(); - } /** * Method used for registering new widgets @@ -24,27 +18,41 @@ class WidgetRegistrator */ public function register($classname, $templateId = null, $moduleId = null) { - $class = new $classname; - if (!$class instanceof PublicWidget) { - throw new InvalidArgumentException($class . ' must implement PublicWidget interface.'); - } + $this->registeredWidgets[] = [ + 'class' => $classname, + 'templateId' => $templateId, + 'moduleId' => $moduleId + ]; + } - // register widget as new widget type - if (!in_array($classname, $this->widgets)) { - $widgetName = call_user_func($classname . '::getName'); - $widgetDescription = call_user_func($classname . '::getDescription'); + /** + * Install all non-installed widgets + */ + public function installWidgets() + { + $installed = WidgetTypesWithHandlers::getSimple(); + foreach ($this->registeredWidgets as $registeredWidget) { + $classname = $registeredWidget['class']; + $templateId = $registeredWidget['templateId']; + $moduleId = $registeredWidget['moduleId']; - // create row in widget types - WidgetType::create([ - 'handler' => $classname, - 'name' => $widgetName, - 'module_id' => $moduleId, - 'template_id' => $templateId, - 'description' => $widgetDescription - ]); + // register widget as new widget type + if (!in_array($classname, $installed)) { + $widgetName = call_user_func($classname . '::getName'); + $widgetDescription = call_user_func($classname . '::getDescription'); - // install widget (if neccessary) - call_user_func($classname . '::install'); + // create row in widget types + WidgetType::create([ + 'handler' => $classname, + 'name' => $widgetName, + 'module_id' => $moduleId, + 'template_id' => $templateId, + 'description' => $widgetDescription + ]); + + // install widget (if neccessary) + call_user_func($classname . '::install'); + } } } } diff --git a/app/Helpers/CurrentTemplate.php b/app/Helpers/CurrentTemplate.php index 2dfaa2cc..ff6900cf 100644 --- a/app/Helpers/CurrentTemplate.php +++ b/app/Helpers/CurrentTemplate.php @@ -1,7 +1,6 @@ where('enabled', true) ->first(); + + if (self::$template) { + self::$template->module_settings = json_decode(self::$template->module_settings); + } + + self::$initialized = true; } return self::$template; diff --git a/app/Helpers/Settings.php b/app/Helpers/Settings.php index 56882328..56499040 100644 --- a/app/Helpers/Settings.php +++ b/app/Helpers/Settings.php @@ -38,6 +38,7 @@ class Settings if (isset(self::$settings->$key)) { $exists = true; + self::$initialized = true; return self::$settings->$key; } diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 15940382..7ec6718f 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -2,8 +2,13 @@ namespace App\Http; +use App\Http\Middleware\TemplatePathInstaller; +use App\Http\Middleware\WidgetInstaller; use Illuminate\Foundation\Http\Kernel as HttpKernel; +use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode; use Illuminate\Routing\Middleware\ThrottleRequests; +use Illuminate\Session\Middleware\StartSession; +use Illuminate\View\Middleware\ShareErrorsFromSession; use Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter; use Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes; use Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect; @@ -18,7 +23,10 @@ class Kernel extends HttpKernel * @var array */ protected $middleware = [ - \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, + Middleware\EncryptCookies::class, + StartSession::class, + ShareErrorsFromSession::class, + Middleware\VerifyCsrfToken::class ]; /** * The application's route middleware groups. @@ -26,14 +34,16 @@ class Kernel extends HttpKernel * @var array */ protected $middlewareGroups = [ - 'web' => [ - Middleware\EncryptCookies::class, - \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, - \Illuminate\Session\Middleware\StartSession::class, - \Illuminate\View\Middleware\ShareErrorsFromSession::class, - Middleware\VerifyCsrfToken::class, + 'web' => [ + CheckForMaintenanceMode::class, ], - 'api' => [ + 'admin' => [ + Middleware\Authenticate::class, + Middleware\AdminMenuRegistrator::class, + TemplatePathInstaller::class, + WidgetInstaller::class, + ], + 'api' => [ 'throttle:60,1', ], ]; diff --git a/app/Http/Middleware/TemplatePathInstaller.php b/app/Http/Middleware/TemplatePathInstaller.php new file mode 100644 index 00000000..f06d1446 --- /dev/null +++ b/app/Http/Middleware/TemplatePathInstaller.php @@ -0,0 +1,31 @@ +saveTemplates(); + + return $next($request); + } +} diff --git a/app/Http/Middleware/WidgetInstaller.php b/app/Http/Middleware/WidgetInstaller.php new file mode 100644 index 00000000..883819f3 --- /dev/null +++ b/app/Http/Middleware/WidgetInstaller.php @@ -0,0 +1,30 @@ +installWidgets(); + + return $next($request); + } +} diff --git a/app/Http/routes.php b/app/Http/routes.php index f5f885c5..19c7cd70 100644 --- a/app/Http/routes.php +++ b/app/Http/routes.php @@ -19,7 +19,7 @@ Route::group([ * This route group serves to handle request in admin */ Route::group([ - 'middleware' => ['web', 'auth', 'adminMenu'], + 'middleware' => ['admin'], 'namespace' => 'Admin', 'prefix' => 'admin' ], function () { diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 20fb3f5c..cb1c8fec 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -16,6 +16,7 @@ use App\Widgets\HtmlCode\HtmlCode; use App\Widgets\Menu\Menu; use App\Widgets\OrbitSlider\OrbitSlider; use Illuminate\Support\Facades\App; +use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\File; use Illuminate\Support\ServiceProvider; use Symfony\Component\Process\Exception\InvalidArgumentException; @@ -34,7 +35,6 @@ class AppServiceProvider extends ServiceProvider } $this->registerWidgets(); - $this->registerTemplates(); $this->registerSettings(); $this->registerSearch(); } @@ -97,24 +97,6 @@ class AppServiceProvider extends ServiceProvider $registrator->register(HtmlCode::class); $registrator->register(Menu::class); $registrator->register(OrbitSlider::class); - - // register some menu extensions - // $menuExtensions = $this->app->make('registerMenuExtension'); - // $menuExtensions->register(new URL()); - } - - /** - * Register path with editable contents - */ - private function registerTemplates() - { - /** - * @var $registrator TemplateRegistrator - */ -// $registrator = $this->app->make('registerTemplateDir'); -// $registrator->setBaseDirectory('resources/views/visitor'); - -// $registrator->register(config('app.theme'), 'admin/templates.core'); } /** diff --git a/app/Providers/TemplateServiceProvider.php b/app/Providers/TemplateServiceProvider.php index d4ff4457..468453a4 100644 --- a/app/Providers/TemplateServiceProvider.php +++ b/app/Providers/TemplateServiceProvider.php @@ -3,32 +3,13 @@ namespace App\Providers; use App\Handlers\Registrators\TemplateRegistrator; -use App\Models\Module; +use App\Helpers\CurrentTemplate; use App\Models\Template; use Illuminate\Support\Facades\App; use Illuminate\Support\ServiceProvider; -use InvalidArgumentException; class TemplateServiceProvider extends ServiceProvider { - private function getTemplate() - { - // select template - try { - $template = Module::where('is_template', true) - ->where('enabled', true) - ->first(); - - if ($template) { - $template->settings = json_decode($template->module_settings); - } - } catch (\Exception $e) { - return null; - } - - return $template; - } - public function boot() { // ignore running from artisan @@ -38,28 +19,24 @@ class TemplateServiceProvider extends ServiceProvider return; } - $template = $this->getTemplate(); + $template = CurrentTemplate::get(); if (!$template) { throw new \ErrorException('Template is not set, cannot continue'); } // include files - $files = isset($template->settings->files) ? $template->settings->files : []; + $files = isset($template->module_settings->files) ? $template->module_settings->files : []; foreach ($files as $file) { include_once $file; } // register templates - $publicTemplates = call_user_func([$template->handler, 'getPublicTemplatePaths']); + $publicTemplates = call_user_func([CurrentTemplate::handler(), 'getPublicTemplatePaths']); if (!is_array($publicTemplates)) { - throw new \ErrorException($template->handler . '::getPublicTemplatePaths() must return array!'); - } - - if (empty($publicTemplates)) { - return; + throw new \ErrorException(CurrentTemplate::handler() . '::getPublicTemplatePaths() must return array!'); } /** @@ -70,16 +47,12 @@ class TemplateServiceProvider extends ServiceProvider // setup some global variables $module = strtolower($template['module']); $namespace = isset($template['namespace']) ? $template['namespace'] : strtolower($template['module']); - try { - $registrator->setBaseDirectory('resources/views/modules/' . $module); - $registrator->setNamespace($namespace); - $registrator->setModuleId(call_user_func([config($module . '.handler'), 'getModuleId'])); - // register path with current template name - $registrator->register('visitor', $template['templateName']); - } catch (InvalidArgumentException $e) { - // ignore this exception - } + // register path with current template name + + $registrator->setNamespace($namespace); + $registrator->setModuleId(call_user_func([config($module . '.handler'), 'getModuleId'])); + $registrator->register('resources/views/modules/' . $module, 'visitor', $template['templateName']); } } @@ -97,12 +70,12 @@ class TemplateServiceProvider extends ServiceProvider */ private function publishViewResources() { - $template = $this->getTemplate(); + $template = CurrentTemplate::get(); if (!$template) { return; } - $templateDir = app_path('../templates/' . $template->settings->staticName . '/Resources'); + $templateDir = base_path('templates/' . $template->module_settings->staticName . '/Resources'); $assetsDir = $templateDir . '/' . Template::ASSETS_DIRECTORY; $viewsDir = $templateDir . '/views'; diff --git a/modules/StaticPages/Providers/StaticPagesServiceProvider.php b/modules/StaticPages/Providers/StaticPagesServiceProvider.php index 5b9e181b..5e38229e 100644 --- a/modules/StaticPages/Providers/StaticPagesServiceProvider.php +++ b/modules/StaticPages/Providers/StaticPagesServiceProvider.php @@ -1,12 +1,6 @@ publishes([$config => config_path('staticpages.php')]); $this->mergeConfigFrom($config, 'staticpages'); } diff --git a/templates/Base/OnePage/Handlers/OnePage.php b/templates/Base/OnePage/Handlers/OnePage.php index 6ecaef48..9734aad7 100644 --- a/templates/Base/OnePage/Handlers/OnePage.php +++ b/templates/Base/OnePage/Handlers/OnePage.php @@ -18,6 +18,8 @@ abstract class OnePage implements TemplateHandler * Name of settings key for list of pages used on homepage */ const HOMEPAGE_PAGES_SETTINGS_KEY = 'template.onepage.homepagePages'; + protected static $homepagePagesInitialized = false; + protected static $homepagePages; /** * Register admin menu (or multiple ones) @@ -40,22 +42,28 @@ abstract class OnePage implements TemplateHandler */ public static function getPagesOnHomepage() { - $pageIds = (array)json_decode(Settings::get(self::HOMEPAGE_PAGES_SETTINGS_KEY, '[]')); + if (!self::$homepagePagesInitialized) { + $pageIds = (array)json_decode(Settings::get(self::HOMEPAGE_PAGES_SETTINGS_KEY, '[]')); - if (empty($pageIds)) { - return []; + if (empty($pageIds)) { + return []; + } + + // get all available pages + $pages = Content::whereIn('id', $pageIds); + + if (Auth::user()) { + $pages = $pages->where('status', '!=', Content::STATUS_DRAFT); + } else { + $pages = $pages->where('status', Content::STATUS_PUBLIC); + } + + self:: $homepagePages = $pages->get(); + + self::$homepagePagesInitialized = true; } - // get all available pages - $pages = Content::whereIn('id', $pageIds); - - if (Auth::user()) { - $pages = $pages->where('status', '!=', Content::STATUS_DRAFT); - } else { - $pages = $pages->where('status', Content::STATUS_PUBLIC); - } - - return $pages->get(); + return self::$homepagePages; } /**