FEATURE: prepare for installing templates

This commit is contained in:
Michal Kváček
2016-09-20 00:46:32 +02:00
parent 7a681fd7f7
commit f087da1b43
22 changed files with 397 additions and 253 deletions
+3 -5
View File
@@ -1,8 +1,7 @@
APP_ENV=testing
APP_DEBUG=true
APP_KEY=ZKZAzM23wQ6BPji6zffBjaTzZ3yW7zKQ
APP_ENV=
APP_DEBUG=
DB_HOST=localhost
DB_HOST=
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=
@@ -17,4 +16,3 @@ MAIL_PASSWORD=
SITE_URL=/
UPLOAD_URL=/public/uploads
THUMBNAILS_URL=/uploads/thumbnails
THEME=
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace App\Console\Commands;
use App\Models\Module;
use Illuminate\Console\Command;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class SetTemplate extends Command
{
/**
* The name and signature of the console command.
* @var string
*/
protected $signature = 'template:set {template}';
/**
* The console command description.
* @var string
*/
protected $description = 'Install template';
/**
* Execute the console command.
* @return mixed
*/
public function handle()
{
$template = $this->argument('template');
$templatePath = app_path('../templates/' . $template);
if (!is_dir($templatePath) || !file_exists($templatePath . '/config.php')) {
throw new NotFoundHttpException('Invalid template ' . $template . '!');
}
// try to find currently installed template
$current = Module::where('is_template', true)->first();
if ($current) {
$this->line('Template is already set up. Currently using '.trans($current->name).'.');
$confirm = $this->ask('Uninstall it and install '.$template.'? [y/n]');
if ($confirm === 'y') {
$this->line('Uninstalling '.$current->name.'.');
$current->uninstall();
} else {
$this->line('Aborting installation.');
return;
}
}
// install template
$config = @include $templatePath . '/config.php';
try {
$config['staticName'] = $template;
Module::install($config['name'], $config['alias'], $config['description'], $config['handler'], false, $config);
} catch (\Exception $e) {
$this->error('Cannot install template '.$template.'.');
return;
}
// theme written
$this->line('Template successfully setup.');
// $this->line('');
// $this->line(' ** PUBLISHING ASSETS AND VIEWS **');
// // publish assets and views for module and theme
// $this->call('vendor:publish', ['--tag' => ['public-assets'], '--force' => true]);
// $this->call('vendor:publish', ['--tag' => ['module-views'], '--force' => true]);
// $this->call('vendor:publish');
}
}
-70
View File
@@ -1,70 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class SetTheme extends Command
{
/**
* The name and signature of the console command.
* @var string
*/
protected $signature = 'theme:set {theme_name}';
/**
* The console command description.
* @var string
*/
protected $description = 'Set theme for visitor area';
/**
* Create a new command instance.
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
* @return mixed
*/
public function handle()
{
$theme = $this->argument('theme_name');
if (!is_dir(resource_path('views/visitor/' . $theme))) {
throw new NotFoundHttpException('Invalid theme ' . $theme . '!');
}
// load .env file
$envFile = base_path('.env');
$env = file_get_contents($envFile);
if (!Str::contains($env, 'THEME=')) {
$env = sprintf("%s\nTHEME=%s\n", $env, $theme);
} else {
$env = preg_replace('/THEME=(.*)/i', 'THEME=' . $theme, $env, -1, $cnt);
}
// try to write content
$bytesWritten = file_put_contents($envFile, $env);
// check if write was successfull
if (!$bytesWritten) {
throw new \Exception('Cannot write to ' . base_path('.env') . '. Add THEME=' . $theme . ' to your .env file manualy.');
}
// theme written
$this->line('Theme successfully setup.');
$this->line('');
$this->line(' ** PUBLISHING ASSETS AND VIEWS **');
// publish assets and views for module and theme
$this->call('vendor:publish', ['--tag' => ['public-assets'], '--force' => true]);
$this->call('vendor:publish', ['--tag' => ['module-views'], '--force' => true]);
$this->call('vendor:publish');
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ class Kernel extends ConsoleKernel
Commands\Translations::class,
Commands\TranslateAll::class,
Commands\InitDatabaseSchema::class,
Commands\SetTheme::class,
Commands\SetTemplate::class,
AddLanguage::class
];
+1 -1
View File
@@ -5,7 +5,7 @@ use App\Models\User;
interface BaseModuleHandler
{
public static function getModuleId();
// public static function getModuleId();
/**
* Register admin menu (or multiple ones)
@@ -0,0 +1,11 @@
<?php
namespace App\Handlers\Contracts;
use App\Models\Module;
interface TemplateHandler extends BaseModuleHandler
{
public static function uninstall(Module $template);
public static function getPublicTemplatePaths();
}
@@ -187,7 +187,6 @@ class TemplateRegistrator
$registeredTemplates = Templates::getWithTranslations();
if (!in_array($templateName, $registeredTemplates)) {
$params = [
'template_name' => $templateName,
'name' => $templateName,
@@ -197,8 +196,6 @@ class TemplateRegistrator
'editable' => 1
];
echo 'ukladam do db '.$templateName."\n";
// save template into database
$newTemplate = Template::create($params);
+34 -3
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Handlers\Contracts\TemplateHandler;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
@@ -20,7 +21,8 @@ class Module extends Model
'module_settings',
'enabled',
'support_categories',
'manages_content'
'manages_content',
'is_template'
];
protected $guarded = [];
@@ -45,6 +47,7 @@ class Module extends Model
}
$managesContent = $handler ? in_array('App\Handlers\Contracts\AppHandler', class_implements($handler)) : false;
$isTemplate = $handler ? in_array(TemplateHandler::class, class_implements($handler)) : false;
$supportCategories = $managesContent ? call_user_func([$handler, 'supportCategories']) : false;
if ($parentModuleId) {
@@ -62,8 +65,9 @@ class Module extends Model
'support_categories' => $supportCategories,
'alias' => $alias,
'module_settings' => json_encode($settings),
'parent_id' => $parentModuleId,
'enabled' => 1
'parent_id' => $parentModuleId ? $parentModuleId : null,
'enabled' => 1,
'is_template' => $isTemplate
]);
// install something module-specific
@@ -73,4 +77,31 @@ class Module extends Model
return $module;
}
public function uninstall() {
// check if user does not want to install module in runtime
if (!App::runningInConsole()) {
throw new \ErrorException('Modules can be uninstalled only via Artisan!');
}
// delete everything in /resources/views/visitor
$directories = \File::directories(resource_path('views/visitor'));
foreach ($directories as $directory) {
$success = \File::deleteDirectory($directory);
if (!$success) {
throw new \ErrorException('Cannot delete '.$directory);
}
}
$handler = $this->handler;
if ($handler) {
call_user_func([$handler, 'uninstall'], $this);
}
$this->delete();
}
}
+3 -10
View File
@@ -39,13 +39,6 @@ class AppServiceProvider extends ServiceProvider
$this->registerTemplates();
$this->registerSettings();
$this->registerSearch();
// check if given template is valid
$theme = config('app.theme');
$themeDir = resource_path('views/visitor/' . $theme);
if (!$theme || empty($theme) || !is_dir($themeDir)) {
throw new InvalidArgumentException('No or invalid theme set! Use artisan theme:set or edit .env file manually and include THEME option, please');
}
}
/**
@@ -120,10 +113,10 @@ class AppServiceProvider extends ServiceProvider
/**
* @var $registrator TemplateRegistrator
*/
$registrator = $this->app->make('registerTemplateDir');
$registrator->setBaseDirectory('resources/views/visitor');
// $registrator = $this->app->make('registerTemplateDir');
// $registrator->setBaseDirectory('resources/views/visitor');
$registrator->register(config('app.theme'), 'admin/templates.core');
// $registrator->register(config('app.theme'), 'admin/templates.core');
}
/**
@@ -5,18 +5,13 @@ use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Symfony\Component\Translation\Translator;
class LaravelLocalizationServiceProvider extends ServiceProvider
{
public function register()
{
try {
$languages = DB::table('languages')
->get();
} catch (\Exception $e) {
$languages = [];
}
$supportedLocales = [];
if (empty($languages)) {
@@ -28,11 +23,7 @@ class LaravelLocalizationServiceProvider extends ServiceProvider
];
// create default language
try {
Language::create($supportedLocales[config('app.locale')]);
} catch (\Exception $e) {
// ignore, table languages probably does not exist.
}
}
foreach ($languages as $language) {
+3 -2
View File
@@ -21,7 +21,8 @@ class ModuleManager extends ServiceProvider
}
// this service provider needs published config - config is merged right after this service provider
$modules = Module::get();
$modules = Module::where('is_template', false)
->get();
// iterate over all modules and enable or disable them
foreach ($modules as $module) {
@@ -58,7 +59,7 @@ class ModuleManager extends ServiceProvider
// check if module config is writable
if (!is_writable(dirname($path))) {
Log::warning('Cannot write to '.$path);
Log::warning('Cannot write to ' . $path);
return;
}
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace App\Providers;
use App\Handlers\Registrators\TemplateRegistrator;
use App\Models\Module;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
use InvalidArgumentException;
class TemplateServiceProvider extends ServiceProvider
{
public function boot()
{
if (App::runningInConsole())
return;
parent::boot();
// select template
$template = Module::where('is_template', true)
->first();
if (!$template) {
throw new \ErrorException('Template is not set, cannot continue');
}
$templateSettings = json_decode($template->module_settings);
// include files
$files = isset($templateSettings->files) ? $templateSettings->files : [];
foreach ($files as $file) {
include_once app_path('../templates/' . $templateSettings->staticName . '/' . $file);
}
// register templates
$publicTemplates = call_user_func([$template->handler, 'getPublicTemplatePaths']);
if (!is_array($publicTemplates)) {
throw new \ErrorException($template->handler . '::getPublicTemplatePaths() must return array!');
}
if (empty($publicTemplates)) {
return;
}
/**
* @var $registrator TemplateRegistrator
*/
$registrator = $this->app->make('registerTemplateDir');
foreach ($publicTemplates as $template) {
// setup some global variables
// try {
// $registrator->setBaseDirectory('resources/views/modules/gallery/visitor');
// $registrator->setNamespace('gallery');
// $registrator->setModuleId(call_user_func([config('gallery.handler'), 'getModuleId']));
//
// // register path with current template name
// $registrator->register(config('app.theme'), 'gallery::admin/adminMenu.templatePath');
// } catch (InvalidArgumentException $e) {
// // ignore this exception
// }
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
}
}
+2 -1
View File
@@ -30,7 +30,8 @@
],
"psr-4": {
"App\\": "app/",
"Modules\\": "modules/"
"Modules\\": "modules/",
"Templates\\": "templates/"
}
},
"scripts": {
+3 -2
View File
@@ -159,6 +159,7 @@ return [
Pingpong\Modules\ModulesServiceProvider::class,
Pingpong\Menus\MenusServiceProvider::class,
App\Providers\SubmodulesManager::class,
\App\Providers\TemplateServiceProvider::class,
Franzose\ClosureTable\ClosureTableServiceProvider::class,
\Watson\Sitemap\SitemapServiceProvider::class,
@@ -171,7 +172,7 @@ return [
App\Providers\RouteServiceProvider::class,
App\Providers\GlobalViewDataProvider::class,
],
],
/*
|--------------------------------------------------------------------------
| Class Aliases
@@ -220,6 +221,6 @@ return [
'LaravelLocalization' => Mcamara\LaravelLocalization\Facades\LaravelLocalization::class,
'View' => Illuminate\Support\Facades\View::class,
],
],
];
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
class SaveTemplatesIntoModulesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('modules', function (Blueprint $table){
$table->boolean('is_template')->default(false)->comment('Templates can be treated as modules.');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('modules', function (Blueprint $table){
$table->dropColumn('is_template');
});
}
}
@@ -63,21 +63,21 @@ class ArticleServiceProvider extends ServiceProvider {
return $path . '/modules/article';
}, \Config::get('view.paths')), [$sourcePath]), 'article');
/**
* @var $registrator TemplateRegistrator
*/
try {
// setup some global variables
$registrator = $this->app->make('registerTemplateDir');
$registrator->setBaseDirectory('resources/views/modules/article/visitor');
$registrator->setNamespace('article');
$registrator->setModuleId(Article::getModuleId());
// register path with current template name
$registrator->register(config('app.theme'), 'article::admin/adminMenu.templatePath');
} catch (InvalidArgumentException $e) {
// ignore this exception
}
// /**
// * @var $registrator TemplateRegistrator
// */
// try {
// // setup some global variables
// $registrator = $this->app->make('registerTemplateDir');
// $registrator->setBaseDirectory('resources/views/modules/article/visitor');
// $registrator->setNamespace('article');
// $registrator->setModuleId(Article::getModuleId());
//
// // register path with current template name
// $registrator->register(config('app.theme'), 'article::admin/adminMenu.templatePath');
// } catch (InvalidArgumentException $e) {
// // ignore this exception
// }
}
/**
@@ -63,21 +63,21 @@ class ContactFormServiceProvider extends ServiceProvider
return $path . '/modules/contactform';
}, \Config::get('view.paths')), [$sourcePath]), 'contactform');
/**
* @var $registrator TemplateRegistrator
*/
$registrator = $this->app->make('registerTemplateDir');
try {
// setup some global variables
$registrator->setBaseDirectory('resources/views/modules/contactform/visitor');
$registrator->setNamespace('contactform');
$registrator->setModuleId(call_user_func([config('contactform.handler'), 'getModuleId']));
// register path with current template name
$registrator->register(config('app.theme'), 'contactform::admin/adminMenu.templatePath');
} catch (InvalidArgumentException $e) {
// ignore this exception
}
// /**
// * @var $registrator TemplateRegistrator
// */
// $registrator = $this->app->make('registerTemplateDir');
// try {
// // setup some global variables
// $registrator->setBaseDirectory('resources/views/modules/contactform/visitor');
// $registrator->setNamespace('contactform');
// $registrator->setModuleId(call_user_func([config('contactform.handler'), 'getModuleId']));
//
// // register path with current template name
// $registrator->register(config('app.theme'), 'contactform::admin/adminMenu.templatePath');
// } catch (InvalidArgumentException $e) {
// // ignore this exception
// }
}
/**
@@ -63,21 +63,21 @@ class GalleryServiceProvider extends ServiceProvider
return $path.'/modules/gallery';
}, \Config::get('view.paths')), [$sourcePath]), 'gallery');
/**
* @var $registrator TemplateRegistrator
*/
$registrator = $this->app->make('registerTemplateDir');
try {
// setup some global variables
$registrator->setBaseDirectory('resources/views/modules/gallery/visitor');
$registrator->setNamespace('gallery');
$registrator->setModuleId(call_user_func([config('gallery.handler'), 'getModuleId']));
// register path with current template name
$registrator->register(config('app.theme'), 'gallery::admin/adminMenu.templatePath');
} catch (InvalidArgumentException $e) {
// ignore this exception
}
// /**
// * @var $registrator TemplateRegistrator
// */
// $registrator = $this->app->make('registerTemplateDir');
// try {
// // setup some global variables
// $registrator->setBaseDirectory('resources/views/modules/gallery/visitor');
// $registrator->setNamespace('gallery');
// $registrator->setModuleId(call_user_func([config('gallery.handler'), 'getModuleId']));
//
// // register path with current template name
// $registrator->register(config('app.theme'), 'gallery::admin/adminMenu.templatePath');
// } catch (InvalidArgumentException $e) {
// // ignore this exception
// }
}
/**
@@ -38,18 +38,6 @@ class StaticPagesServiceProvider extends ServiceProvider
{
}
// /**
// * Method for installing module into database
// */
// protected function install()
// {
// $handler = config('staticpages.handler');
// $installedModules = ModulesHandlerToId::getWithTranslations();
// if (!isset($installedModules[$handler])) {
// Module::install('staticpages::module.name', 'staticpages', 'staticpages::module.description');
// }
// }
/**
* Register config.
*
@@ -82,17 +70,17 @@ class StaticPagesServiceProvider extends ServiceProvider
* @var $registrator TemplateRegistrator
*/
$registrator = $this->app->make('registerTemplateDir');
try {
// setup some global variables
$registrator->setBaseDirectory('resources/views/modules/staticpages/visitor');
$registrator->setNamespace('staticpages');
$registrator->setModuleId(call_user_func([config('staticpages.handler'), 'getModuleId']));
// register path with current template name
$registrator->register(config('app.theme'), 'staticpages::admin.templatePath');
} catch (InvalidArgumentException $e) {
// ignore this exception
}
// try {
// // setup some global variables
// $registrator->setBaseDirectory('resources/views/modules/staticpages/visitor');
// $registrator->setNamespace('staticpages');
// $registrator->setModuleId(call_user_func([config('staticpages.handler'), 'getModuleId']));
//
// // register path with current template name
// $registrator->register(config('app.theme'), 'staticpages::admin.templatePath');
// } catch (InvalidArgumentException $e) {
// // ignore this exception
// }
}
/**
@@ -0,0 +1,8 @@
<?php
namespace Templates\Base\OnePage\Handlers;
use App\Handlers\Contracts\TemplateHandler;
abstract class OnePage implements TemplateHandler
{
}
+10
View File
@@ -0,0 +1,10 @@
<?php
return [
'handler' => \Templates\Base\OnePage\Handlers\OnePage::class,
'name' => 'Sablona',
'alias' => 'sablona',
'description' => 'Sablona jednostrankova',
'files' => [
'routes.php'
]
];
+6
View File
@@ -0,0 +1,6 @@
<?php
Route::group(['middleware' => 'web', 'prefix' => 'test', 'namespace' => 'Modules\Blog\Comments\Http\Controllers'], function()
{
Route::get('/neco-neco', 'CommentsController@index')->name('template.route');
});