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. 66
      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. 5
      common/modules/banners/entities/queries/BannerPlaceQuery.php
  13. 14
      common/modules/banners/entities/queries/BannerQuery.php
  14. 114
      common/modules/banners/forms/BannerForm.php
  15. 27
      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. 85
      common/modules/banners/services/BannerManageService.php
  21. 25
      common/modules/banners/services/BannerPlaceManageService.php
  22. 184
      common/modules/banners/views/manage/banner/_form.php
  23. 53
      common/modules/banners/widgets/BannerWidget.php
  24. 93
      common/modules/blog/entities/BlogCategory.php
  25. 6
      common/modules/blog/forms/search/BlogPostSearch.php
  26. 5
      common/modules/blog/manifest.php
  27. 129
      common/modules/blog/services/BlogPostManageService.php
  28. 10
      common/modules/blog/views/manage/post/_form.php
  29. 67
      common/modules/blog/views/manage/post/index.php
  30. 2
      common/modules/blog/widgets/views/categories/categories.php
  31. 5
      common/modules/forms/manifest.php
  32. 5
      common/modules/languages/manifest.php
  33. 2
      common/modules/pages/forms/PageSearch.php
  34. 40
      core/forms/MetaForm-org.php
  35. 245
      core/services/ModuleService.php
  36. 2
      core/services/auth/AuthService.php
  37. 2
      frontend/web/themes/start/modules/blog/views/post/post.php

4
.editorconfig

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

1
backend/messages/ru/user.php

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

76
common/config/main.php

@ -1,51 +1,51 @@
<?php
return [
'aliases' => [
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
],
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'controllerMap' => [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'controllerMap' => [
// Common migrations for the whole application
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'class' => 'yii\console\controllers\MigrateController',
'migrationPath' => [
'@console/migrations',
'@console/migrations',
],
],
],
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
'cachePath' => '@common/runtime/cache',
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
'itemTable' => '{{%auth_items}}',
'itemChildTable' => '{{%auth_item_children}}',
'assignmentTable' => '{{%auth_assignments}}',
'ruleTable' => '{{%auth_rules}}',
],
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
'cachePath' => '@common/runtime/cache',
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
'itemTable' => '{{%auth_items}}',
'itemChildTable' => '{{%auth_item_children}}',
'assignmentTable' => '{{%auth_assignments}}',
'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 yii\helpers\ArrayHelper;
/**
* blog module definition class
*/
@ -26,52 +25,52 @@ class BannersModule extends \yii\base\Module implements ModuleInterface
// custom initialization code goes here
}
public function bootstrap($app)
{
// add migration path
$app->controllerMap['migrate']['migrationPath'][] = '@common/modules/banners/migrations';
public function bootstrap($app)
{
// add migration path
$app->controllerMap['migrate']['migrationPath'][] = '@common/modules/banners/migrations';
// add search rules
$app->params['search_rules'][] = "SELECT title, title as content, CONCAT('/banners/manage/banner/view/', id) AS url FROM {{banners}}";
// add search rules
$app->params['search_rules'][] = "SELECT title, title as content, CONCAT('/banners/manage/banner/view/', id) AS url FROM {{banners}}";
$app->getUrlManager()->addRules([
'banner/view' => 'banners/banner/view',
'banner/click' => 'banners/banner/click',
]);
$app->getUrlManager()->addRules([
'banner/view' => 'banners/banner/view',
'banner/click' => 'banners/banner/click',
]);
$app->getUrlManager()->addRules([
'banners/manage/banner/view/<id:\d+>' => 'banners/manage/banner/view',
]);
$app->getUrlManager()->addRules([
'banners/manage/banner/view/<id:\d+>' => 'banners/manage/banner/view',
]);
// add languages
$app->getI18n()->translations = ArrayHelper::merge($app->getI18n()->translations, [
'banners' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@common/modules/banners/messages',
],
]);
// add languages
$app->getI18n()->translations = ArrayHelper::merge($app->getI18n()->translations, [
'banners' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@common/modules/banners/messages',
],
]);
// add menu items
if (basename(\Yii::$app->getBasePath()) === 'backend') {
$app->params['adminMenu'][] = [
'label' => \Yii::t( 'banners', 'Banners' ),
'icon' => 'flag',
'items' => [
[
'label' => \Yii::t( 'banners', 'Banners' ),
'icon' => 'caret-right',
'url' => [ '/banners/manage/banner/index' ],
//'active' => \Yii::$app->controller->getUniqueId() == 'banners/manage/banner'
],
[
'label' => \Yii::t( 'banners', 'Places' ),
'icon' => 'caret-right',
'url' => [ '/banners/manage/place/index' ],
//'active' => \Yii::$app->controller->getUniqueId() == 'banners/manage/place'
],
],
'visible' => $app->user->can( 'admin' ) || \Yii::$app->user->can( 'BannersManagement' ),
];
}
}
// add menu items
if (basename(\Yii::$app->getBasePath()) === 'backend') {
$app->params['adminMenu'][] = [
'label' => \Yii::t('banners', 'Banners'),
'icon' => 'flag',
'items' => [
[
'label' => \Yii::t('banners', 'Banners'),
'icon' => 'caret-right',
'url' => ['/banners/manage/banner/index'],
//'active' => \Yii::$app->controller->getUniqueId() == 'banners/manage/banner'
],
[
'label' => \Yii::t('banners', 'Places'),
'icon' => 'caret-right',
'url' => ['/banners/manage/place/index'],
//'active' => \Yii::$app->controller->getUniqueId() == 'banners/manage/place'
],
],
'visible' => $app->user->can('admin') || \Yii::$app->user->can('BannersManagement'),
];
}
}
}

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

