Browse Source

Reformat some code

master
Egorka 6 years ago
parent
commit
0ac26e5eca
  1. 4
      .editorconfig
  2. 49
      README.md
  3. 218
      backend/config/main.php
  4. 1
      backend/messages/ru/user.php
  5. 76
      common/config/main.php
  6. 87
      common/modules/banners/BannersModule.php
  7. 68
      common/modules/banners/controllers/BannerController.php
  8. 89
      common/modules/banners/controllers/manage/BannerController.php
  9. 79
      common/modules/banners/controllers/manage/PlaceController.php
  10. 218
      common/modules/banners/entities/Banner.php
  11. 112
      common/modules/banners/entities/BannerPlace.php
  12. 7
      common/modules/banners/entities/queries/BannerPlaceQuery.php
  13. 16
      common/modules/banners/entities/queries/BannerQuery.php
  14. 114
      common/modules/banners/forms/BannerForm.php
  15. 29
      common/modules/banners/forms/BannerPlaceForm.php
  16. 11
      common/modules/banners/forms/search/BannerSearch.php
  17. 17
      common/modules/banners/forms/search/PlaceSearch.php
  18. 88
      common/modules/banners/helpers/BannerHelper.php
  19. 5
      common/modules/banners/manifest.php
  20. 2
      common/modules/banners/repositories/BannerPlaceRepository.php
  21. 2
      common/modules/banners/repositories/BannerRepository.php
  22. 85
      common/modules/banners/services/BannerManageService.php
  23. 25
      common/modules/banners/services/BannerPlaceManageService.php
  24. 184
      common/modules/banners/views/manage/banner/_form.php
  25. 55
      common/modules/banners/widgets/BannerWidget.php
  26. 95
      common/modules/blog/entities/BlogCategory.php
  27. 6
      common/modules/blog/forms/search/BlogPostSearch.php
  28. 5
      common/modules/blog/manifest.php
  29. 129
      common/modules/blog/services/BlogPostManageService.php
  30. 10
      common/modules/blog/views/manage/post/_form.php
  31. 67
      common/modules/blog/views/manage/post/index.php
  32. 2
      common/modules/blog/widgets/views/categories/categories.php
  33. 5
      common/modules/forms/manifest.php
  34. 5
      common/modules/languages/manifest.php
  35. 2
      common/modules/pages/forms/PageSearch.php
  36. 40
      core/forms/MetaForm-org.php
  37. 247
      core/services/ModuleService.php
  38. 2
      core/services/auth/AuthService.php
  39. 2
      frontend/web/themes/start/modules/blog/views/post/post.php

4
.editorconfig

@ -34,8 +34,8 @@ indent_style=space
indent_size=2 indent_size=2
[{*.hphp,*.phtml,*.module,*.php,*.php5,*.php4,*.inc}] [{*.hphp,*.phtml,*.module,*.php,*.php5,*.php4,*.inc}]
indent_style=tab indent_style=space
tab_width=4 indent_size=4
[*.less] [*.less]
indent_style=space indent_style=space

49
README.md

@ -1,50 +1,5 @@
# ZxCMS - Yii2 site management system # Zertex CMS - Site management system based on Yii2 framework
Yii 2 Advanced Project Template is a skeleton [Yii 2](http://www.yiiframework.com/) application best for ## Deep alpha version
developing complex Web applications with multiple tiers.
The template includes three tiers: front end, back end, and console, each of which
is a separate Yii application.
The template is designed to work in a team development environment. It supports
deploying the application in different environments.
Documentation is at [docs/guide/README.md](docs/guide/README.md). Documentation is at [docs/guide/README.md](docs/guide/README.md).
DIRECTORY STRUCTURE
-------------------
```
common
config/ contains shared configurations
mail/ contains view files for e-mails
models/ contains model classes used in both backend and frontend
tests/ contains tests for common classes
console
config/ contains console configurations
controllers/ contains console controllers (commands)
migrations/ contains database migrations
models/ contains console-specific model classes
runtime/ contains files generated during runtime
backend
assets/ contains application assets such as JavaScript and CSS
config/ contains backend configurations
controllers/ contains Web controller classes
models/ contains backend-specific model classes
runtime/ contains files generated during runtime
tests/ contains tests for backend application
views/ contains view files for the Web application
web/ contains the entry script and Web resources
frontend
assets/ contains application assets such as JavaScript and CSS
config/ contains frontend configurations
controllers/ contains Web controller classes
models/ contains frontend-specific model classes
runtime/ contains files generated during runtime
tests/ contains tests for frontend application
views/ contains view files for the Web application
web/ contains the entry script and Web resources
widgets/ contains frontend widgets
vendor/ contains dependent 3rd-party packages
environments/ contains environment-based overrides
```

218
backend/config/main.php

@ -7,23 +7,23 @@ $params = array_merge(
); );
return [ return [
'id' => 'app-backend', 'id' => 'app-backend',
'language' => 'ru', 'language' => 'ru',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'aliases' => [ 'aliases' => [
'@staticRoot' => $params['staticPath'], '@staticRoot' => $params['staticPath'],
'@static' => $params['staticHostInfo'], '@static' => $params['staticHostInfo'],
], ],
'controllerNamespace' => 'backend\controllers', 'controllerNamespace' => 'backend\controllers',
'bootstrap' => [ 'bootstrap' => [
'log', 'log',
'common\bootstrap\SetUp', 'common\bootstrap\SetUp',
'backend\bootstrap\SetUp', 'backend\bootstrap\SetUp',
], ],
'modules' => [ 'modules' => [
'elfinder' => [ 'elfinder' => [
'class' => 'core\components\elfinder\ElFinderModule', 'class' => 'core\components\elfinder\ElFinderModule',
], ],
], ],
/*'controllerMap' => [ /*'controllerMap' => [
'elfinder' => [ 'elfinder' => [
@ -46,109 +46,109 @@ return [
], ],
], ],
],*/ ],*/
'controllerMap' => [ 'controllerMap' => [
'elfinder' => [ 'elfinder' => [
'class' => 'zertex\elfinder\Controller', 'class' => 'zertex\elfinder\Controller',
'access' => ['@'], 'access' => ['@'],
'plugin' => [ 'plugin' => [
[ [
'class'=>'\zertex\elfinder\plugin\Sluggable', 'class' => '\zertex\elfinder\plugin\Sluggable',
'lowercase' => true, 'lowercase' => true,
'replacement' => '-' 'replacement' => '-'
] ]
], ],
'roots' => [ 'roots' => [
[ [
'baseUrl'=>'@static', 'baseUrl' => '@static',
'basePath'=>'@staticRoot', 'basePath' => '@staticRoot',
'path' => 'files', 'path' => 'files',
'name' => 'Global' 'name' => 'Global'
], ],
], ],
], ],
], ],
'components' => [ 'components' => [
'request' => [ 'request' => [
'baseUrl' => '', 'baseUrl' => '',
'csrfParam' => '_csrf-backend', 'csrfParam' => '_csrf-backend',
'cookieValidationKey' => $params['cookieValidationKey'], 'cookieValidationKey' => $params['cookieValidationKey'],
], ],
'user' => [ 'user' => [
'identityClass' => 'common\auth\Identity', 'identityClass' => 'common\auth\Identity',
'enableAutoLogin' => true, 'enableAutoLogin' => true,
'identityCookie' => [ 'identityCookie' => [
'name' => '_identity', 'name' => '_identity',
'httpOnly' => true, 'httpOnly' => true,
'domain' => $params['cookieDomain'], 'domain' => $params['cookieDomain'],
], ],
'loginUrl' => ['auth/login'], 'loginUrl' => ['auth/login'],
], ],
'session' => [ 'session' => [
'name' => '_session', 'name' => '_session',
'class' => 'yii\web\DbSession', 'class' => 'yii\web\DbSession',
'writeCallback' => function($session){ 'writeCallback' => function ($session) {
return [ return [
'user_id' => Yii::$app->user->id 'user_id' => Yii::$app->user->id
]; ];
}, },
'cookieParams' => [ 'cookieParams' => [
'domain' => $params['cookieDomain'], 'domain' => $params['cookieDomain'],
'httpOnly' => true, 'httpOnly' => true,
], ],
], ],
'log' => [ 'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0, 'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [ 'targets' => [
[ [
'class' => 'yii\log\FileTarget', 'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'], 'levels' => ['error', 'warning'],
], ],
], ],
], ],
'errorHandler' => [ 'errorHandler' => [
'errorAction' => 'site/error', 'errorAction' => 'site/error',
], ],
'backendUrlManager' => require __DIR__ . '/urlManager.php', 'backendUrlManager' => require __DIR__ . '/urlManager.php',
'frontendUrlManager' => require __DIR__ . '/../../frontend/config/urlManager.php', 'frontendUrlManager' => require __DIR__ . '/../../frontend/config/urlManager.php',
'urlManager' => function () { 'urlManager' => function () {
return Yii::$app->get('backendUrlManager'); return Yii::$app->get('backendUrlManager');
}, },
'i18n' => [ 'i18n' => [
'translations' => [ 'translations' => [
'main' => [ 'main' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@backend/messages', 'basePath' => '@backend/messages',
], ],
'dashboard' => [ 'dashboard' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@backend/messages', 'basePath' => '@backend/messages',
], ],
'menu' => [ 'menu' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@backend/messages', 'basePath' => '@backend/messages',
], ],
'page' => [ 'page' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@backend/messages', 'basePath' => '@backend/messages',
], ],
'user' => [ 'user' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@backend/messages', 'basePath' => '@backend/messages',
], ],
'post' => [ 'post' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@backend/messages', 'basePath' => '@backend/messages',
], ],
'buttons' => [ 'buttons' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@backend/messages', 'basePath' => '@backend/messages',
], ],
'slider' => [ 'slider' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@backend/messages', 'basePath' => '@backend/messages',
], ],
], ],
], ],
], ],
'params' => $params, 'params' => $params,
]; ];

1
backend/messages/ru/user.php

@ -39,4 +39,5 @@ return [
'Registered: {date}' => 'Дата регистрации: {date}', 'Registered: {date}' => 'Дата регистрации: {date}',
'Remember Me' => 'Запомнить меня', 'Remember Me' => 'Запомнить меня',
'Dashboard Language' => 'Язык панели управления', 'Dashboard Language' => 'Язык панели управления',
'Undefined user or password.' => 'Ошибка в имени или пароле',
]; ];

76
common/config/main.php

@ -1,51 +1,51 @@
<?php <?php
return [ return [
'aliases' => [ 'aliases' => [
'@bower' => '@vendor/bower-asset', '@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset', '@npm' => '@vendor/npm-asset',
], ],
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor', 'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'controllerMap' => [ 'controllerMap' => [
// Common migrations for the whole application // Common migrations for the whole application
'migrate' => [ 'migrate' => [
'class' => 'yii\console\controllers\MigrateController', 'class' => 'yii\console\controllers\MigrateController',
'migrationPath' => [ 'migrationPath' => [
'@console/migrations', '@console/migrations',
], ],
], ],
], ],
'components' => [ 'components' => [
'cache' => [ 'cache' => [
'class' => 'yii\caching\FileCache', 'class' => 'yii\caching\FileCache',
'cachePath' => '@common/runtime/cache', 'cachePath' => '@common/runtime/cache',
], ],
'authManager' => [ 'authManager' => [
'class' => 'yii\rbac\DbManager', 'class' => 'yii\rbac\DbManager',
'itemTable' => '{{%auth_items}}', 'itemTable' => '{{%auth_items}}',
'itemChildTable' => '{{%auth_item_children}}', 'itemChildTable' => '{{%auth_item_children}}',
'assignmentTable' => '{{%auth_assignments}}', 'assignmentTable' => '{{%auth_assignments}}',
'ruleTable' => '{{%auth_rules}}', 'ruleTable' => '{{%auth_rules}}',
],
'queue' => [
//'class' => 'yii\queue\redis\Queue',
//'as log' => 'yii\queue\LogBehavior',
'class' => \yii\queue\file\Queue::class,
//'path' => '@runtime/queue',
'path' => '@common/runtime/queue',
],
'avatar' => [
'class' => \zertex\avatar_generator\AvatarGenerator::class,
'images_folder' => '@staticRoot/images/avatars',
'images_url' => '@static/images/avatars',
'size_width' => 300, // default: 300
'font_size' => 200, // default: 200
'salt' => 'my_cms_salt', // salt for image file names
'texture' => ['sun', 'rain'], // texture name
'texture_over_image' => false,
'text_over_image' => false,
],
'moduleManager' => [
'class' => \core\components\modules\ModuleManager::class,
], ],
'queue' => [
//'class' => 'yii\queue\redis\Queue',
//'as log' => 'yii\queue\LogBehavior',
'class' => \yii\queue\file\Queue::class,
//'path' => '@runtime/queue',
'path' => '@common/runtime/queue',
],
'avatar' => [
'class' => \zertex\avatar_generator\AvatarGenerator::class,
'images_folder' => '@staticRoot/images/avatars',
'images_url' => '@static/images/avatars',
'size_width' => 300, // default: 300
'font_size' => 200, // default: 200
'salt' => 'my_cms_salt', // salt for image file names
'texture' => ['sun', 'rain'], // texture name
'texture_over_image' => false,
'text_over_image' => false,
],
'moduleManager' => [
'class' => \core\components\modules\ModuleManager::class,
],
], ],
]; ];

87
common/modules/banners/BannersModule.php

@ -5,7 +5,6 @@ namespace common\modules\banners;
use core\components\modules\ModuleInterface; use core\components\modules\ModuleInterface;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
/** /**
* blog module definition class * blog module definition class
*/ */
@ -26,52 +25,52 @@ class BannersModule extends \yii\base\Module implements ModuleInterface
// custom initialization code goes here // custom initialization code goes here
} }
public function bootstrap($app) public function bootstrap($app)
{ {
// add migration path // add migration path
$app->controllerMap['migrate']['migrationPath'][] = '@common/modules/banners/migrations'; $app->controllerMap['migrate']['migrationPath'][] = '@common/modules/banners/migrations';
// add search rules // add search rules
$app->params['search_rules'][] = "SELECT title, title as content, CONCAT('/banners/manage/banner/view/', id) AS url FROM {{banners}}"; $app->params['search_rules'][] = "SELECT title, title as content, CONCAT('/banners/manage/banner/view/', id) AS url FROM {{banners}}";
$app->getUrlManager()->addRules([ $app->getUrlManager()->addRules([
'banner/view' => 'banners/banner/view', 'banner/view' => 'banners/banner/view',
'banner/click' => 'banners/banner/click', 'banner/click' => 'banners/banner/click',
]); ]);
$app->getUrlManager()->addRules([ $app->getUrlManager()->addRules([
'banners/manage/banner/view/<id:\d+>' => 'banners/manage/banner/view', 'banners/manage/banner/view/<id:\d+>' => 'banners/manage/banner/view',
]); ]);
// add languages // add languages
$app->getI18n()->translations = ArrayHelper::merge($app->getI18n()->translations, [ $app->getI18n()->translations = ArrayHelper::merge($app->getI18n()->translations, [
'banners' => [ 'banners' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@common/modules/banners/messages', 'basePath' => '@common/modules/banners/messages',
], ],
]); ]);
// add menu items // add menu items
if (basename(\Yii::$app->getBasePath()) === 'backend') { if (basename(\Yii::$app->getBasePath()) === 'backend') {
$app->params['adminMenu'][] = [ $app->params['adminMenu'][] = [
'label' => \Yii::t( 'banners', 'Banners' ), 'label' => \Yii::t('banners', 'Banners'),
'icon' => 'flag', 'icon' => 'flag',
'items' => [ 'items' => [
[ [
'label' => \Yii::t( 'banners', 'Banners' ), 'label' => \Yii::t('banners', 'Banners'),
'icon' => 'caret-right', 'icon' => 'caret-right',
'url' => [ '/banners/manage/banner/index' ], 'url' => ['/banners/manage/banner/index'],
//'active' => \Yii::$app->controller->getUniqueId() == 'banners/manage/banner' //'active' => \Yii::$app->controller->getUniqueId() == 'banners/manage/banner'
], ],
[ [
'label' => \Yii::t( 'banners', 'Places' ), 'label' => \Yii::t('banners', 'Places'),
'icon' => 'caret-right', 'icon' => 'caret-right',
'url' => [ '/banners/manage/place/index' ], 'url' => ['/banners/manage/place/index'],
//'active' => \Yii::$app->controller->getUniqueId() == 'banners/manage/place' //'active' => \Yii::$app->controller->getUniqueId() == 'banners/manage/place'
], ],
], ],
'visible' => $app->user->can( 'admin' ) || \Yii::$app->user->can( 'BannersManagement' ), 'visible' => $app->user->can('admin') || \Yii::$app->user->can('BannersManagement'),
]; ];
} }
} }
} }

68
common/modules/banners/controllers/BannerController.php

@ -6,7 +6,6 @@
namespace common\modules\banners\controllers; namespace common\modules\banners\controllers;
use common\modules\banners\entities\Banner; use common\modules\banners\entities\Banner;
use common\modules\banners\services\BannerManageService; use common\modules\banners\services\BannerManageService;
use frontend\components\FrontendController; use frontend\components\FrontendController;
@ -14,36 +13,37 @@ use yii\web\NotFoundHttpException;
class BannerController extends FrontendController class BannerController extends FrontendController
{ {
private $service; private $_service;
public function __construct( string $id, $module, BannerManageService $service, array $config = [] ) { public function __construct(string $id, $module, BannerManageService $service, array $config = [])
parent::__construct( $id, $module, $config ); {
$this->service = $service; parent::__construct($id, $module, $config);
} $this->_service = $service;
}
public function actionView()
{ public function actionView()
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT); {
if (\Yii::$app->request->isAjax && $id) { $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
$banner = $this->findModel( $id ); if (\Yii::$app->request->isAjax && $id) {
$this->service->addView( $banner ); $banner = $this->findModel($id);
} $this->_service->addView($banner);
} }
}
public function actionClick()
{ public function actionClick()
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT); {
if (\Yii::$app->request->isAjax && $id) { $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
$banner = $this->findModel( $id ); if (\Yii::$app->request->isAjax && $id) {
$this->service->addClick( $banner ); $banner = $this->findModel($id);
} $this->_service->addClick($banner);
} }
}
protected function findModel($id): Banner
{ protected function findModel($id): Banner
if (($model = Banner::findOne($id)) !== null) { {
return $model; if (($model = Banner::findOne($id)) !== null) {
} return $model;
throw new NotFoundHttpException('The requested banner does not exist.'); }
} throw new NotFoundHttpException('The requested banner does not exist.');
} }
}

89
common/modules/banners/controllers/manage/BannerController.php

@ -14,32 +14,32 @@ use Yii;
class BannerController extends Controller class BannerController extends Controller
{ {
private $service; private $_service;
public function __construct($id, $module, BannerManageService $service, $config = []) public function __construct($id, $module, BannerManageService $service, $config = [])
{ {
parent::__construct($id, $module, $config); parent::__construct($id, $module, $config);
$this->service = $service; $this->_service = $service;
} }
public function behaviors(): array public function behaviors(): array
{ {
return [ return [
'access' => [ 'access' => [
'class' => AccessControl::class, 'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['BannersManagement'], 'roles' => ['BannersManagement'],
], ],
[ // all the action are accessible to admin [ // all the action are accessible to admin
'allow' => true, 'allow' => true,
'roles' => ['admin'], 'roles' => ['admin'],
], ],
], ],
], ],
'verbs' => [ 'verbs' => [
'class' => VerbFilter::class, 'class' => VerbFilter::class,
'actions' => [ 'actions' => [
'delete' => ['POST'], 'delete' => ['POST'],
], ],
@ -52,21 +52,21 @@ class BannerController extends Controller
*/ */
public function actionIndex() public function actionIndex()
{ {
$searchModel = new BannerSearch(); $searchModel = new BannerSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams); $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [ return $this->render('index', [
'searchModel' => $searchModel, 'searchModel' => $searchModel,
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
]); ]);
} }
/** /**
* @param $id * @param $id
* *
* @return string * @return string
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function actionView($id) public function actionView($id)
{ {
return $this->render('view', [ return $this->render('view', [
@ -83,36 +83,38 @@ class BannerController extends Controller
if ($form->load(Yii::$app->request->post()) && $form->validate()) { if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try { try {
$form = $this->service->create($form); $form = $this->_service->create($form);
return $this->redirect(['view', 'id' => $form->id]); return $this->redirect(['view', 'id' => $form->id]);
} catch (\DomainException $e) { } catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e); Yii::$app->errorHandler->logException($e);
Yii::$app->session->setFlash('error', $e->getMessage()); Yii::$app->session->setFlash('error', $e->getMessage());
} }
} else {
$form->active = $form->active ?: Banner::STATUS_ACTIVE;
} }
else {
$form->active = $form->active ?: Banner::STATUS_ACTIVE;
}
return $this->render('create', [ return $this->render('create', [
'model' => $form, 'model' => $form,
]); ]);
} }
/** /**
* @param $id * @param $id
* *
* @return string|\yii\web\Response * @return string|\yii\web\Response
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function actionUpdate($id) public function actionUpdate($id)
{ {
$banner = $this->findModel($id); $banner = $this->findModel($id);
$form = new BannerForm($banner); $form = new BannerForm($banner);
$form->start_at = date('d.m.Y H:i:s', $form->start_at); $form->start_at = date('d.m.Y H:i:s', $form->start_at);
$form->end_at = date('d.m.Y H:i:s', $form->end_at); $form->end_at = date('d.m.Y H:i:s', $form->end_at);
if ($form->load(Yii::$app->request->post()) && $form->validate()) { if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try { try {
$this->service->edit($banner->id, $form); $this->_service->edit($banner->id, $form);
return $this->redirect(['view', 'id' => $banner->id]); return $this->redirect(['view', 'id' => $banner->id]);
} catch (\DomainException $e) { } catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e); Yii::$app->errorHandler->logException($e);
@ -121,28 +123,31 @@ class BannerController extends Controller
} }
return $this->render('update', [ return $this->render('update', [
'model' => $form, 'model' => $form,
'banner' => $banner, 'banner' => $banner,
]); ]);
} }
/** /**
* @param integer $id * @param integer $id
*
* @return mixed * @return mixed
*/ */
public function actionDelete($id) public function actionDelete($id)
{ {
try { try {
$this->service->remove($id); $this->_service->remove($id);
} catch (\DomainException $e) { } catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e); Yii::$app->errorHandler->logException($e);
Yii::$app->session->setFlash('error', $e->getMessage()); Yii::$app->session->setFlash('error', $e->getMessage());
} }
return $this->redirect(['index']); return $this->redirect(['index']);
} }
/** /**
* @param integer $id * @param integer $id
*
* @return Banner the loaded model * @return Banner the loaded model
* @throws NotFoundHttpException if the model cannot be found * @throws NotFoundHttpException if the model cannot be found
*/ */