@ -6,7 +6,6 @@
namespace common\modules\banners\controllers;
use common\modules\banners\entities\Banner;
use common\modules\banners\services\BannerManageService;
use frontend\components\FrontendController;
@ -14,36 +13,37 @@ use yii\web\NotFoundHttpException;
class BannerController extends FrontendController
{
private $service;
public function __construct( string $id, $module, BannerManageService $service, array $config = [] ) {
parent::__construct( $id, $module, $config );
$this->service = $service;
}
public function actionView()
{
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
if (\Yii::$app->request->isAjax && $id) {
$banner = $this->findModel( $id );
$this->service->addView( $banner );
}
}
public function actionClick()
{
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
if (\Yii::$app->request->isAjax && $id) {
$banner = $this->findModel( $id );
$this->service->addClick( $banner );
}
}
protected function findModel($id): Banner
{
if (($model = Banner::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested banner does not exist.');
}
private $_service;
public function __construct(string $id, $module, BannerManageService $service, array $config = [])
{
parent::__construct($id, $module, $config);
$this->_service = $service;
}
public function actionView()
{
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
if (\Yii::$app->request->isAjax && $id) {
$banner = $this->findModel($id);
$this->_service->addView($banner);
}
}
public function actionClick()
{
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
if (\Yii::$app->request->isAjax && $id) {
$banner = $this->findModel($id);
$this->_service->addClick($banner);
}
}
protected function findModel($id): Banner
{
if (($model = Banner::findOne($id)) !== null) {
return $model;
}
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
{
private $service;
private $_service;
public function __construct($id, $module, BannerManageService $service, $config = [])
{
parent::__construct($id, $module, $config);
$this->service = $service;
$this->_service = $service;
}
public function behaviors(): array
{
return [
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['BannersManagement'],
],
[ // all the action are accessible to admin
'allow' => true,
'roles' => ['admin'],
],
],
],
'verbs' => [
'class' => VerbFilter::class,
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['BannersManagement'],
],
[ // all the action are accessible to admin
'allow' => true,
'roles' => ['admin'],
],
],
],
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
'delete' => ['POST'],
],
@ -52,21 +52,21 @@ class BannerController extends Controller
*/
public function actionIndex()
{
$searchModel = new BannerSearch();
$searchModel = new BannerSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* @param $id
*
* @return string
* @throws NotFoundHttpException
*/
/**
* @param $id
*
* @return string
* @throws NotFoundHttpException
*/
public function actionView($id)
{
return $this->render('view', [
@ -83,36 +83,38 @@ class BannerController extends Controller
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try {
$form = $this->service->create($form);
$form = $this->_service->create($form);
return $this->redirect(['view', 'id' => $form->id]);
} catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e);
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', [
'model' => $form,
]);
}
/**
* @param $id
*
* @return string|\yii\web\Response
* @throws NotFoundHttpException
*/
/**
* @param $id
*
* @return string|\yii\web\Response
* @throws NotFoundHttpException
*/
public function actionUpdate($id)
{
$banner = $this->findModel($id);
$form = new BannerForm($banner);
$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);
$banner = $this->findModel($id);
$form = new BannerForm($banner);
$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);
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try {
$this->service->edit($banner->id, $form);
$this->_service->edit($banner->id, $form);
return $this->redirect(['view', 'id' => $banner->id]);
} catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e);
@ -121,28 +123,31 @@ class BannerController extends Controller
}
return $this->render('update', [
'model' => $form,
'model' => $form,
'banner' => $banner,
]);
}
/**
* @param integer $id
*
* @return mixed
*/
public function actionDelete($id)
{
try {
$this->service->remove($id);
$this->_service->remove($id);
} catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e);
Yii::$app->session->setFlash('error', $e->getMessage());
}
return $this->redirect(['index']);
}
/**
* @param integer $id
*
* @return Banner the loaded model
* @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
{
private $service;
private $_service;
public function __construct($id, $module, BannerPlaceManageService $service, $config = [])
{
parent::__construct($id, $module, $config);
$this->service = $service;
$this->_service = $service;
}
public function behaviors(): array
{
return [
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['BannersManagement'],
],
[ // all the action are accessible to admin
'allow' => true,
'roles' => ['admin'],
],
],
],
'verbs' => [
'class' => VerbFilter::class,
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['BannersManagement'],
],
[ // all the action are accessible to admin
'allow' => true,
'roles' => ['admin'],
],
],
],
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
'delete' => ['POST'],
],
@ -52,21 +52,21 @@ class PlaceController extends Controller
*/
public function actionIndex()
{
$searchModel = new PlaceSearch();
$searchModel = new PlaceSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* @param $id
*
* @return string
* @throws NotFoundHttpException
*/
/**
* @param $id
*
* @return string
* @throws NotFoundHttpException
*/
public function actionView($id)
{
return $this->render('view', [
@ -82,27 +82,28 @@ class PlaceController extends Controller
$form = new BannerPlaceForm();
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try {
$form = $this->service->create($form);
$form = $this->_service->create($form);
return $this->redirect(['view', 'id' => $form->id]);
} catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e);
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', [
'model' => $form,
]);
}
/**
* @param $id
*
* @return string|\yii\web\Response
* @throws NotFoundHttpException
*/
/**
* @param $id
*
* @return string|\yii\web\Response
* @throws NotFoundHttpException
*/
public function actionUpdate($id)
{
$place = $this->findModel($id);
@ -110,7 +111,8 @@ class PlaceController extends Controller
$form = new BannerPlaceForm($place);
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try {
$this->service->edit($place->id, $form);
$this->_service->edit($place->id, $form);
return $this->redirect(['view', 'id' => $place->id]);
} catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e);
@ -126,21 +128,24 @@ class PlaceController extends Controller
/**
* @param integer $id
*
* @return mixed
*/
public function actionDelete($id)
{
try {
$this->service->remove($id);
$this->_service->remove($id);
} catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e);
Yii::$app->session->setFlash('error', $e->getMessage());
}
return $this->redirect(['index']);
}
/**
* @param integer $id
*
* @return BannerPlace the loaded model
* @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;
/**
* This is the model class for table "banners".
*
@ -32,49 +31,70 @@ use Yii;
*/
class Banner extends ActiveRecord
{
const STATUS_DRAFT = 0;
const STATUS_ACTIVE = 1;
const TARGET_BLANK = '_blank';
const TARGET_SELF = '_self';
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
{
$banner = new static();
$banner->title = $title;
$banner->image = $image;
$banner->url = $url;
$banner->target = $target;
$banner->start_at = $start_at;
$banner->end_at = $end_at;
$banner->include_urls = $include_urls;
$banner->exclude_urls = $exclude_urls;
$banner->active = $active;
$banner->place_id = $place_id;
return $banner;
}
public function setImage(UploadedFile $image): void
{
$this->image = $image;
}
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;
}
const STATUS_DRAFT = 0;
const STATUS_ACTIVE = 1;
const TARGET_BLANK = '_blank';
const TARGET_SELF = '_self';
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 {
$banner = new static();
$banner->title = $title;
$banner->image = $image;
$banner->url = $url;
$banner->target = $target;
$banner->start_at = $start_at;
$banner->end_at = $end_at;
$banner->include_urls = $include_urls;
$banner->exclude_urls = $exclude_urls;
$banner->active = $active;
$banner->place_id = $place_id;
return $banner;
}
public function setImage(UploadedFile $image): void
{
$this->image = $image;
}
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
@ -90,67 +110,67 @@ class Banner extends ActiveRecord
public function attributeLabels()
{
return [
'id' => Yii::t('banners', 'ID'),
'title' => Yii::t('banners', 'Title'),
'url' => Yii::t('banners', 'URL'),
'image' => Yii::t('banners', 'Image'),
'target' => Yii::t('banners', 'Target'),
'active' => Yii::t('banners', 'Status'),
'start_at' => Yii::t('banners', 'Start At'),
'end_at' => Yii::t('banners', 'End At'),
'created_at' => Yii::t('banners', 'Created At'),
'updated_at' => Yii::t('banners', 'Updated At'),
'id' => Yii::t('banners', 'ID'),
'title' => Yii::t('banners', 'Title'),
'url' => Yii::t('banners', 'URL'),
'image' => Yii::t('banners', 'Image'),
'target' => Yii::t('banners', 'Target'),
'active' => Yii::t('banners', 'Status'),
'start_at' => Yii::t('banners', 'Start At'),
'end_at' => Yii::t('banners', 'End At'),
'created_at' => Yii::t('banners', 'Created At'),
'updated_at' => Yii::t('banners', 'Updated At'),
'include_urls' => Yii::t('banners', 'Show only on URLs'),
'exclude_urls' => Yii::t('banners', 'Not show on URLs'),
'views' => Yii::t('banners', 'Views'),
'clicks' => Yii::t('banners', 'Visits'),
'place_id' => Yii::t('banners', 'Place'),
'views' => Yii::t('banners', 'Views'),
'clicks' => Yii::t('banners', 'Visits'),
'place_id' => Yii::t('banners', 'Place'),
];
}
public function activate(): void
{
if ($this->isActive()) {
throw new \DomainException('Banner is already active.');
}
$this->active = self::STATUS_ACTIVE;
}
public function draft(): void
{
if ($this->isDraft()) {
throw new \DomainException('Banner is already draft.');
}
$this->active = self::STATUS_DRAFT;
}
public function isActive(): bool
{
return $this->active == self::STATUS_ACTIVE;
}
public function isDraft(): bool
{
return $this->active == self::STATUS_DRAFT;
}
public function getPlace()
{
return $this->hasOne(BannerPlace::class, ['id' => 'place_id']);
}
public function activate(): void
{
if ($this->isActive()) {
throw new \DomainException('Banner is already active.');
}
$this->active = self::STATUS_ACTIVE;
}
public function draft(): void
{
if ($this->isDraft()) {
throw new \DomainException('Banner is already draft.');
}
$this->active = self::STATUS_DRAFT;
}
public function isActive(): bool
{
return $this->active == self::STATUS_ACTIVE;
}
public function isDraft(): bool
{
return $this->active == self::STATUS_DRAFT;
}
public function getPlace()
{
return $this->hasOne(BannerPlace::class, ['id' => 'place_id']);
}
######################################
public function behaviors(): array
{
return [
TimestampBehavior::class,
];
}
public static function find(): BannerQuery
{
return new BannerQuery(static::class);
}
public function behaviors(): array
{
return [
TimestampBehavior::class,
];
}
public static function find(): BannerQuery
{
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;
/**
* This is the model class for table "banners".
*
@ -22,26 +21,27 @@ use Yii;
*/
class BannerPlace extends ActiveRecord
{
const STATUS_DRAFT = 0;
const STATUS_ACTIVE = 1;
const STATUS_DRAFT = 0;
const STATUS_ACTIVE = 1;
public static function create($title, $width, $height, $active): self
{
$place = new static();
$place->title = $title;
$place->width = $width;
$place->height = $height;
$place->active = $active;
return $place;
}
public static function create($title, $width, $height, $active): self
{
$place = new static();
$place->title = $title;
$place->width = $width;
$place->height = $height;
$place->active = $active;
public function edit($title, $width, $height, $active): void
{
$this->title = $title;
$this->width = $width;
$this->height = $height;
$this->active = $active;
}
return $place;
}
public function edit($title, $width, $height, $active): void
{
$this->title = $title;
$this->width = $width;
$this->height = $height;
$this->active = $active;
}
/**
* @inheritdoc
@ -57,52 +57,52 @@ class BannerPlace extends ActiveRecord
public function attributeLabels()
{
return [
'id' => Yii::t('banners', 'ID'),
'title' => Yii::t('banners', 'Title'),
'width' => Yii::t('banners', 'Width'),
'id' => Yii::t('banners', 'ID'),
'title' => Yii::t('banners', 'Title'),
'width' => Yii::t('banners', 'Width'),
'height' => Yii::t('banners', 'Height'),
'active' => Yii::t('banners', 'Status'),
];
}
public function activate(): void
{
if ($this->isActive()) {
throw new \DomainException('Place is already active.');
}
$this->active = self::STATUS_ACTIVE;
}
public function activate(): void
{
if ($this->isActive()) {
throw new \DomainException('Place is already active.');
}
$this->active = self::STATUS_ACTIVE;
}
public function draft(): void
{
if ($this->isDraft()) {
throw new \DomainException('Place is already draft.');
}
$this->active = self::STATUS_DRAFT;
}
public function draft(): void
{
if ($this->isDraft()) {
throw new \DomainException('Place is already draft.');
}
$this->active = self::STATUS_DRAFT;
}
public function isActive(): bool
{
return $this->active == self::STATUS_ACTIVE;
}
public function isActive(): bool
{
return $this->active == self::STATUS_ACTIVE;
}
public function isDraft(): bool
{
return $this->active == self::STATUS_DRAFT;
}
public function isDraft(): bool
{
return $this->active == self::STATUS_DRAFT;
}
public function getBanners()
{
return $this->hasMany(Banner::class, ['place_id' => 'id']);
}
public function getBanners()
{
return $this->hasMany(Banner::class, ['place_id' => 'id']);
}
public function getActiveBanners()
{
return $this->hasMany(Banner::class, ['place_id' => 'id'])->andWhere(['active' => Banner::STATUS_ACTIVE]);
}
public function getActiveBanners()
{
return $this->hasMany(Banner::class, ['place_id' => 'id'])->andWhere(['active' => Banner::STATUS_ACTIVE]);
}
public static function find(): BannerPlaceQuery
{
return new BannerPlaceQuery(static::class);
}
public static function find(): BannerPlaceQuery
{
return new BannerPlaceQuery(static::class);
}
}

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

@ -5,6 +5,11 @@ namespace common\modules\banners\entities\queries;
use common\modules\banners\entities\BannerPlace;
use yii\db\ActiveQuery;
/**
* Class BannerPlaceQuery
*
* @see BannerPlace
*/
class BannerPlaceQuery extends ActiveQuery
{
/**

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

@ -3,23 +3,29 @@
namespace common\modules\banners\entities\queries;
use common\modules\banners\entities\Banner;
use yii\helpers\Url;
use yii\db\ActiveQuery;
/**
* Class BannerQuery
*
* @see Banner
*/
class BannerQuery extends ActiveQuery
{
/**
* @param null $alias
* @return $this
* @return BannerQuery
*/
public function active()
{
return $this->andWhere(['active' => Banner::STATUS_ACTIVE]);
}
/**
* @return BannerQuery
*/
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()

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

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

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

@ -18,10 +18,10 @@ class BannerPlaceForm extends Model
public function __construct(BannerPlace $place = null, $config = [])
{
if ($place) {
$this->title = $place->title;
$this->width = $place->width;
$this->height = $place->height;
$this->active = $place->active;
$this->title = $place->title;
$this->width = $place->width;
$this->height = $place->height;
$this->active = $place->active;
$this->_place = $place;
}
parent::__construct($config);
@ -35,13 +35,14 @@ class BannerPlaceForm extends Model
];
}
public function attributeLabels() {
return [
'id' => Yii::t('banners', 'ID'),
'title' => Yii::t('banners', 'Title'),
'width' => Yii::t('banners', 'Width'),
'height' => Yii::t('banners', 'Height'),
'active' => Yii::t('banners', 'Status'),
];
}
public function attributeLabels()
{
return [
'id' => Yii::t('banners', 'ID'),
'title' => Yii::t('banners', 'Title'),
'width' => Yii::t('banners', 'Width'),
'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
*
* @return ActiveDataProvider
*/
public function search(array $params): ActiveDataProvider
@ -32,7 +33,7 @@ class BannerSearch extends Model
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'sort' => [
'defaultOrder' => ['id' => SORT_DESC]
]
]);
@ -41,18 +42,20 @@ class BannerSearch extends Model
if (!$this->validate()) {
$query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'active' => $this->active,
'id' => $this->id,
'active' => $this->active,
'place_id' => $this->place_id,
'target' => $this->target
'target' => $this->target
]);
$query
->andFilterWhere(['like', 'title', $this->title]);
return $dataProvider;
}
}

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

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

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

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