79
common/modules/banners/controllers/manage/PlaceController.php

@ -14,32 +14,32 @@ use Yii;
class PlaceController extends Controller class PlaceController extends Controller
{ {
private $service; private $_service;
public function __construct($id, $module, BannerPlaceManageService $service, $config = []) public function __construct($id, $module, BannerPlaceManageService $service, $config = [])
{ {
parent::__construct($id, $module, $config); parent::__construct($id, $module, $config);
$this->service = $service; $this->_service = $service;
} }
public function behaviors(): array public function behaviors(): array
{ {
return [ return [
'access' => [ 'access' => [
'class' => AccessControl::class, 'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['BannersManagement'], 'roles' => ['BannersManagement'],
], ],
[ // all the action are accessible to admin [ // all the action are accessible to admin
'allow' => true, 'allow' => true,
'roles' => ['admin'], 'roles' => ['admin'],
], ],
], ],
], ],
'verbs' => [ 'verbs' => [
'class' => VerbFilter::class, 'class' => VerbFilter::class,
'actions' => [ 'actions' => [
'delete' => ['POST'], 'delete' => ['POST'],
], ],
@ -52,21 +52,21 @@ class PlaceController extends Controller
*/ */
public function actionIndex() public function actionIndex()
{ {
$searchModel = new PlaceSearch(); $searchModel = new PlaceSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams); $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [ return $this->render('index', [
'searchModel' => $searchModel, 'searchModel' => $searchModel,
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
]); ]);
} }
/** /**
* @param $id * @param $id
* *
* @return string * @return string
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function actionView($id) public function actionView($id)
{ {
return $this->render('view', [ return $this->render('view', [
@ -82,27 +82,28 @@ class PlaceController extends Controller
$form = new BannerPlaceForm(); $form = new BannerPlaceForm();
if ($form->load(Yii::$app->request->post()) && $form->validate()) { if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try { try {
$form = $this->service->create($form); $form = $this->_service->create($form);
return $this->redirect(['view', 'id' => $form->id]); return $this->redirect(['view', 'id' => $form->id]);
} catch (\DomainException $e) { } catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e); Yii::$app->errorHandler->logException($e);
Yii::$app->session->setFlash('error', $e->getMessage()); Yii::$app->session->setFlash('error', $e->getMessage());
} }
} else {
$form->active = $form->active ?: BannerPlace::STATUS_ACTIVE;
} }
else {
$form->active = $form->active ?: BannerPlace::STATUS_ACTIVE;
}
return $this->render('create', [ return $this->render('create', [
'model' => $form, 'model' => $form,
]); ]);
} }
/** /**
* @param $id * @param $id
* *
* @return string|\yii\web\Response * @return string|\yii\web\Response
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function actionUpdate($id) public function actionUpdate($id)
{ {
$place = $this->findModel($id); $place = $this->findModel($id);
@ -110,7 +111,8 @@ class PlaceController extends Controller
$form = new BannerPlaceForm($place); $form = new BannerPlaceForm($place);
if ($form->load(Yii::$app->request->post()) && $form->validate()) { if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try { try {
$this->service->edit($place->id, $form); $this->_service->edit($place->id, $form);
return $this->redirect(['view', 'id' => $place->id]); return $this->redirect(['view', 'id' => $place->id]);
} catch (\DomainException $e) { } catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e); Yii::$app->errorHandler->logException($e);
@ -126,21 +128,24 @@ class PlaceController extends Controller
/** /**
* @param integer $id * @param integer $id
*
* @return mixed * @return mixed
*/ */
public function actionDelete($id) public function actionDelete($id)
{ {
try { try {
$this->service->remove($id); $this->_service->remove($id);
} catch (\DomainException $e) { } catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e); Yii::$app->errorHandler->logException($e);
Yii::$app->session->setFlash('error', $e->getMessage()); Yii::$app->session->setFlash('error', $e->getMessage());
} }
return $this->redirect(['index']); return $this->redirect(['index']);
} }
/** /**
* @param integer $id * @param integer $id
*
* @return BannerPlace the loaded model * @return BannerPlace the loaded model
* @throws NotFoundHttpException if the model cannot be found * @throws NotFoundHttpException if the model cannot be found
*/ */

218
common/modules/banners/entities/Banner.php

@ -8,7 +8,6 @@ use yii\db\ActiveRecord;
use yii\web\UploadedFile; use yii\web\UploadedFile;
use Yii; use Yii;
/** /**
* This is the model class for table "banners". * This is the model class for table "banners".
* *
@ -32,49 +31,70 @@ use Yii;
*/ */
class Banner extends ActiveRecord class Banner extends ActiveRecord
{ {
const STATUS_DRAFT = 0; const STATUS_DRAFT = 0;
const STATUS_ACTIVE = 1; const STATUS_ACTIVE = 1;
const TARGET_BLANK = '_blank'; const TARGET_BLANK = '_blank';
const TARGET_SELF = '_self'; const TARGET_SELF = '_self';
const FILE_ORIGINAL_PATH = '@staticRoot/origin/banners'; const FILE_ORIGINAL_PATH = '@staticRoot/origin/banners';
public static function create($title, $image, $url, $target, $start_at, $end_at, $include_urls, $exclude_urls, $active, $place_id): self public static function create(
{ $title,
$banner = new static(); $image,
$banner->title = $title; $url,
$banner->image = $image; $target,
$banner->url = $url; $start_at,
$banner->target = $target; $end_at,
$banner->start_at = $start_at; $include_urls,
$banner->end_at = $end_at; $exclude_urls,
$banner->include_urls = $include_urls; $active,
$banner->exclude_urls = $exclude_urls; $place_id
$banner->active = $active; ): self {
$banner->place_id = $place_id; $banner = new static();
return $banner; $banner->title = $title;
} $banner->image = $image;
$banner->url = $url;
public function setImage(UploadedFile $image): void $banner->target = $target;
{ $banner->start_at = $start_at;
$this->image = $image; $banner->end_at = $end_at;
} $banner->include_urls = $include_urls;
$banner->exclude_urls = $exclude_urls;
$banner->active = $active;
public function edit($title, $image, $url, $target, $start_at, $end_at, $include_urls, $exclude_urls, $active, $place_id): void $banner->place_id = $place_id;
{
$this->title = $title; return $banner;
$this->image = $image; }
$this->url = $url;
$this->target = $target; public function setImage(UploadedFile $image): void
$this->start_at = $start_at; {
$this->end_at = $end_at; $this->image = $image;
$this->include_urls = $include_urls; }
$this->exclude_urls = $exclude_urls;
$this->active = $active;
$this->place_id = $place_id; public function edit(
} $title,
$image,
$url,
$target,
$start_at,
$end_at,
$include_urls,
$exclude_urls,
$active,
$place_id
): void {
$this->title = $title;
$this->image = $image;
$this->url = $url;
$this->target = $target;
$this->start_at = $start_at;
$this->end_at = $end_at;
$this->include_urls = $include_urls;
$this->exclude_urls = $exclude_urls;
$this->active = $active;
$this->place_id = $place_id;
}
/** /**
* @inheritdoc * @inheritdoc
@ -90,67 +110,67 @@ class Banner extends ActiveRecord
public function attributeLabels() public function attributeLabels()
{ {
return [ return [
'id' => Yii::t('banners', 'ID'), 'id' => Yii::t('banners', 'ID'),
'title' => Yii::t('banners', 'Title'), 'title' => Yii::t('banners', 'Title'),
'url' => Yii::t('banners', 'URL'), 'url' => Yii::t('banners', 'URL'),
'image' => Yii::t('banners', 'Image'), 'image' => Yii::t('banners', 'Image'),
'target' => Yii::t('banners', 'Target'), 'target' => Yii::t('banners', 'Target'),
'active' => Yii::t('banners', 'Status'), 'active' => Yii::t('banners', 'Status'),
'start_at' => Yii::t('banners', 'Start At'), 'start_at' => Yii::t('banners', 'Start At'),
'end_at' => Yii::t('banners', 'End At'), 'end_at' => Yii::t('banners', 'End At'),
'created_at' => Yii::t('banners', 'Created At'), 'created_at' => Yii::t('banners', 'Created At'),
'updated_at' => Yii::t('banners', 'Updated At'), 'updated_at' => Yii::t('banners', 'Updated At'),
'include_urls' => Yii::t('banners', 'Show only on URLs'), 'include_urls' => Yii::t('banners', 'Show only on URLs'),
'exclude_urls' => Yii::t('banners', 'Not show on URLs'), 'exclude_urls' => Yii::t('banners', 'Not show on URLs'),
'views' => Yii::t('banners', 'Views'), 'views' => Yii::t('banners', 'Views'),
'clicks' => Yii::t('banners', 'Visits'), 'clicks' => Yii::t('banners', 'Visits'),
'place_id' => Yii::t('banners', 'Place'), 'place_id' => Yii::t('banners', 'Place'),
]; ];
} }
public function activate(): void public function activate(): void
{ {
if ($this->isActive()) { if ($this->isActive()) {
throw new \DomainException('Banner is already active.'); throw new \DomainException('Banner is already active.');
} }
$this->active = self::STATUS_ACTIVE; $this->active = self::STATUS_ACTIVE;
} }
public function draft(): void public function draft(): void
{ {
if ($this->isDraft()) { if ($this->isDraft()) {
throw new \DomainException('Banner is already draft.'); throw new \DomainException('Banner is already draft.');
} }
$this->active = self::STATUS_DRAFT; $this->active = self::STATUS_DRAFT;
} }
public function isActive(): bool public function isActive(): bool
{ {
return $this->active == self::STATUS_ACTIVE; return $this->active == self::STATUS_ACTIVE;
} }
public function isDraft(): bool public function isDraft(): bool
{ {
return $this->active == self::STATUS_DRAFT; return $this->active == self::STATUS_DRAFT;
} }
public function getPlace() public function getPlace()
{ {
return $this->hasOne(BannerPlace::class, ['id' => 'place_id']); return $this->hasOne(BannerPlace::class, ['id' => 'place_id']);
} }
###################################### ######################################
public function behaviors(): array public function behaviors(): array
{ {
return [ return [
TimestampBehavior::class, TimestampBehavior::class,
]; ];
} }
public static function find(): BannerQuery public static function find(): BannerQuery
{ {
return new BannerQuery(static::class); return new BannerQuery(static::class);
} }
} }

112
common/modules/banners/entities/BannerPlace.php

@ -6,7 +6,6 @@ use common\modules\banners\entities\queries\BannerPlaceQuery;
use yii\db\ActiveRecord; use yii\db\ActiveRecord;
use Yii; use Yii;
/** /**
* This is the model class for table "banners". * This is the model class for table "banners".
* *
@ -22,26 +21,27 @@ use Yii;
*/ */
class BannerPlace extends ActiveRecord class BannerPlace extends ActiveRecord
{ {
const STATUS_DRAFT = 0; const STATUS_DRAFT = 0;
const STATUS_ACTIVE = 1; const STATUS_ACTIVE = 1;
public static function create($title, $width, $height, $active): self public static function create($title, $width, $height, $active): self
{ {
$place = new static(); $place = new static();
$place->title = $title; $place->title = $title;
$place->width = $width; $place->width = $width;
$place->height = $height; $place->height = $height;
$place->active = $active; $place->active = $active;
return $place;
}
public function edit($title, $width, $height, $active): void return $place;
{ }
$this->title = $title;
$this->width = $width; public function edit($title, $width, $height, $active): void
$this->height = $height; {
$this->active = $active; $this->title = $title;
} $this->width = $width;
$this->height = $height;
$this->active = $active;
}
/** /**
* @inheritdoc * @inheritdoc
@ -57,52 +57,52 @@ class BannerPlace extends ActiveRecord
public function attributeLabels() public function attributeLabels()
{ {
return [ return [
'id' => Yii::t('banners', 'ID'), 'id' => Yii::t('banners', 'ID'),
'title' => Yii::t('banners', 'Title'), 'title' => Yii::t('banners', 'Title'),
'width' => Yii::t('banners', 'Width'), 'width' => Yii::t('banners', 'Width'),
'height' => Yii::t('banners', 'Height'), 'height' => Yii::t('banners', 'Height'),
'active' => Yii::t('banners', 'Status'), 'active' => Yii::t('banners', 'Status'),
]; ];
} }
public function activate(): void public function activate(): void
{ {
if ($this->isActive()) { if ($this->isActive()) {
throw new \DomainException('Place is already active.'); throw new \DomainException('Place is already active.');
} }
$this->active = self::STATUS_ACTIVE; $this->active = self::STATUS_ACTIVE;
} }
public function draft(): void public function draft(): void
{ {
if ($this->isDraft()) { if ($this->isDraft()) {
throw new \DomainException('Place is already draft.'); throw new \DomainException('Place is already draft.');
} }
$this->active = self::STATUS_DRAFT; $this->active = self::STATUS_DRAFT;
} }
public function isActive(): bool public function isActive(): bool
{ {
return $this->active == self::STATUS_ACTIVE; return $this->active == self::STATUS_ACTIVE;
} }
public function isDraft(): bool public function isDraft(): bool
{ {
return $this->active == self::STATUS_DRAFT; return $this->active == self::STATUS_DRAFT;
} }
public function getBanners() public function getBanners()
{ {
return $this->hasMany(Banner::class, ['place_id' => 'id']); return $this->hasMany(Banner::class, ['place_id' => 'id']);
} }
public function getActiveBanners() public function getActiveBanners()
{ {
return $this->hasMany(Banner::class, ['place_id' => 'id'])->andWhere(['active' => Banner::STATUS_ACTIVE]); return $this->hasMany(Banner::class, ['place_id' => 'id'])->andWhere(['active' => Banner::STATUS_ACTIVE]);
} }
public static function find(): BannerPlaceQuery public static function find(): BannerPlaceQuery
{ {
return new BannerPlaceQuery(static::class); return new BannerPlaceQuery(static::class);
} }
} }

7
common/modules/banners/entities/queries/BannerPlaceQuery.php

@ -5,6 +5,11 @@ namespace common\modules\banners\entities\queries;
use common\modules\banners\entities\BannerPlace; use common\modules\banners\entities\BannerPlace;
use yii\db\ActiveQuery; use yii\db\ActiveQuery;
/**
* Class BannerPlaceQuery
*
* @see BannerPlace
*/
class BannerPlaceQuery extends ActiveQuery class BannerPlaceQuery extends ActiveQuery
{ {
/** /**
@ -17,4 +22,4 @@ class BannerPlaceQuery extends ActiveQuery
($alias ? $alias . '.' : '') . 'active' => BannerPlace::STATUS_ACTIVE, ($alias ? $alias . '.' : '') . 'active' => BannerPlace::STATUS_ACTIVE,
]); ]);
} }
} }

16
common/modules/banners/entities/queries/BannerQuery.php

@ -3,23 +3,29 @@
namespace common\modules\banners\entities\queries; namespace common\modules\banners\entities\queries;
use common\modules\banners\entities\Banner; use common\modules\banners\entities\Banner;
use yii\helpers\Url;
use yii\db\ActiveQuery; use yii\db\ActiveQuery;
/**
* Class BannerQuery
*
* @see Banner
*/
class BannerQuery extends ActiveQuery class BannerQuery extends ActiveQuery
{ {
/** /**
* @param null $alias * @return BannerQuery
* @return $this
*/ */
public function active() public function active()
{ {
return $this->andWhere(['active' => Banner::STATUS_ACTIVE]); return $this->andWhere(['active' => Banner::STATUS_ACTIVE]);
} }
/**
* @return BannerQuery
*/
public function showTime() public function showTime()
{ {
return $this->andWhere(['<', 'start_at', time()])->andWhere(['>', 'end_at', time()]); return $this->andWhere(['<', 'start_at', time()])->andWhere(['>', 'end_at', time()]);
} }
/*public function excludeFree() /*public function excludeFree()
@ -27,4 +33,4 @@ class BannerQuery extends ActiveQuery
$current = Url::current([]); $current = Url::current([]);
return $this->andWhere(['not rlike', 'exclude_urls', '^'.$current.'$']); return $this->andWhere(['not rlike', 'exclude_urls', '^'.$current.'$']);
}*/ }*/
} }

114
common/modules/banners/forms/BannerForm.php

@ -11,9 +11,9 @@ class BannerForm extends Model
{ {
public $title; public $title;
/** /**
* @var UploadedFile * @var UploadedFile
*/ */
public $image; public $image;
public $url; public $url;
public $target; public $target;
@ -29,17 +29,17 @@ class BannerForm extends Model
public function __construct(Banner $banner = null, $config = []) public function __construct(Banner $banner = null, $config = [])
{ {
if ($banner) { if ($banner) {
$this->title = $banner->title; $this->title = $banner->title;
$this->image = $banner->image; $this->image = $banner->image;
$this->url = $banner->url; $this->url = $banner->url;
$this->target = $banner->target; $this->target = $banner->target;
$this->active = $banner->active; $this->active = $banner->active;
$this->start_at = $banner->start_at; $this->start_at = $banner->start_at;
$this->end_at = $banner->end_at; $this->end_at = $banner->end_at;
$this->include_urls = $banner->include_urls; $this->include_urls = $banner->include_urls;
$this->exclude_urls = $banner->exclude_urls; $this->exclude_urls = $banner->exclude_urls;
$this->place_id = $banner->place_id; $this->place_id = $banner->place_id;
$this->_banner = $banner; $this->_banner = $banner;
} }
parent::__construct($config); parent::__construct($config);
} }
@ -51,50 +51,54 @@ class BannerForm extends Model
[['active', 'place_id', 'active'], 'integer'], [['active', 'place_id', 'active'], 'integer'],
[['title', 'target', 'url'], 'string', 'max' => 255], [['title', 'target', 'url'], 'string', 'max' => 255],
[['include_urls', 'exclude_urls'], 'string'], [['include_urls', 'exclude_urls'], 'string'],
[['image'], 'file', 'extensions' => 'png, jpg, gif'], [['image'], 'file', 'extensions' => 'png, jpg, gif'],
[['start_at','end_at'],'safe'], [['start_at', 'end_at'], 'safe'],
/*[['start_at', 'end_at'], 'date', /*[['start_at', 'end_at'], 'date',
'format' => 'php:d.m.Y H:i' 'format' => 'php:d.m.Y H:i'
],*/ ],*/
]; ];
} }
public function attributeLabels() { public function attributeLabels()
return [ {
'id' => Yii::t('banners', 'ID'), return [
'title' => Yii::t('banners', 'Title'), 'id' => Yii::t('banners', 'ID'),
'url' => Yii::t('banners', 'URL'), 'title' => Yii::t('banners', 'Title'),
'image' => Yii::t('banners', 'Image'), 'url' => Yii::t('banners', 'URL'),
'target' => Yii::t('banners', 'Target'), 'image' => Yii::t('banners', 'Image'),
'active' => Yii::t('banners', 'Status'), 'target' => Yii::t('banners', 'Target'),
'start_at' => Yii::t('banners', 'Start At'), 'active' => Yii::t('banners', 'Status'),
'end_at' => Yii::t('banners', 'End At'), 'start_at' => Yii::t('banners', 'Start At'),
'created_at' => Yii::t('banners', 'Created At'), 'end_at' => Yii::t('banners', 'End At'),
'updated_at' => Yii::t('banners', 'Updated At'), 'created_at' => Yii::t('banners', 'Created At'),
'include_urls' => Yii::t('banners', 'Show only on URLs'), 'updated_at' => Yii::t('banners', 'Updated At'),
'exclude_urls' => Yii::t('banners', 'Not show on URLs'), 'include_urls' => Yii::t('banners', 'Show only on URLs'),
'views' => Yii::t('banners', 'Views'), 'exclude_urls' => Yii::t('banners', 'Not show on URLs'),
'clicks' => Yii::t('banners', 'Visits'), 'views' => Yii::t('banners', 'Views'),
'place_id' => Yii::t('banners', 'Place'), 'clicks' => Yii::t('banners', 'Visits'),
]; 'place_id' => Yii::t('banners', 'Place'),
} ];
}
public function beforeValidate()
{
if (parent::beforeValidate()) {
$this->image = UploadedFile::getInstance($this, 'image');
$this->start_at = strtotime($this->start_at);
$this->end_at = strtotime($this->end_at);
public function beforeValidate() { return true;
if (parent::beforeValidate()) { }
$this->image = UploadedFile::getInstance($this, 'image');
$this->start_at = strtotime($this->start_at);
$this->end_at = strtotime($this->end_at);
return true;
}
return false;
}
/*public function afterValidate() { return false;
if (parent::afterValidate()) { }
$this->start_at = strtotime($this->start_at);
$this->end_at = strtotime($this->end_at); /*public function afterValidate() {
return true; if (parent::afterValidate()) {
} $this->start_at = strtotime($this->start_at);
return false; $this->end_at = strtotime($this->end_at);
}*/ return true;
}
return false;
}*/
} }

29
common/modules/banners/forms/BannerPlaceForm.php

@ -18,10 +18,10 @@ class BannerPlaceForm extends Model
public function __construct(BannerPlace $place = null, $config = []) public function __construct(BannerPlace $place = null, $config = [])
{ {
if ($place) { if ($place) {
$this->title = $place->title; $this->title = $place->title;
$this->width = $place->width; $this->width = $place->width;
$this->height = $place->height; $this->height = $place->height;
$this->active = $place->active; $this->active = $place->active;
$this->_place = $place; $this->_place = $place;
} }
parent::__construct($config); parent::__construct($config);
@ -35,13 +35,14 @@ class BannerPlaceForm extends Model
]; ];
} }
public function attributeLabels() { public function attributeLabels()
return [ {
'id' => Yii::t('banners', 'ID'), return [
'title' => Yii::t('banners', 'Title'), 'id' => Yii::t('banners', 'ID'),
'width' => Yii::t('banners', 'Width'), 'title' => Yii::t('banners', 'Title'),
'height' => Yii::t('banners', 'Height'), 'width' => Yii::t('banners', 'Width'),
'active' => Yii::t('banners', 'Status'), 'height' => Yii::t('banners', 'Height'),
]; 'active' => Yii::t('banners', 'Status'),
} ];
} }
}