5
common/modules/banners/manifest.php

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

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

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

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

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

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

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

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

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

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

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

5
common/modules/blog/manifest.php

@ -5,4 +5,9 @@ return [
'name' => 'blog',
'description' => 'Blog system for site with comments and slug',
'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\services\TransactionManager;
use yii\base\Security;
use yii\db\ActiveRecord;
use yii\helpers\Inflector;
class BlogPostManageService
@ -154,6 +153,8 @@ class BlogPostManageService
$post = $this->posts->get($id);
// Remove revisions
$this->clearHistory($post);
// Remove preview
$this->removePreviews();
$this->posts->remove($post);
}
@ -189,130 +190,4 @@ class BlogPostManageService
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
use kartik\file\FileInput;
use zertex\ckeditor\CKEditor;
use yii\helpers\Html;
use kartik\form\ActiveForm;
use yii\web\JsExpression;
@ -175,15 +174,6 @@ $this->registerJs($js2);
<div class="box box-default">
<div class="box-header with-border"><?= Yii::t('blog', 'Publish') ?></div>
<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">
<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 $dataProvider yii\data\ActiveDataProvider */
$title = Yii::t('blog', 'All Posts');
$this->title = $title;
$title = Yii::t('blog', 'All Posts');
$this->title = $title;
$this->params['breadcrumbs'][] = $title;
?>
<div class="blog-post-index">
@ -24,52 +24,55 @@ $this->params['breadcrumbs'][] = $title;
<div class="box-body">
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'filterModel' => $searchModel,
'columns' => [
[
'attribute' => 'id',
'options' => ['style' => 'width: 40px;'],
'attribute' => 'id',
'options' => ['style' => 'width: 40px;'],
'contentOptions' => ['class' => 'text-center'],
],
[
'attribute' => 'title',
'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;
'value' => function (BlogPost $model) {
$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]);
},
'format' => 'raw',
'format' => 'raw',
],
[
'attribute' => 'category_id',
'filter' => $searchModel->categoriesList(),
'value' => 'category.name',
'filter' => $searchModel->categoriesList(),
'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',
'filter' => $searchModel->statusList(),
'value' => function (BlogPost $model) {
'attribute' => 'status',
'filter' => $searchModel->statusList(),
'value' => function (BlogPost $model) {
return BlogPostHelper::statusLabel($model->status);
},
'format' => 'raw',
'options' => ['style' => 'width: 120px;'],
'format' => 'raw',
'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'],
],
[
'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>

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">
<?php foreach ($categories as $category): ?>
<li>
<?= Html::a($category->name, ['/blog/post/category', 'id' => $category->id]) ?>
<?= Html::a($category->translation->name, ['/blog/post/category', 'id' => $category->id]) ?>
</li>
<?php endforeach; ?>
</ul>

5
common/modules/forms/manifest.php

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

5
common/modules/languages/manifest.php

@ -5,4 +5,9 @@ return [
'name' => 'languages',
'description' => 'Web site languages management',
'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
{
$query = Page::find()->typePublic()->andWhere(['>', 'depth', 0]);
$query = Page::find()->typePublic()->andWhere(['>', 'depth', 0])->joinWith('translation');
$dataProvider = new ActiveDataProvider([
'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'),
];
}
}

245
core/services/ModuleService.php

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

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->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['active_category'] = $post->category;

Loading…
Cancel
Save