11
common/modules/banners/forms/search/BannerSearch.php

@ -24,6 +24,7 @@ class BannerSearch extends Model
/** /**
* @param array $params * @param array $params
*
* @return ActiveDataProvider * @return ActiveDataProvider
*/ */
public function search(array $params): ActiveDataProvider public function search(array $params): ActiveDataProvider
@ -32,7 +33,7 @@ class BannerSearch extends Model
$dataProvider = new ActiveDataProvider([ $dataProvider = new ActiveDataProvider([
'query' => $query, 'query' => $query,
'sort' => [ 'sort' => [
'defaultOrder' => ['id' => SORT_DESC] 'defaultOrder' => ['id' => SORT_DESC]
] ]
]); ]);
@ -41,18 +42,20 @@ class BannerSearch extends Model
if (!$this->validate()) { if (!$this->validate()) {
$query->where('0=1'); $query->where('0=1');
return $dataProvider; return $dataProvider;
} }
$query->andFilterWhere([ $query->andFilterWhere([
'id' => $this->id, 'id' => $this->id,
'active' => $this->active, 'active' => $this->active,
'place_id' => $this->place_id, 'place_id' => $this->place_id,
'target' => $this->target 'target' => $this->target
]); ]);
$query $query
->andFilterWhere(['like', 'title', $this->title]); ->andFilterWhere(['like', 'title', $this->title]);
return $dataProvider; return $dataProvider;
} }
} }

17
common/modules/banners/forms/search/PlaceSearch.php

@ -10,8 +10,8 @@ class PlaceSearch extends Model
{ {
public $id; public $id;
public $title; public $title;
public $width; public $width;
public $height; public $height;
public $active; public $active;
public function rules(): array public function rules(): array
@ -24,6 +24,7 @@ class PlaceSearch extends Model
/** /**
* @param array $params * @param array $params
*
* @return ActiveDataProvider * @return ActiveDataProvider
*/ */
public function search(array $params): ActiveDataProvider public function search(array $params): ActiveDataProvider
@ -32,7 +33,7 @@ class PlaceSearch extends Model
$dataProvider = new ActiveDataProvider([ $dataProvider = new ActiveDataProvider([
'query' => $query, 'query' => $query,
'sort' => [ 'sort' => [
'defaultOrder' => ['id' => SORT_DESC] 'defaultOrder' => ['id' => SORT_DESC]
] ]
]); ]);
@ -41,18 +42,20 @@ class PlaceSearch extends Model
if (!$this->validate()) { if (!$this->validate()) {
$query->where('0=1'); $query->where('0=1');
return $dataProvider; return $dataProvider;
} }
$query->andFilterWhere([ $query->andFilterWhere([
'id' => $this->id, 'id' => $this->id,
'active' => $this->active, 'active' => $this->active,
'width' => $this->width, 'width' => $this->width,
'height' => $this->height 'height' => $this->height
]); ]);
$query $query
->andFilterWhere(['like', 'title', $this->title]); ->andFilterWhere(['like', 'title', $this->title]);
return $dataProvider; return $dataProvider;
} }
} }

88
common/modules/banners/helpers/BannerHelper.php

@ -6,56 +6,54 @@
namespace common\modules\banners\helpers; namespace common\modules\banners\helpers;
use common\modules\banners\entities\Banner; use common\modules\banners\entities\Banner;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use yii\helpers\Html; use yii\helpers\Html;
use yii\helpers\Url;
use Yii; use Yii;
class BannerHelper class BannerHelper
{ {
public static function targetList(): array public static function targetList(): array
{ {
return [ return [
Banner::TARGET_SELF => Yii::t('banners', 'Self window'), Banner::TARGET_SELF => Yii::t('banners', 'Self window'),
Banner::TARGET_BLANK => Yii::t('banners', 'Blank window'), Banner::TARGET_BLANK => Yii::t('banners', 'Blank window'),
]; ];
} }
public static function targetName($target): string public static function targetName($target): string
{ {
return ArrayHelper::getValue(self::targetList(), $target); return ArrayHelper::getValue(self::targetList(), $target);
} }
public static function statusList(): array public static function statusList(): array
{ {
return [ return [
Banner::STATUS_DRAFT => Yii::t('banners', 'Draft'), Banner::STATUS_DRAFT => Yii::t('banners', 'Draft'),
Banner::STATUS_ACTIVE => Yii::t('banners', 'Active'), Banner::STATUS_ACTIVE => Yii::t('banners', 'Active'),
]; ];
} }
public static function statusName($status): string public static function statusName($status): string
{ {
return ArrayHelper::getValue(self::statusList(), $status); return ArrayHelper::getValue(self::statusList(), $status);
} }
public static function statusLabel($status): string public static function statusLabel($status): string
{ {
switch ($status) { switch ($status) {
case Banner::STATUS_DRAFT: case Banner::STATUS_DRAFT:
$class = 'label label-default'; $class = 'label label-default';
break; break;
case Banner::STATUS_ACTIVE: case Banner::STATUS_ACTIVE:
$class = 'label label-success'; $class = 'label label-success';
break; break;
default: default:
$class = 'label label-default'; $class = 'label label-default';
} }
return Html::tag('span', ArrayHelper::getValue(self::statusList(), $status), [ return Html::tag('span', ArrayHelper::getValue(self::statusList(), $status), [
'class' => $class, 'class' => $class,
]); ]);
} }
} }

5
common/modules/banners/manifest.php

@ -5,4 +5,9 @@ return [
'name' => 'banners', 'name' => 'banners',
'description' => 'Banners management and rotation system for site', 'description' => 'Banners management and rotation system for site',
'module' => 'BannersModule', 'module' => 'BannersModule',
'permissions' => [
'BannersManagement' => [
'description' => 'Manage banners system'
],
],
]; ];

2
common/modules/banners/repositories/BannerPlaceRepository.php

@ -28,4 +28,4 @@ class BannerPlaceRepository
throw new \RuntimeException('Removing error.'); throw new \RuntimeException('Removing error.');
} }
} }
} }

2
common/modules/banners/repositories/BannerRepository.php

@ -28,4 +28,4 @@ class BannerRepository
throw new \RuntimeException('Removing error.'); throw new \RuntimeException('Removing error.');
} }
} }
} }

85
common/modules/banners/services/BannerManageService.php

@ -9,29 +9,28 @@ use yii\base\Security;
class BannerManageService class BannerManageService
{ {
private $repository; private $_repository;
public function __construct(BannerRepository $repository) public function __construct(BannerRepository $repository)
{ {
$this->repository = $repository; $this->_repository = $repository;
} }
public function create(BannerForm $form): Banner public function create(BannerForm $form): Banner
{ {
if ($form->image) { if ($form->image) {
$filename = $form->image->baseName . '_' . (new Security())->generateRandomString(5) . '.' . $form->image->extension; $filename = $form->image->baseName . '_' . (new Security())->generateRandomString(5) . '.' . $form->image->extension;
$path = \Yii::getAlias(Banner::FILE_ORIGINAL_PATH); $path = \Yii::getAlias(Banner::FILE_ORIGINAL_PATH);
if (!file_exists($path)) if (!file_exists($path)) {
{ mkdir($path, 0777, true);
mkdir($path, 0777, true); }
} $form->image->saveAs($path . '/' . $filename);
$form->image->saveAs($path . '/' . $filename); $form->image = $filename;
$form->image = $filename; }
}
$banner = Banner::create( $banner = Banner::create(
$form->title, $form->title,
$form->image, $form->image,
$form->url, $form->url,
$form->target, $form->target,
$form->start_at, $form->start_at,
@ -41,54 +40,54 @@ class BannerManageService
$form->active, $form->active,
$form->place_id $form->place_id
); );
$this->repository->save($banner); $this->_repository->save($banner);
return $banner; return $banner;
} }
public function edit($id, BannerForm $form): void public function edit($id, BannerForm $form): void
{ {
$banner = $this->repository->get($id); $banner = $this->_repository->get($id);
if ($form->image) { if ($form->image) {
$filename = $form->image->baseName . '_' . (new Security())->generateRandomString(5) . '.' . $form->image->extension; $filename = $form->image->baseName . '_' . (new Security())->generateRandomString(5) . '.' . $form->image->extension;
$path = \Yii::getAlias(Banner::FILE_ORIGINAL_PATH); $path = \Yii::getAlias(Banner::FILE_ORIGINAL_PATH);
$form->image->saveAs($path . '/' . $filename); $form->image->saveAs($path . '/' . $filename);
$form->image = $filename; $form->image = $filename;
} } else {
else { $form->image = $banner->image;
$form->image = $banner->image; }
}
$banner->edit( $banner->edit(
$form->title, $form->title,
$form->image, $form->image,
$form->url, $form->url,
$form->target, $form->target,
$form->start_at, $form->start_at,
$form->end_at, $form->end_at,
$form->include_urls, $form->include_urls,
$form->exclude_urls, $form->exclude_urls,
$form->active, $form->active,
$form->place_id $form->place_id
); );
$this->repository->save($banner); $this->_repository->save($banner);
} }
public function remove($id): void public function remove($id): void
{ {
$banner = $this->repository->get($id); $banner = $this->_repository->get($id);
$this->repository->remove($banner); $this->_repository->remove($banner);
} }
public function addView(Banner $banner) public function addView(Banner $banner)
{ {
$banner->views++; $banner->views++;
$this->repository->save($banner); $this->_repository->save($banner);
} }
public function addClick(Banner $banner) public function addClick(Banner $banner)
{ {
$banner->clicks++; $banner->clicks++;
$this->repository->save($banner); $this->_repository->save($banner);
} }
} }

25
common/modules/banners/services/BannerPlaceManageService.php

@ -8,40 +8,41 @@ use common\modules\banners\repositories\BannerPlaceRepository;
class BannerPlaceManageService class BannerPlaceManageService
{ {
private $repository; private $_repository;
public function __construct(BannerPlaceRepository $repository) public function __construct(BannerPlaceRepository $repository)
{ {
$this->repository = $repository; $this->_repository = $repository;
} }
public function create(BannerPlaceForm $form): BannerPlace public function create(BannerPlaceForm $form): BannerPlace
{ {
$place = BannerPlace::create( $place = BannerPlace::create(
$form->title, $form->title,
$form->width, $form->width,
$form->height, $form->height,
$form->active $form->active
); );
$this->repository->save($place); $this->_repository->save($place);
return $place; return $place;
} }
public function edit($id, BannerPlaceForm $form): void public function edit($id, BannerPlaceForm $form): void
{ {
$place = $this->repository->get($id); $place = $this->_repository->get($id);
$place->edit( $place->edit(
$form->title, $form->title,
$form->width, $form->width,
$form->height, $form->height,
$form->active $form->active
); );
$this->repository->save($place); $this->_repository->save($place);
} }
public function remove($id): void public function remove($id): void
{ {
$place = $this->repository->get($id); $place = $this->_repository->get($id);
$this->repository->remove($place); $this->_repository->remove($place);
} }
} }

184
common/modules/banners/views/manage/banner/_form.php

@ -33,98 +33,98 @@ $this->registerJs($js2);
<?php $form = ActiveForm::begin(); ?> <?php $form = ActiveForm::begin(); ?>
<div class="row"> <div class="row">
<div class="col-md-10"> <div class="col-md-10">
<div class="box box-default"> <div class="box box-default">
<div class="box-body"> <div class="box-body">
<div class="row"> <div class="row">
<div class="col-md-4"> <div class="col-md-4">
<?= $form->field($model, 'place_id')->dropDownList(ArrayHelper::map(BannerPlace::find()->all(), 'id', 'title')) ?> <?= $form->field($model, 'place_id')->dropDownList(ArrayHelper::map(BannerPlace::find()->all(), 'id', 'title')) ?>
</div> </div>
<div class="col-md-8"> <div class="col-md-8">
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-8"> <div class="col-md-8">
<?= $form->field($model, 'url')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'url')->textInput(['maxlength' => true]) ?>
</div> </div>
<div class="col-md-4"> <div class="col-md-4">
<?= $form->field($model, 'target')->dropDownList(BannerHelper::targetList()) ?> <?= $form->field($model, 'target')->dropDownList(BannerHelper::targetList()) ?>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-4"> <div class="col-md-4">
<?= $form->field($model, 'image')->widget(FileInput::class, [ <?= $form->field($model, 'image')->widget(FileInput::class, [
'options' => [ 'options' => [
'accept' => 'image/*', 'accept' => 'image/*',
], ],
'pluginOptions' => [ 'pluginOptions' => [
'showUpload' => false, 'showUpload' => false,
'showPreview' => false, 'showPreview' => false,
], ],
]) ?> ]) ?>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-6"> <div class="col-md-6">
<?= $form->field($model, 'start_at')->widget(DateTimePicker::class, [ <?= $form->field($model, 'start_at')->widget(DateTimePicker::class, [
'options' => [], 'options' => [],
'removeButton' => false, 'removeButton' => false,
'pluginOptions' => [ 'pluginOptions' => [
'autoclose' => true, 'autoclose' => true,
'format' => 'dd.mm.yyyy hh:ii:ss', 'format' => 'dd.mm.yyyy hh:ii:ss',
] ]
]); ?> ]); ?>
</div> </div>
<div class="col-md-6"> <div class="col-md-6">
<?= $form->field($model, 'end_at')->widget(DateTimePicker::class, [ <?= $form->field($model, 'end_at')->widget(DateTimePicker::class, [
'options' => [], 'options' => [],
'removeButton' => false, 'removeButton' => false,
'pluginOptions' => [ 'pluginOptions' => [
'autoclose' => true, 'autoclose' => true,
//'format' => 'dd.MM.yyyy hh:i', //'format' => 'dd.MM.yyyy hh:i',
'format' => 'dd.mm.yyyy hh:ii:ss', 'format' => 'dd.mm.yyyy hh:ii:ss',
] ]
]); ?> ]); ?>
</div> </div>
</div> </div>
<!--<div class="row"> <!--<div class="row">
<div class="col-md-6"> <div class="col-md-6">
< ?= $form->field($model, 'include_urls')->textarea(['rows' => 4]) ?> < ?= $form->field($model, 'include_urls')->textarea(['rows' => 4]) ?>
</div> </div>
<div class="col-md-6"> <div class="col-md-6">
< ?= $form->field($model, 'exclude_urls')->textarea(['rows' => 4]) ?> < ?= $form->field($model, 'exclude_urls')->textarea(['rows' => 4]) ?>
</div> </div>
</div>--> </div>-->
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
<?= Html::submitButton(Yii::t('buttons', 'Save'), ['class' => 'btn btn-success']) ?> <?= Html::submitButton(Yii::t('buttons', 'Save'), ['class' => 'btn btn-success']) ?>
</div> </div>
</div> </div>
<div class="col-md-2"> <div class="col-md-2">
<div class="box box-default"> <div class="box box-default">
<div class="box-header with-border"><?= Yii::t('banners', 'Publish') ?></div> <div class="box-header with-border"><?= Yii::t('banners', 'Publish') ?></div>
<div class="box-body"> <div class="box-body">
<?= $form->field($model, 'active')->radioList(BannerHelper::statusList()) ?> <?= $form->field($model, 'active')->radioList(BannerHelper::statusList()) ?>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>

55
common/modules/banners/widgets/BannerWidget.php

@ -12,30 +12,31 @@ use yii\base\Widget;
class BannerWidget extends Widget class BannerWidget extends Widget
{ {
public $id; public $id;
public function run() { public function run()
$place = BannerPlace::findOne($this->id); {
if (!$place) { $place = BannerPlace::findOne($this->id);
return 'Place is not found'; if (!$place) {
} return 'Place is not found';
}
$banners = Banner::find()
->active() $banners = Banner::find()
->showTime() ->active()
//->excludeFree() ->showTime()
->andWhere(['place_id' => $place->id]) //->excludeFree()
->all(); ->andWhere(['place_id' => $place->id])
->all();
if (!$banners || $place->isDraft()) {
return ''; if (!$banners || $place->isDraft()) {
} return '';
}
/* @var $banner Banner */
$banner = $banners[array_rand($banners)]; /* @var $banner Banner */
$banner = $banners[array_rand($banners)];
return $this->render('banner', [
'banner' => $banner, return $this->render('banner', [
]); 'banner' => $banner,
} ]);
} }
}

95
common/modules/blog/entities/BlogCategory.php

@ -8,7 +8,6 @@ use core\behaviors\SluggableRelationBehavior;
use yii\db\ActiveRecord; use yii\db\ActiveRecord;
use Yii; use Yii;
/** /**
* @property integer $id * @property integer $id
* @property string $slug * @property string $slug
@ -18,41 +17,42 @@ use Yii;
* @method ActiveRecord findTranslation(string $language) * @method ActiveRecord findTranslation(string $language)
* @method void saveTranslations($translations) * @method void saveTranslations($translations)
* *
* @property ActiveRecord[] translations * @property ActiveRecord[] $translations
* @property ActiveRecord[] translation * @property ActiveRecord $translation
*/ */
class BlogCategory extends ActiveRecord class BlogCategory extends ActiveRecord
{ {
public $_form; public $_form;
public static function create($form, $slug, $sort): self public static function create($form, $slug, $sort): self
{ {
$category = new static(); $category = new static();
$category->slug = $slug; $category->slug = $slug;
$category->sort = $sort; $category->sort = $sort;
$category->_form = $form; $category->_form = $form;
return $category; return $category;
} }
public function edit($form, $slug, $sort): void public function edit($form, $slug, $sort): void
{ {
$this->slug = $slug; $this->slug = $slug;
$this->sort = $sort; $this->sort = $sort;
$this->_form = $form; $this->_form = $form;
} }
public function attributeLabels() public function attributeLabels()
{ {
return [ return [
'id' => Yii::t('blog', 'ID'), 'id' => Yii::t('blog', 'ID'),
'name' => Yii::t('blog', 'Name'), 'name' => Yii::t('blog', 'Name'),
'slug' => Yii::t('blog', 'SEO link'), 'slug' => Yii::t('blog', 'SEO link'),
'sort' => Yii::t('blog', 'Sort'), 'sort' => Yii::t('blog', 'Sort'),
'title' => Yii::t('blog', 'Title'), 'title' => Yii::t('blog', 'Title'),
'description' => Yii::t('blog', 'Description'), 'description' => Yii::t('blog', 'Description'),
'meta_title' => Yii::t('blog', 'META Title'), 'meta_title' => Yii::t('blog', 'META Title'),
'meta_description' => Yii::t('blog', 'META Description'), 'meta_description' => Yii::t('blog', 'META Description'),
'meta_keywords' => Yii::t('blog', 'META Keywords'), 'meta_keywords' => Yii::t('blog', 'META Keywords'),
]; ];
} }
@ -68,7 +68,7 @@ class BlogCategory extends ActiveRecord
public function getPostsCount(): int public function getPostsCount(): int
{ {
return BlogPost::find()->where(['category_id' => $this->id])->count('*'); return BlogPost::find()->where(['category_id' => $this->id])->count('*');
} }
public static function tableName(): string public static function tableName(): string
@ -79,32 +79,39 @@ class BlogCategory extends ActiveRecord
public function behaviors(): array public function behaviors(): array
{ {
return [ return [
/*[ /*[
'class' => SluggableBehavior::class, 'class' => SluggableBehavior::class,
'attribute' => 'title', 'attribute' => 'title',
'ensureUnique' => true, 'ensureUnique' => true,
'preserveNonEmptyValues' => true, 'preserveNonEmptyValues' => true,
],*/ ],*/
[ [
'class' => LanguageBehavior::class, 'class' => LanguageBehavior::class,
'virtualClassName' => 'BlogCategoryVirtualTranslate', 'virtualClassName' => 'BlogCategoryVirtualTranslate',
'translatedLanguages' => \Yii::$app->params['translatedLanguages'], 'translatedLanguages' => \Yii::$app->params['translatedLanguages'],
'relativeField' => 'blog_category_id', 'relativeField' => 'blog_category_id',
'tableName' => "{{%blog_categories_lng}}", 'tableName' => '{{%blog_categories_lng}}',
'attributes' => ['title', 'description', 'name', 'meta_title', 'meta_description', 'meta_keywords'], 'attributes' => [
//'defaultLanguage' => basename(Yii::$app->getBasePath()) === 'backend' ? Yii::$app->language : Yii::$app->params['defaultLanguage'], 'title',
'defaultLanguage' => \Yii::$app->params['defaultLanguage'], 'description',
], 'name',
[ 'meta_title',
'class' => SluggableRelationBehavior::class, 'meta_description',
'attribute' => 'name', 'meta_keywords'
'relation' => 'translation', ],
], //'defaultLanguage' => basename(Yii::$app->getBasePath()) === 'backend' ? Yii::$app->language : Yii::$app->params['defaultLanguage'],
'defaultLanguage' => \Yii::$app->params['defaultLanguage'],
],
[
'class' => SluggableRelationBehavior::class,
'attribute' => 'name',
'relation' => 'translation',
],
]; ];
} }
public static function find(): BlogCategoryQuery public static function find(): BlogCategoryQuery
{ {
return new BlogCategoryQuery(static::class); return new BlogCategoryQuery(static::class);
} }
} }

6
common/modules/blog/forms/search/BlogPostSearch.php

@ -30,7 +30,7 @@ class BlogPostSearch extends Model
*/ */
public function search(array $params): ActiveDataProvider public function search(array $params): ActiveDataProvider
{ {
$query = BlogPost::find()->typePublic(); $query = BlogPost::find()->typePublic()->joinWith('translation');
$dataProvider = new ActiveDataProvider([ $dataProvider = new ActiveDataProvider([
'query' => $query, 'query' => $query,
@ -59,7 +59,9 @@ class BlogPostSearch extends Model
public function categoriesList(): array public function categoriesList(): array
{ {
return ArrayHelper::map(BlogCategory::find()->orderBy('sort')->asArray()->all(), 'id', 'title'); return ArrayHelper::map(BlogCategory::find()->orderBy('sort')->all(), 'id', function (BlogCategory $category) {
return $category->translation->name;
});
} }
public function statusList(): array public function statusList(): array

5
common/modules/blog/manifest.php

@ -5,4 +5,9 @@ return [
'name' => 'blog', 'name' => 'blog',
'description' => 'Blog system for site with comments and slug', 'description' => 'Blog system for site with comments and slug',
'module' => 'BlogModule', 'module' => 'BlogModule',
'permissions' => [
'BlogManagement' => [
'description' => 'Blog management system'
],
],
]; ];

129
common/modules/blog/services/BlogPostManageService.php

@ -12,7 +12,6 @@ use common\modules\blog\repositories\BlogTagRepository;
use core\helpers\VideoHelper; use core\helpers\VideoHelper;
use core\services\TransactionManager; use core\services\TransactionManager;
use yii\base\Security; use yii\base\Security;
use yii\db\ActiveRecord;
use yii\helpers\Inflector; use yii\helpers\Inflector;
class BlogPostManageService class BlogPostManageService
@ -154,6 +153,8 @@ class BlogPostManageService
$post = $this->posts->get($id); $post = $this->posts->get($id);
// Remove revisions // Remove revisions
$this->clearHistory($post); $this->clearHistory($post);
// Remove preview
$this->removePreviews();
$this->posts->remove($post); $this->posts->remove($post);
} }
@ -189,130 +190,4 @@ class BlogPostManageService
return $from->id; return $from->id;
} }
public function restoreHistory2($from_id, $id): void
{
$post = $this->posts->get($id);
$from = $this->posts->get($from_id);
$post->category_id = $from->category_id;
$post->published_at = $from->published_at;
$post->created_at = $from->created_at;
$post->updated_at = $from->updated_at;
$post->video = $from->video;
$post->revision_at = $from->revision_at;
$post->status = $from->status;
$post->slug = $from->slug;
$this->posts->save($post);
// remove distance translation
foreach ( $post->translations as $translate ) {
/* @var $translate ActiveRecord */
$translate->delete();
}
// move source translation
foreach ( $from->translations as $translate ) {
/* @var $translate ActiveRecord */
$translate->blog_post_id = $post->id;
$translate->save();
}
// get from tags
$from_tags = $from->tags;
$new_tags_names = array_map(function ($item){
return $item->name;
}, $from_tags);
// clear from tags
$from->revokeTags();
$this->posts->save($from);
// remove current revision
$this->posts->remove($post);
// copy image
$path = \Yii::getAlias('@staticRoot/origin/posts');
$parts = pathinfo($from->image);
copy($path . '/' . $from->id . '.' . $parts['extension'], $path . '/' . $id . '.' . $parts['extension']);
$from->createThumbs();
//$from->id = $id;
//$from->type = BlogPost::TYPE_PUBLIC;
//$from->revision_id = null;
foreach ($new_tags_names as $tag_name) {
if ( ! $tag = $this->tags->findByName( $tag_name ) ) {
$tag = BlogTag::create( $tag_name, Inflector::slug( $tag_name, '_' ) );
$this->tags->save( $tag );
}
$from->assignTag( $tag->id );
}
$this->posts->save($from);
// delete never revisions
BlogPost::deleteAll(['AND', ['revision_id' => $from->id], ['>', 'revision_at', $from->revision_at]]);
}
/*public function saveRevision2(BlogPost $model) {
if (!$model->revision_id) {
$revision = clone $model;
$revision->id = null;
$revision->isNewRecord = true;
$revision->revision_at = $revision->updated_at;
$revision->revision_id = $model->id;
$revision->type = BlogPost::TYPE_REVISION;
$revision->_form = new BlogPostForm($model);
$revision->save();
// tags
foreach ($model->tags as $tag) {
$revision->assignTag($tag->id);
}
$revision->save();
if ($model->image) {
$path = Yii::getAlias( '@staticRoot/origin/posts' );
$parts = pathinfo( $model->image );
copy( $path . '/' . $model->id . '.' . $parts['extension'], $path . '/' . $revision->id . '.' . $parts['extension'] );
}
}
}*/
/*public function saveRevision(BlogPost $model) {
if (!$model->revision_id) {
$blogForm = new BlogPostForm($model);
$blog = BlogPost::create(
$blogForm,
$blogForm->category_id,
$blogForm->slug,
$blogForm->published_at,
$blogForm->video,
BlogPost::TYPE_REVISION
);
//$blog->id = null;
//$blog->isNewRecord = true;
$blog->revision_at = $model->updated_at;
$blog->revision_id = $model->id;
$this->transaction->wrap(function () use ($blog, $model) {
foreach ( $model->tags as $tag ) {
$blog->assignTag( $tag->id );
}
$this->posts->save($blog);
//print_r($blog->translations); die;
//print_r($model->translations); die;
if ($model->image) {
$path = Yii::getAlias( '@staticRoot/origin/posts' );
$parts = pathinfo( $model->image );
copy( $path . '/' . $model->id . '.' . $parts['extension'], $path . '/' . $blog->id . '.' . $parts['extension'] );
}
});
}
}*/
} }

10
common/modules/blog/views/manage/post/_form.php

@ -1,7 +1,6 @@
<?php <?php
use kartik\file\FileInput; use kartik\file\FileInput;
use zertex\ckeditor\CKEditor;
use yii\helpers\Html; use yii\helpers\Html;
use kartik\form\ActiveForm; use kartik\form\ActiveForm;
use yii\web\JsExpression; use yii\web\JsExpression;
@ -175,15 +174,6 @@ $this->registerJs($js2);
<div class="box box-default"> <div class="box box-default">
<div class="box-header with-border"><?= Yii::t('blog', 'Publish') ?></div> <div class="box-header with-border"><?= Yii::t('blog', 'Publish') ?></div>
<div class="box-body"> <div class="box-body">
<?= Html::submitButton(Yii::t('blog', 'Preview on site'), [
'class' => 'btn btn-info',
'value'=>'preview',
'name'=>'submit_preview',
'formaction' => Url::to(['/blog/manage/post/create-preview', 'id' => $model->_post ? $model->_post->id : null]),
'formtarget' => '_blank',
]) ?>
<div class="btn-group"> <div class="btn-group">
<button type="button" class="btn btn-info"><?= Yii::t('blog', 'Preview on site') ?></button> <button type="button" class="btn btn-info"><?= Yii::t('blog', 'Preview on site') ?></button>

67
common/modules/blog/views/manage/post/index.php

@ -10,8 +10,8 @@ use yii\grid\GridView;
/* @var $searchModel \common\modules\blog\forms\search\BlogPostSearch */ /* @var $searchModel \common\modules\blog\forms\search\BlogPostSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */ /* @var $dataProvider yii\data\ActiveDataProvider */
$title = Yii::t('blog', 'All Posts'); $title = Yii::t('blog', 'All Posts');
$this->title = $title; $this->title = $title;
$this->params['breadcrumbs'][] = $title; $this->params['breadcrumbs'][] = $title;
?> ?>
<div class="blog-post-index"> <div class="blog-post-index">
@ -24,52 +24,55 @@ $this->params['breadcrumbs'][] = $title;
<div class="box-body"> <div class="box-body">
<?= GridView::widget([ <?= GridView::widget([
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'filterModel' => $searchModel, 'filterModel' => $searchModel,
'columns' => [ 'columns' => [
[ [
'attribute' => 'id', 'attribute' => 'id',
'options' => ['style' => 'width: 40px;'], 'options' => ['style' => 'width: 40px;'],
'contentOptions' => ['class' => 'text-center'], 'contentOptions' => ['class' => 'text-center'],
], ],
[ [
'attribute' => 'title', 'attribute' => 'title',
'value' => function (BlogPost $model) { 'value' => function (BlogPost $model) {
$title = isset($model->findTranslation(Yii::$app->language)->title) ? $model->findTranslation(Yii::$app->language)->title : $model->findTranslation(Yii::$app->params['defaultLanguage'])->title; $title = isset($model->translation->title) ? $model->findTranslation(Yii::$app->language)->title : $model->findTranslation(Yii::$app->params['defaultLanguage'])->title;
return Html::a(Html::encode($title), ['view', 'id' => $model->id]); return Html::a(Html::encode($title), ['view', 'id' => $model->id]);
}, },
'format' => 'raw', 'format' => 'raw',
], ],
[ [
'attribute' => 'category_id', 'attribute' => 'category_id',
'filter' => $searchModel->categoriesList(), 'filter' => $searchModel->categoriesList(),
'value' => 'category.name', 'value' => function (BlogPost $model) {
return $model->category->translation->name;
},
],
[
'attribute' => 'published_at',
'format' => ['datetime', 'php:d.m.Y H:i'],
'options' => ['style' => 'width: 60px;'],
'contentOptions' => ['class' => 'text-center'],
], ],
[
'attribute' => 'published_at',
'format' => ['datetime', 'php:d.m.Y H:i'],
'options' => ['style' => 'width: 60px;'],
'contentOptions' => ['class' => 'text-center'],
],
[ [
'attribute' => 'status', 'attribute' => 'status',
'filter' => $searchModel->statusList(), 'filter' => $searchModel->statusList(),
'value' => function (BlogPost $model) { 'value' => function (BlogPost $model) {
return BlogPostHelper::statusLabel($model->status); return BlogPostHelper::statusLabel($model->status);
}, },
'format' => 'raw', 'format' => 'raw',
'options' => ['style' => 'width: 120px;'], 'options' => ['style' => 'width: 120px;'],
'contentOptions' => ['class' => 'text-center'],
],
[
'class' => ActionColumn::class,
/*'urlCreator' => function($action, BlogPost $model, $key, $index, $column) {
$params = is_array($key) ? $key : ['id' => (string) $key];
$params[0] = $column->controller ? $column->controller . '/' . $action : $action;
return Url::toRoute($params);
},*/
'options' => ['style' => 'width: 100px;'],
'contentOptions' => ['class' => 'text-center'], 'contentOptions' => ['class' => 'text-center'],
], ],
[
'class' => ActionColumn::class,
/*'urlCreator' => function($action, BlogPost $model, $key, $index, $column) {
$params = is_array($key) ? $key : ['id' => (string) $key];
$params[0] = $column->controller ? $column->controller . '/' . $action : $action;
return Url::toRoute($params);
},*/
'options' => ['style' => 'width: 100px;'],
'contentOptions' => ['class' => 'text-center'],
],
], ],
]); ?> ]); ?>
</div> </div>

2
common/modules/blog/widgets/views/categories/categories.php

@ -22,7 +22,7 @@ use yii\helpers\Html;
<ul class="list-unstyled mb-0 blog-categories-widget-list"> <ul class="list-unstyled mb-0 blog-categories-widget-list">
<?php foreach ($categories as $category): ?> <?php foreach ($categories as $category): ?>
<li> <li>
<?= Html::a($category->name, ['/blog/post/category', 'id' => $category->id]) ?> <?= Html::a($category->translation->name, ['/blog/post/category', 'id' => $category->id]) ?>
</li> </li>
<?php endforeach; ?> <?php endforeach; ?>
</ul> </ul>

5
common/modules/forms/manifest.php

@ -5,4 +5,9 @@ return [
'name' => 'forms', 'name' => 'forms',
'description' => 'Form widget generator for site', 'description' => 'Form widget generator for site',
'module' => 'FormsModule', 'module' => 'FormsModule',
'permissions' => [
'FormsManagement' => [
'description' => 'Forms management'
],
],
]; ];

5
common/modules/languages/manifest.php

@ -5,4 +5,9 @@ return [
'name' => 'languages', 'name' => 'languages',
'description' => 'Web site languages management', 'description' => 'Web site languages management',
'module' => 'LanguagesModule', 'module' => 'LanguagesModule',
'permissions' => [
'LanguagesManagement' => [
'description' => 'Languages management'
],
],
]; ];

2
common/modules/pages/forms/PageSearch.php

@ -27,7 +27,7 @@ class PageSearch extends Model
*/ */
public function search(array $params): ActiveDataProvider public function search(array $params): ActiveDataProvider
{ {
$query = Page::find()->typePublic()->andWhere(['>', 'depth', 0]); $query = Page::find()->typePublic()->andWhere(['>', 'depth', 0])->joinWith('translation');
$dataProvider = new ActiveDataProvider([ $dataProvider = new ActiveDataProvider([
'query' => $query, 'query' => $query,

40
core/forms/MetaForm-org.php

@ -1,40 +0,0 @@
<?php
namespace core\forms;
use core\entities\Meta;
use yii\base\Model;
use Yii;
class MetaFormOrg extends Model
{
public $title;
public $description;
public $keywords;
public function __construct(Meta $meta = null, $config = [])
{
if ($meta) {
$this->title = $meta->title;
$this->description = $meta->description;
$this->keywords = $meta->keywords;
}
parent::__construct($config);
}
public function rules(): array
{
return [
[['title'], 'string', 'max' => 255],
[['description', 'keywords'], 'string'],
];
}
public function attributeLabels() {
return [
'title' => Yii::t('main', 'Title'),
'description' => Yii::t('main', 'Description'),
'keywords' => Yii::t('main', 'Keywords'),
];
}
}

247
core/services/ModuleService.php

@ -2,6 +2,7 @@
namespace core\services; namespace core\services;
use core\components\SearchPerformance;
use core\entities\ModuleRecord; use core\entities\ModuleRecord;
use core\repositories\ModuleRepository; use core\repositories\ModuleRepository;
use yii\helpers\FileHelper; use yii\helpers\FileHelper;
@ -9,139 +10,147 @@ use Yii;
class ModuleService class ModuleService
{ {
private $modules; private $_modules;
private $permission_manager; private $_permission_manager;
public function __construct(ModuleRepository $modules, PermissionManager $permission_manager) public function __construct(ModuleRepository $modules, PermissionManager $permission_manager)
{ {
$this->modules = $modules; $this->_modules = $modules;
$this->permission_manager = $permission_manager; $this->_permission_manager = $permission_manager;
} }
public function create($name, $class, $type = 'common', $active = ModuleRecord::STATUS_DISABLED): ModuleRecord public function create($name, $class, $type = 'common', $active = ModuleRecord::STATUS_DISABLED): ModuleRecord
{ {
$module = new ModuleRecord(); $module = new ModuleRecord();
$module->name = $name; $module->name = $name;
$module->class = $class; $module->class = $class;
$module->type = $type; $module->type = $type;
$module->active = $active; $module->active = $active;
$this->modules->save($module); $this->_modules->save($module);
return $module;
return $module;
} }
/**
* @param ModuleRecord $module
*
* @throws \yii\base\ErrorException
*/
public function delete(ModuleRecord $module) public function delete(ModuleRecord $module)
{ {
// connect manifest // connect manifest
$manifest = require Yii::getAlias('@common/modules/' . $module->name . '/manifest.php'); $manifest = require Yii::getAlias('@common/modules/' . $module->name . '/manifest.php');
// down migrations // down migrations
$migrations = $this->getMigrationFiles($module->name); $migrations = $this->getMigrationFiles($module->name);
$migrations = array_reverse($migrations); $migrations = array_reverse($migrations);
foreach ($migrations as $migrationPath) { foreach ($migrations as $migrationPath) {
$migrationFile = basename($migrationPath); $migrationFile = basename($migrationPath);
$migration = str_replace('.php', '', $migrationFile); $migration = str_replace('.php', '', $migrationFile);
if ($this->migrationExists($migration)) { if ($this->migrationExists($migration)) {
require $migrationPath; require $migrationPath;
$obj = new $migration; $obj = new $migration;
if (method_exists($obj, 'safeDown')) { if (method_exists($obj, 'safeDown')) {
$obj->safeDown(); $obj->safeDown();
Yii::$app->moduleManager->removeFromMigrationTable($migration); Yii::$app->moduleManager->removeFromMigrationTable($migration);
} elseif (method_exists($obj, 'down')) {
} $obj->down();
elseif (method_exists($obj, 'down')) { Yii::$app->moduleManager->removeFromMigrationTable($migration);
$obj->down(); }
Yii::$app->moduleManager->removeFromMigrationTable($migration); }
} }
}
} // remove permissions
if (isset($manifest['permissions']) && is_array($manifest['permissions'])) {
// remove permissions $this->removePermissions($manifest['permissions']);
if (isset($manifest['permissions']) && is_array($manifest['permissions'])) { }
$this->removePermissions($manifest['permissions']);
} // delete files
$modulePath = Yii::getAlias('@common/modules/' . $module->name);
// delete files if (file_exists($modulePath)) {
$modulePath = Yii::getAlias('@common/modules/' . $module->name); FileHelper::removeDirectory($modulePath);
if (file_exists($modulePath)) { }
FileHelper::removeDirectory($modulePath); // delete module record
} $this->_modules->remove($module);
// delete module record
$this->modules->remove($module);
} }
public function disable(ModuleRecord $module) public function disable(ModuleRecord $module)
{ {
$module->active = ModuleRecord::STATUS_DISABLED; $module->active = ModuleRecord::STATUS_DISABLED;
$this->modules->save($module); $this->_modules->save($module);
// regenerate global control panel search
SearchPerformance::init();
} }
public function enable(ModuleRecord $module) public function enable(ModuleRecord $module)
{ {
// connect manifest // connect manifest
$manifest = require Yii::getAlias('@common/modules/' . $module->name . '/manifest.php'); $manifest = require Yii::getAlias('@common/modules/' . $module->name . '/manifest.php');
$module->active = ModuleRecord::STATUS_ENABLED; $module->active = ModuleRecord::STATUS_ENABLED;
// migration if not exists // migration if not exists
$migrations = $this->getMigrationFiles($module->name); $migrations = $this->getMigrationFiles($module->name);
foreach ($migrations as $migrationPath) { foreach ($migrations as $migrationPath) {
$migrationFile = basename($migrationPath); $migrationFile = basename($migrationPath);
$migration = str_replace('.php', '', $migrationFile); $migration = str_replace('.php', '', $migrationFile);
if (!$this->migrationExists($migration)) { if (!$this->migrationExists($migration)) {
// run migration // run migration
require $migrationPath; require $migrationPath;
$obj = new $migration; $obj = new $migration;
if (method_exists($obj, 'safeUp')) { if (method_exists($obj, 'safeUp')) {
$obj->safeUp(); $obj->safeUp();
Yii::$app->moduleManager->appendToMigrationTable($migration); Yii::$app->moduleManager->appendToMigrationTable($migration);
} elseif (method_exists($obj, 'up')) {
} $obj->up();
elseif (method_exists($obj, 'up')) { Yii::$app->moduleManager->appendToMigrationTable($migration);
$obj->up(); }
Yii::$app->moduleManager->appendToMigrationTable($migration); }
} }
}
} // add not exists permissions
if (isset($manifest['permissions']) && is_array($manifest['permissions'])) {
// add not exists permissions $this->assignPermissions($manifest['permissions']);
if (isset($manifest['permissions']) && is_array($manifest['permissions'])) { }
$this->assignPermissions($manifest['permissions']);
} $this->_modules->save($module);
// regenerate global control panel search
$this->modules->save($module); SearchPerformance::init();
} }
private function assignPermissions(array $permissions): void private function assignPermissions(array $permissions): void
{ {
foreach ($permissions as $permission => $description) { foreach ($permissions as $permission => $description) {
if (!$this->permission_manager->permissionExists($permission)) { if (!$this->_permission_manager->permissionExists($permission)) {
$this->permission_manager->create($permission, $description); $this->_permission_manager->create($permission, $description);
} }
} }
} }
private function removePermissions(array $permissions) private function removePermissions(array $permissions)
{ {
foreach ($permissions as $permission => $description) { foreach ($permissions as $permission => $description) {
if ($this->permission_manager->permissionExists($permission)) { if ($this->_permission_manager->permissionExists($permission)) {
$this->permission_manager->delete($permission); $this->_permission_manager->delete($permission);
} }
} }
} }
private function getMigrationFiles($module) private function getMigrationFiles($module)
{ {
// migration if not exists // migration if not exists
$migrationPath = Yii::getAlias('@common/modules/' . $module . '/migrations'); $migrationPath = Yii::getAlias('@common/modules/' . $module . '/migrations');
return file_exists($migrationPath) ? FileHelper::findFiles($migrationPath) : [];
} return file_exists($migrationPath) ? FileHelper::findFiles($migrationPath) : [];
}
private function migrationExists($name): bool
{ private function migrationExists($name): bool
// check record exists {
$connection = Yii::$app->getDb(); // check record exists
$command = $connection->createCommand("SELECT * FROM migration WHERE version = '$name'"); $connection = Yii::$app->getDb();
$result = $command->queryAll(); $command = $connection->createCommand("SELECT * FROM migration WHERE version = '$name'");
return $result ? true : false; $result = $command->queryAll();
}
} return $result ? true : false;
}
}

2
core/services/auth/AuthService.php

@ -20,7 +20,7 @@ class AuthService
{ {
$user = $this->users->findByUsernameOrEmail($form->username); $user = $this->users->findByUsernameOrEmail($form->username);
if (!$user || !$user->isActive() || !$user->validatePassword($form->password)) { if (!$user || !$user->isActive() || !$user->validatePassword($form->password)) {
throw new \DomainException(Yii::t('auth', 'Undefined user or password.')); throw new \DomainException(Yii::t('user', 'Undefined user or password.'));
} }
return $user; return $user;
} }

2
frontend/web/themes/start/modules/blog/views/post/post.php

@ -13,7 +13,7 @@ $this->registerMetaTag(['name' =>'description', 'content' => $post->translation-
$this->registerMetaTag(['name' =>'keywords', 'content' => $post->translation->meta_keywords]); $this->registerMetaTag(['name' =>'keywords', 'content' => $post->translation->meta_keywords]);
$this->params['breadcrumbs'][] = ['label' => Yii::t('blog_public', 'Blog'), 'url' => ['/blog/post/index']]; $this->params['breadcrumbs'][] = ['label' => Yii::t('blog_public', 'Blog'), 'url' => ['/blog/post/index']];
$this->params['breadcrumbs'][] = ['label' => $post->category->name, 'url' => ['/blog/post/category', 'id' => $post->category->id]]; $this->params['breadcrumbs'][] = ['label' => $post->category->translation->name, 'url' => ['/blog/post/category', 'id' => $post->category->id]];
$this->params['breadcrumbs'][] = $post->translation->title; $this->params['breadcrumbs'][] = $post->translation->title;
$this->params['active_category'] = $post->category; $this->params['active_category'] = $post->category;

Loading…
Cancel
Save