<?php

namespace kato\modules\media\controllers;

use Yii;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use kato\modules\media\models\ContentMedia;
use yii\web\Controller;
use kato\modules\media\models\Media;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use kato\modules\media\Media as MediaModule;
use kato\modules\media\models\MediaSearch;
use yii\grid\DataColumn;

class DefaultController extends Controller
{
    public $pageTitle = 'Media';
    public $pageIcon = 'fa fa-camera-retro fa-fw';

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['delete'],
                'rules' => [
                    [
                        'actions' => ['index', 'update', 'delete'],
                        'allow' => true,
                        'roles' => ['admin'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $meta['title'] = $this->pageTitle;
        $meta['description'] = 'List all media';
        $meta['pageIcon'] = $this->pageIcon;

        $module = MediaModule::getInstance();
        if (!is_null($module->adminLayout)) {
            $this->layout = $module->adminLayout;
        }

        $searchModel = new MediaSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());

        $getColumns = [
            ['class' => 'yii\grid\SerialColumn'],
            [
                'class' => DataColumn::className(),
                'attribute' => 'title',
                'format' => 'text',
                'label' => 'Title',
            ],
            'create_time',
            [
                'class' => DataColumn::className(),
                'attribute' => 'statusLabel',
                'format' => 'text',
                'label' => 'Status',
            ],
            [
                'class' => DataColumn::className(),
                'attribute' => 'uploadedTo',
                'format' => 'html',
                'label' => 'Uploaded to',
            ],
            ['class' => 'backend\components\ActionColumn'],
        ];

        return $this->render($module->adminView, [
            'meta' => $meta,
            'dataProvider' => $dataProvider,
            'getColumns' => $getColumns,
        ]);
    }

    /**
     * Updates an existing Media model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $module = MediaModule::getInstance();
        if (!is_null($module->adminLayout)) {
            $this->layout = $module->adminLayout;
        }

        $model = $this->findModel($id);
        $model->title = $model->id;
        $controllerName = $this->getUniqueId();

        $meta['title'] = $this->pageTitle;
        $meta['description'] = 'Update media';
        $meta['pageIcon'] = $this->pageIcon;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', 'Media has been updated');
            return $this->redirect(Url::previous());
        } else {
            return $this->render('update', [
                'model' => $model,
                'meta' => $meta,
                'controllerName' => $controllerName,
            ]);
        }
    }

    /**
     * If content id and type provided then do join
     * return boolean
     * @param $result
     * @return bool
     */
    private function doMediaJoin($result)
    {
        if (isset($_GET['content_id']) && isset($_GET['content_type'])) {
            $media = $result['data'];
            if (!is_null($media)) {
                //Do join here
                $contentMedia = new ContentMedia();
                $contentMedia->content_id = $_GET['content_id'];
                $contentMedia->content_type = $_GET['content_type'];
                $contentMedia->media_id = $media['id'];
                if ($contentMedia->save(false)) {
                    //success
                    return true;
                } else {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * Uploads the file and update database
     */
    public function actionUpload()
    {
        /**
         * @var \kato\modules\media\Media $module
         */
        $module = \Yii::$app->controller->module;
        $result = $module->mediaUpload();

        $response = new Response();
        $response->format = Response::FORMAT_JSON;
        $response->setStatusCode(500);

        if ($result['success'] === true) {

            if ($this->doMediaJoin($result)) {
                //success
                $response->setStatusCode(200);
                $response->data = $result['data'];
                $response->send();
                Yii::$app->end();
            } else {
                $response->statusText = 'Unable to do join of media with content.';
                $response->send();
                Yii::$app->end();
            }

        } else {
            $response->statusText = $result['message'];
            $response->send();
            Yii::$app->end();
        }
    }

    /**
     * Action for file uploads via sir-trevor image block from SirTrevorWidget (input widget)
     */
    public function actionSirTrevorUpload()
    {
        //header('Access-Control-Allow-Origin: *');
        /**
         * @var \kato\modules\media\Media $module
         */
        $module = \Yii::$app->controller->module;
        $result = $module->mediaUpload('attachment[file]');

        $response = new Response();
        $response->format = Response::FORMAT_JSON;

        if ($result['success'] === true) {

            if ($this->doMediaJoin($result)) {
                //success
                $response->setStatusCode(200);
                $response->data = [
                    'file' => [
                        'url' => '/' . $result['data']['source'],
                        'media_id' => $result['data']['id'],
                    ],
                ];
                $response->send();
            } else {
                $response->statusText = 'Unable to do join of media with content.';
                $response->send();
                Yii::$app->end();
            }

        } else {
            $response->statusText = $result['message'];
            $response->setStatusCode(500);
            $response->send();
            Yii::$app->end();
        }
    }

    /**
     * Action for file uploads via sir-trevor image block from SirTrevorWidget (input widget)
     */
    public function actionRedactorUpload()
    {
        //header('Access-Control-Allow-Origin: *');
        /**
         * @var \kato\modules\media\Media $module
         */
        $module = \Yii::$app->controller->module;
        $result = $module->mediaUpload();

        $response = new Response();
        $response->format = Response::FORMAT_JSON;

        if ($result['success'] === true) {

            if ($this->doMediaJoin($result)) {
                //success
                $response->setStatusCode(200);
                $response->data = [
                    'filelink' => '/' . $result['data']['source'],
                ];
                $response->send();
            } else {
                $response->statusText = 'Unable to do join of media with content.';
                $response->send();
                Yii::$app->end();
            }

        } else {
            $response->statusText = $result['message'];
            $response->setStatusCode(500);
            $response->send();
            Yii::$app->end();
        }
    }

    /**
     * Update data information of media
     * @param $id
     * @throws NotFoundHttpException
     */
    public function actionUpdateData($id)
    {
        if ($post = Yii::$app->request->post()) {
            $model = $this->findModel($id);
            $model->$post['name'] = $post['value'];
            if ($model->save(false)) {
                echo 'true';
                exit;
            }
        }
        echo 'false';
    }

    /**
     * Returns list of media in json format
     */
    public function actionListMedia()
    {
        $result = array();

        if (isset($_GET['content_id']) && isset($_GET['content_type'])) {
            //get for modal
            $media = Media::find()
                ->leftJoin('kato_content_media', 'kato_content_media.media_id = kato_media.id')
                ->where(['kato_content_media.content_id' => $_GET['content_id'], 'kato_content_media.content_type' => $_GET['content_type']])
                ->all();
        } else {
            //return all media
            $media = Media::find()->all();
        }

        if ($media) {
            foreach ($media as $data) {
                $result[] = array(
                    'thumb' => '/' . $data->source,
                    'image' => '/' . $data->source,
                    'title' => '/' . $data->filename,
                    //'filelink' => '/' . $data->source,
                );
            }
        }

        echo Json::encode($result);
    }

    /**
     * Get data about requested media and return as row
     * @param $id
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionRenderRow($id)
    {
        $this->layout = false;

        if ($media = $this->findModel($id)) {
            return $this->render('mediaRow', [
                'media' => $media,
                'isNew' => true,
            ]);
        }
        return '';
    }

    /**
     * Deletes an existing Media model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        if (Yii::$app->request->isAjax) {
            echo 'true';
            exit;
        }

        Yii::$app->session->setFlash('success', 'Media has been deleted');

        return $this->redirect(Url::previous());
    }

    /**
     * Finds the Media model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Media the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Media::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


<?php

declare(strict_types=1);

namespace Mapado\RestClientSdk\Mapping;

use Mapado\RestClientSdk\EntityRepository;
use Mapado\RestClientSdk\Exception\MissingIdentifierException;
use Mapado\RestClientSdk\Exception\MoreThanOneIdentifierException;

/**
 * Class ClassMetadata
 *
 * @author Julien Deniau <julien.deniau@mapado.com>
 */
class ClassMetadata
{
    /**
     * Model name (entity class with full namespace, ie: "Foo\Entity\Article").
     *
     * @var string
     */
    private $modelName;

    /**
     * Model key, used as path prefix for API calls.
     *
     * @var string
     */
    private $key;

    /**
     * Repository name (repository class with full namespace, ie: "Foo\Repository\ArticleRepository").
     *
     * @var string
     */
    private $repositoryName;

    /**
     * attributeList
     *
     * @var array<Attribute>
     */
    private $attributeList;

    /**
     * relationList
     *
     * @var array<Relation>
     */
    private $relationList;

    /**
     * identifierAttribute
     *
     * @var ?Attribute
     */
    private $identifierAttribute;

    public function __construct(
        string $key,
        string $modelName,
        ?string $repositoryName = null
    ) {
        $this->key = $key;
        $this->modelName = $modelName;
        $this->repositoryName = $repositoryName ?? EntityRepository::class;
        $this->attributeList = [];
        $this->relationList = [];
    }

    public function getModelName(): string
    {
        return $this->modelName;
    }

    public function setModelName(string $modelName): self
    {
        $this->modelName = $modelName;

        return $this;
    }

    public function getKey(): string
    {
        return $this->key;
    }

    public function setKey(string $key): self
    {
        $this->key = $key;

        return $this;
    }

    public function getAttribute(string $name): ?Attribute
    {
        return $this->attributeList[$name] ?? null;
    }

    public function hasIdentifierAttribute(): bool
    {
        return (bool) $this->identifierAttribute;
    }

    /**
     * @throws MissingIdentifierException
     */
    public function getIdentifierAttribute(): Attribute
    {
        if (!$this->identifierAttribute) {
            throw new MissingIdentifierException(
                sprintf(
                    'Ressource "%s" does not contains an identifier. You can not call %s. You may want to call `hasIdentifierAttribute` before.',
                    $this->modelName,
                    __METHOD__
                )
            );
        }

        return $this->identifierAttribute;
    }

    /**
     * @return array<Attribute>
     */
    public function getAttributeList(): array
    {
        return $this->attributeList;
    }

    /**
     * Setter for attributeList
     *
     * @param  iterable<Attribute> $attributeList
     */
    public function setAttributeList($attributeList): self
    {
        $this->attributeList = [];

        foreach ($attributeList as $attribute) {
            $this->attributeList[$attribute->getSerializedKey()] = $attribute;

            if ($attribute->isIdentifier()) {
                if ($this->identifierAttribute) {
                    throw new MoreThanOneIdentifierException(
                        sprintf(
                            'Class metadata for model "%s" already has an identifier named "%s". Only one identifier is allowed.',
                            $this->modelName,
                            $this->identifierAttribute->getSerializedKey()
                        )
                    );
                }

                $this->identifierAttribute = $attribute;
            }
        }

        return $this;
    }

    /**
     * Getter for relationList
     *
     * @return array<Relation>
     */
    public function getRelationList(): array
    {
        return $this->relationList;
    }

    /**
     * Setter for relationList
     *
     * @param array<Relation> $relationList
     */
    public function setRelationList($relationList): self
    {
        $this->relationList = $relationList;

        return $this;
    }

    public function getRelation(string $key): ?Relation
    {
        if (!empty($this->relationList)) {
            foreach ($this->relationList as $relation) {
                if ($relation->getSerializedKey() == $key) {
                    return $relation;
                }
            }
        }

        return null;
    }

    public function getRepositoryName(): string
    {
        return $this->repositoryName;
    }

    public function setRepositoryName(string $repositoryName): self
    {
        $this->repositoryName = $repositoryName;

        return $this;
    }

    public function getIdGetter(): string
    {
        return 'get' . ucfirst($this->getIdKey());
    }

    public function getIdSerializeKey(): string
    {
        return $this->getIdentifierAttribute()->getSerializedKey();
    }

    /**
     * return default serialize model with null value or empty array on relations
     *
     * @return array<string, array|null>
     */
    public function getDefaultSerializedModel(): array
    {
        $out = [];
        $attributeList = $this->getAttributeList();
        if ($attributeList) {
            foreach ($attributeList as $attribute) {
                $out[$attribute->getSerializedKey()] = null;
            }
        }

        $relationList = $this->getRelationList();
        if ($relationList) {
            foreach ($relationList as $relation) {
                if ($relation->isOneToMany()) {
                    $out[$relation->getSerializedKey()] = [];
                }
            }
        }

        return $out;
    }

    private function getIdKey(): string
    {
        return $this->getIdentifierAttribute()->getAttributeName();
    }
}


<?php

namespace Syahzul\AdminTheme\Commands;

use ErrorException;
use Illuminate\Console\Command;
use Illuminate\Container\Container;
use Illuminate\Support\Facades\File;

class AdminThemeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:admintheme';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Scaffold Laravel Admin Theme controllers, views and other required files';

    /**
     * The Laravel version
     *
     * @var float
     */
    protected $version;

    /**
     * The views that need to be exported.
     *
     * @var array
     */
    protected $views = [
        'auth/login.stub' => 'auth/login.blade.php',
        'auth/register.stub' => 'auth/register.blade.php',
        'auth/passwords/email.stub' => 'auth/passwords/email.blade.php',
        'auth/passwords/reset.stub' => 'auth/passwords/reset.blade.php',

        'emails/password.stub' => 'emails/password.blade.php',

        'errors/404.stub' => 'errors/404.blade.php',
        'errors/500.stub' => 'errors/500.blade.php',
        'errors/503.stub' => 'errors/503.blade.php',

        'layouts/app.stub' => 'layouts/app.blade.php',
        'layouts/basic.stub' => 'layouts/basic.blade.php',
        'layouts/site.stub' => 'layouts/site.blade.php',

        'partials/auth_scripts.stub' => 'partials/auth_scripts.blade.php',
        'partials/control_sidebar.stub' => 'partials/control_sidebar.blade.php',
        'partials/footer.stub' => 'partials/footer.blade.php',
        'partials/header.stub' => 'partials/header.blade.php',
        'partials/login_logo.stub' => 'partials/login_logo.blade.php',
        'partials/main_header.stub' => 'partials/main_header.blade.php',
        'partials/page_heading.stub' => 'partials/page_heading.blade.php',
        'partials/register_logo.stub' => 'partials/register_logo.blade.php',
        'partials/scripts.stub' => 'partials/scripts.blade.php',
        'partials/sidebar.stub' => 'partials/sidebar.blade.php',

        'profile/index.stub' => 'profile/index.blade.php',
        'profile/partials/settings.stub' => 'profile/partials/settings.blade.php',

        'users/index.stub' => 'users/index.blade.php',

        'home.stub' => 'home.blade.php',
        'welcome.stub' => 'welcome.blade.php',
    ];

    /**
     * The controllers that need to be exported.
     *
     * @var array
     */
    protected $controllers = [
        'ProfileController.stub' => 'ProfileController.php',
        'UsersController.stub'   => 'UsersController.php',
    ];

    /**
     * The asset files that need to be exported.
     *
     * @var array
     */
    protected $assets = [
        'resources/assets/less/app.less' => __DIR__.'/../stubs/less/app.stub',
        'resources/assets/less/welcome.less' => __DIR__.'/../stubs/less/welcome.stub',
        'resources/assets/js/app.js' => __DIR__.'/../stubs/js/app.stub',
        'resources/assets/js/dashboard.js' => __DIR__.'/../stubs/js/dashboard.stub',
        'gulpfile.js' => __DIR__.'/../stubs/gulpfile.stub',
    ];

    /**
     * The LESS folder that need to be copied.
     *
     * @var array
     */
    protected $lessSources = [
        'vendor/almasaeed2010/adminlte/build/less' => 'resources/assets/less/adminlte',
        'vendor/twbs/bootstrap/less' => 'resources/assets/less/bootstrap-less',
    ];

    public function __construct()
    {
        parent::__construct();

        $this->version = $this->getLaravelVersion();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        if ($this->checkPackages()) {
            $this->createDirectories();
            $this->exportViews();
            $this->exportControllers();
            $this->exportRoutes();
            $this->copyAssetFiles();
            $this->copyPlugins();
            $this->copyLessFolders();
            $this->copySampleImages();

            $this->comment('AdminTheme scaffolding generated successfully!');
        }
    }

    /**
     * Create the directories for the files.
     *
     * @return void
     */
    protected function createDirectories()
    {
        if (! is_dir(base_path('resources/views/layouts'))) {
            mkdir(base_path('resources/views/layouts'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/emails'))) {
            mkdir(base_path('resources/views/emails'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/errors'))) {
            mkdir(base_path('resources/views/errors'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/partials'))) {
            mkdir(base_path('resources/views/partials'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/profile'))) {
            mkdir(base_path('resources/views/profile'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/profile/partials'))) {
            mkdir(base_path('resources/views/profile/partials'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/users'))) {
            mkdir(base_path('resources/views/users'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/auth/passwords'))) {
            mkdir(base_path('resources/views/auth/passwords'), 0755, true);
        }

        if (! is_dir(public_path('plugins'))) {
            mkdir(public_path('plugins'), 0755, true);
        }

        if (! is_dir(base_path('resources/assets/less'))) {
            mkdir(base_path('resources/assets/less'), 0755, true);
        }

        if (! is_dir(base_path('resources/assets/js'))) {
            mkdir(base_path('resources/assets/js'), 0755, true);
        }
    }

    /**
     * Export the views.
     *
     * @return void
     */
    protected function exportViews()
    {
        foreach ($this->views as $key => $value) {
            $path = base_path('resources/views/'.$value);

            $this->line('<info>View:</info> '.$path);

            try {
                copy(__DIR__ . '/../stubs/views/' . $key, $path);
            } catch (ErrorException $e) {
                $this->error(__DIR__ . '/../stubs/views/' . $key);
                $this->error($path);
            }
        }
    }

    /**
     * Export the controllers.
     *
     * @return void
     */
    protected function exportControllers()
    {
        foreach ($this->controllers as $key => $value) {

            $path = app_path('Http/Controllers/'.$value);

            $this->line('<info>Controller:</info> '.$path);

            file_put_contents(
                app_path('Http/Controllers/'.$value),
                $this->compileControllerStub($key)
            );
        }
    }

    /**
     * Export the routes.
     *
     * @return void
     */
    protected function exportRoutes()
    {
        if ($this->version < 5.3) {
            $routeFile = app_path('Http/routes.php');
            $stubFile = __DIR__.'/../stubs/routes.stub';
        }
        else {
            $routeFile = base_path('routes/web.php');
            $stubFile = __DIR__.'/../stubs/routes/web.stub';
        }

        $routeContent = file_get_contents($routeFile);

        preg_match('/ProfileController@view/', $routeContent, $matches);

        if (! count($matches)) {
            $this->info('Updated Routes File.');

            file_put_contents(
                $routeFile,
                file_get_contents($stubFile),
                FILE_APPEND
            );
        }
    }

    /**
     * Compiles the controller stub.
     *
     * @param $name
     * @return string
     */
    protected function compileControllerStub($name)
    {
        return str_replace(
            '{{namespace}}',
            $this->getAppNamespace(),
            file_get_contents(__DIR__.'/../stubs/controllers/'.$name)
        );
    }

    /**
     * Check all required packages
     *
     * @return bool
     */
    protected function checkPackages()
    {
        if (! is_dir(base_path('vendor/twbs'))) {
            $this->line('');
            $this->line('<error> Error </error> Missing <comment>Bootstrap</comment> package!');
            $this->line('Run: <comment>composer require twbs/bootstrap</comment>'."\n");
            return false;
        }

        if (! is_dir(base_path('vendor/almasaeed2010'))) {
            $this->line('');
            $this->line('<error> Error </error> Missing <comment>AdminLTE</comment> package!');
            $this->line('Run: <comment>composer require almasaeed2010/adminlte</comment>'."\n");
            return false;
        }

        if (! is_dir(base_path('node_modules/jquery'))) {
            $this->line('');
            $this->line('<error> Error </error> Missing <comment>jQuery</comment> package!');
            $this->line('Run: <comment>npm install</comment> or <comment>npm install jquery</comment>'."\n");
            return false;
        }

        if (! is_dir(base_path('node_modules/font-awesome'))) {
            $this->line('');
            $this->line('<error> Error </error> Missing <comment>Font Awesome</comment> package!');
            $this->line('Run: <comment>npm install</comment> or <comment>npm install font-awesome</comment>'."\n");
            return false;
        }

        if (! is_dir(base_path('node_modules/ionicons'))) {
            $this->line('');
            $this->line('<error> Error </error> Missing <comment>IonIcons</comment> package!');
            $this->line('Run: <comment>npm install</comment> or <comment>npm install ionicons</comment>'."\n");
            return false;
        }

        return true;
    }

    /**
     * Copy jQuery plugins folder from AdminLTE package
     */
    protected function copyPlugins()
    {
        $destination = public_path('plugins');

        $this->line('<info>Plugin:</info> ' . $destination);
        File::copyDirectory(base_path('vendor/almasaeed2010/adminlte/plugins'), $destination);
    }

    /**
     * Copy Less and Js files
     */
    protected function copyAssetFiles()
    {
        foreach ($this->assets as $destination => $source) {

            $this->line('<info>Asset:</info> ' . base_path($destination));

            file_put_contents(
                base_path($destination),
                file_get_contents($source)
            );
        }
    }

    /**
     * Copy sample images
     */
    protected function copySampleImages()
    {
        $this->line('<info>Images:</info> ' . public_path('samples'));

        File::copyDirectory(
            base_path('vendor/almasaeed2010/adminlte/dist/img'),
            public_path('img/samples')
        );
    }

    /**
     * Copy Less folders
     */
    protected function copyLessFolders()
    {
        foreach ($this->lessSources as $source => $destination) {

            $this->line('<info>LESS:</info> ' . base_path($destination));

            File::copyDirectory(
                base_path($source),
                base_path($destination)
            );
        }
    }

    /**
     * Get Laravel version based on route file.
     * Not a very good solution to check the version number.
     *
     * @return float
     */
    protected function getLaravelVersion()
    {
        $laravel = app();

        return (float) $laravel::VERSION;
    }

    protected function getAppNamespace()
    {
        return Container::getInstance()->getNamespace();
    }
}


<?php

namespace kato\modules\setting\models;

use Yii;
use kato\modules\setting\Setting as SettingModule;

/**
 * This is the model class for table "kato_setting".
 *
 * @property integer $id
 * @property string $define
 * @property string $value
 * @property string $category
 * @property string $type
 * @property string $options
 */
class Setting extends \kato\ActiveRecord
{
    const TYPE_TEXT_AREA = 'text-area';
    const TYPE_TEXT_FIELD = 'text-field';
    const TYPE_DROP_DOWN = 'drop-down';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'kato_setting';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['define'], 'required'],
            [['value', 'options'], 'string'],
            [['define', 'category', 'type'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'define' => 'Define',
            'value' => 'Value',
            'category' => 'Category',
            'type' => 'Type',
            'options' => 'Options',
        ];
    }

    /*
     * Returns categories defined in module
     */
    public function getCategories()
    {
        $module = SettingModule::getInstance();
        return $module->categories;
    }

    /**
     * @return string
     */
    public function defineEncoded()
    {
        return ucwords(str_replace('_', ' ', $this->define));
    }

    /**
     * Returns settings grouped by categories
     * @return array
     */
    public function getByCategories()
    {
        $data = [
            'categories' => $this->getCategories(),
            'settings' => [],
        ];

        foreach ($data['categories'] as $key => $category) {
            $model = self::find()
                ->where(['category' => $category])
                ->indexBy('id')
                ->all();
            $data['settings'][$category] = $model;
        }

        return $data;
    }

    /**
     * Returns settings value
     * @return string
     */
    public function renderOutput()
    {
        return $this->value;
    }

    /**
     * Returns buttons array to show on redactor editor
     * Eg: can be set in database as comma separated in column options as: html, unorderedlist, link
     * @return array
     */
    public function redactorOptions()
    {
        if (strlen($this->options) > 1) {
            $options = str_replace(' ', '', $this->options);
            return explode(",", $options);
        }

        return ['html', 'formatting', 'bold', 'italic', 'deleted',
            'unorderedlist', 'orderedlist', 'outdent', 'indent',
            'image', 'file', 'link', 'alignment', 'horizontalrule'];
    }

    /**
     * Returns options for dropdown field
     * Eg: can be set in database as comma separated in column options as (key:value): true:Yes, false:No
     * @return array
     */
    public function dropDownOptions()
    {
        $result = [];

        if (strlen($this->options) > 1) {
            $options = str_replace(' ', '', $this->options);
            $optionsArray = explode(",", $options);

            foreach ($optionsArray as $key => $val) {
                $data = explode(':', $val);
                $result[$data[0]] = $data[1];
            }
        }

        return $result;
    }
}


<?php

namespace Nauvalazhar\FacadePlease\Commands;

use Illuminate\Console\Command;
use Artisan;

class FacadePleaseCreate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'facade:please {name?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Laravel 5 Facade Generator';

    /**
     * Detect os for PATH SEPARATOR Issue
     *
     * @return string
     */

    protected $path;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            $this->path = "\\";
        } else {
            $this->path = "/";
        }
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $name = $this->argument('name');
        if(!$name) {
            $name = $this->ask('Facade Name (e.g Email, Alert, etc)');
        }

        $class = $name . 'FacadeServiceProvider';

        $path_provider = app_path('Providers' . $this->path . $class . '.php');

        // Start
        $this->info("\nGenerating '". $name ."' facade ...\n");

        // Checking
        if(file_exists($path_provider)) {
            return $this->error("'" . $name . "' facade already exists!\n");
        }

        // Generate provider
        $this->info("Generating service provider ...\n");
        Artisan::call('make:provider', [
            'name' => $class
        ]);

        // Binding facade name
        $this->info("Binding facade name into a service provider ...\n");
        $serviceProviderData = file_get_contents($path_provider);

        $serviceProviderRep = str_replace('class ' . $class . ' extends ServiceProvider', 'use App;

class ' . $class . ' extends ServiceProvider' . PHP_EOL, $serviceProviderData);

        $serviceProviderExp = explode("public function register()", $serviceProviderRep);
        $serviceProviderExp1 = str_replace("{", "", $serviceProviderExp[1]);
        $serviceProviderRep =  $serviceProviderExp[0] . 'public function register()
    {
        App::bind("'.strtolower($name).'", function()
        {
            return new \App\\'.config('facadeplease.namespace').'\\'.$name.'ClassFacade;
        });' . $serviceProviderExp1;

        file_put_contents($path_provider, $serviceProviderRep);

        // create facade file
        $this->info("Generating core facade file ...\n");
        if(!is_dir(app_path(config('facadeplease.namespace')))) {
            mkdir(app_path(config('facadeplease.namespace')));
        }
        $facade = fopen(app_path(config('facadeplease.namespace') . $this->path .$name.'Facade.php'), 'w');
        $facadeData = "<?php
namespace App\\".config('facadeplease.namespace').";
use Illuminate\Support\Facades\Facade;
class ".$name."Facade extends Facade {
    protected static function getFacadeAccessor() {
        return '".strtolower($name)."';
    }
}";
        fwrite($facade, $facadeData);
        fclose($facade);

        // create facadeclass file
        $this->info("Generating facade file ...\n");
        $facade = fopen(app_path(config('facadeplease.namespace'). $this->path .$name.'ClassFacade.php'), 'w');
        $facadeData = "<?php
namespace App\\".config('facadeplease.namespace').";

class ".$name."ClassFacade {
    public function hello() {
        return \"Hello, my name is ".$name."!\";
    }
}";
        fwrite($facade, $facadeData);
        fclose($facade);

        // add to config
        $this->info("Registering the facade into the config file ...\n");
        $config = config_path('app.php');
        $configdata = file_get_contents($config);
        $configdata = explode("],", $configdata);
        $last_char1 = substr(trim($configdata[0]), -1);
        $last_char2 = substr(trim($configdata[1]), -1);
        $alias = trim($configdata[0]) . ($last_char1 !== ',' ? ',' : '') . '
        App\Providers\\'.$class.'::class,
],';
        $facade = trim($configdata[1]) . ($last_char2 !== ',' ? ',' : '') . "
        '".$name."' => App\\".config('facadeplease.namespace')."\\".$name."Facade::class,
    ],
];";
        $datatopush = $alias . $facade;
        file_put_contents(config_path('app.php'), $datatopush);

        $this->info("\nDumping the Autoloader..\n");
        exec('composer dump-autoload -o');

        $this->info("Facade `" . $name . "` generated successfully.\n");
        $this->info("\nUsage:\nuse App\\".config('facadeplease.namespace')."\\".$name.";\n" . $name . "::hello();");

        $this->info("\nDone!");
    }
}


<?php

namespace kato\components;

use backend\models\Page;
use Yii;
use kato\modules\setting\models\Setting;
use yii\helpers\HtmlPurifier;

/**
 * Usage
 * -----
 *
 * In your configuration file, add the setting component.
 *
 * ```php
 * 'components' => [
 *    ...
 *    'kato' => 'kato\components\Kato',
 *    ...
 * ]
 * ```
 */
class Kato extends \yii\base\Component
{

    /**
     * Get settings for Kato
     * Usage:
     *
     * ```php
     * $setting = Yii::$app->kato->setting('site_name');
     * ```
     * @param $key
     * @return bool
     */
    public static function setting($key)
    {
        $model = Setting::find()
            ->where(['define' => $key])
            ->one();

        if (!is_null($model)) {
            return $model->renderOutput();
        }

        return false;
    }

    /**
     * returns page slug if set
     * @return string
     */
    public function pageSlug()
    {
        if (isset($_GET['slug'])) {
            return HtmlPurifier::process($_GET['slug']);
        }
        return false;
    }

    public function menuItems()
    {
        $items = [];

        $pages = Page::find()
            ->where([
                'parent_id' => 0,
                'menu_hidden' => Page::MENU_HIDDEN_NO,
                'status' => Page::STATUS_PUBLISHED,
                'deleted' => 0,
                'revision_to' => 0,
            ])
            ->orderBy('listing_order ASC')
            ->all();

        foreach ($pages as $page) {
            $items[] = $this->renderMenuItem($page);
        }

        return $items;
    }

    private function menuChildren($childern)
    {
        $items = [];
        foreach ($childern as $page) {
            $items[] = $this->renderMenuItem($page);
        }

        return $items;
    }

    private function renderMenuItem($page)
    {
        $item = ['label' => $page->menu_title, 'url' => $page->permalink, 'active' => false];

        if ($page->type === Page::TYPE_STATIC) {
            if ($page->slug == Yii::$app->kato->pageSlug()) {
                $item['active'] = true;
            }
        } else {
            if ('/' . $page->slug == \Yii::$app->request->getUrl()) {
                $item['active'] = true;
            }
        }

        if ($page->menuChildren) {
            $item['items'] = $this->menuChildren($page->menuChildren);
        }

        return $item;
    }

}


<?php

/**
 * Contao Bootstrap
 *
 * @package    contao-bootstrap
 * @subpackage Tab
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2013-2018 netzmacht David Molineus. All rights reserved.
 * @license    LGPL-3.0 https://github.com/contao-bootstrap/tab
 * @filesource
 */

declare(strict_types=1);

namespace ContaoBootstrap\Tab\View\Tab;

use Contao\StringUtil;
use ContaoBootstrap\Tab\View\Tab\Item\Dropdown;
use ContaoBootstrap\Tab\View\Tab\Item\NavItem;

/**
 * Class Navigation
 */
final class Navigation implements ItemList
{
    /**
     * Navigation items.
     *
     * @var array
     */
    private $items = [];

    /**
     * Create instance from a serialized definition
     *
     * @param string $definition Serialized definition.
     * @param string $tabId      Tab id as string, used as css id suffix.
     *
     * @return Navigation
     */
    public static function fromSerialized(string $definition, string $tabId): self
    {
        $navigation = new Navigation();
        $current    = $navigation;
        $definition = StringUtil::deserialize($definition, true);
        $cssIds     = [];

        foreach ($definition as $index => $tab) {
            if (!$tab['cssId']) {
                $tab['cssId']  = StringUtil::standardize($tab['title']);
                $tab['cssId'] .= '-' . $tabId;

                if (in_array($tab['cssId'], $cssIds)) {
                    $tab['cssId'] .= '-' . $index;
                }
            }

            if ($tab['type'] === 'dropdown') {
                $item    = Dropdown::fromArray($tab);
                $current = $item;

                $navigation->addItem($item);
            } else {
                if ($tab['type'] !== 'child') {
                    $current = $navigation;
                }

                $item = NavItem::fromArray($tab);
                $current->addItem($item);
            }
        }

        return $navigation;
    }

    /**
     * {@inheritdoc}
     */
    public function addItem(NavItem $item): ItemList
    {
        $this->items[] = $item;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function items(): array
    {
        return $this->items;
    }
}


<?php

/**
 * Contao Bootstrap
 *
 * @package    contao-bootstrap
 * @subpackage Tab
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2013-2018 netzmacht David Molineus. All rights reserved.
 * @license    LGPL-3.0 https://github.com/contao-bootstrap/tab
 * @filesource
 */

declare(strict_types=1);

namespace ContaoBootstrap\Tab\View\Tab\Item;

use Contao\StringUtil;

/**
 * Class Item
 */
class NavItem
{
    /**
     * Navigation item title.
     *
     * @var string
     */
    private $title;

    /**
     * Css id.
     *
     * @var string
     */
    private $cssId;

    /**
     * Nav css id.
     *
     * @var string
     */
    private $navCssId;

    /**
     * Active item.
     *
     * @var bool
     */
    private $active;

    /**
     * Item constructor.
     *
     * @param string      $title    Title of the nav item.
     * @param bool        $active   Active state.
     * @param string|null $cssId    Css id.
     * @param string|null $navCssId Nav css id.
     */
    public function __construct(string $title, bool $active = false, string $cssId = null, string $navCssId = null)
    {
        $this->title    = $title;
        $this->cssId    = $cssId ?: StringUtil::standardize($title);
        $this->navCssId = $navCssId ?: $this->cssId . '-tab';
        $this->active   = $active;
    }

    /**
     * Create nav item from an array definition.
     *
     * @param array $definition The array definition.
     *
     * @return NavItem
     */
    public static function fromArray(array $definition): NavItem
    {
        return new static(
            $definition['title'],
            (bool) $definition['active'],
            $definition['cssId'] ?? null,
            $definition['navCssId'] ?? null
        );
    }

    /**
     * Get the title.
     *
     * @return string
     */
    public function title(): string
    {
        return $this->title;
    }

    /**
     * Get the navigation item css id.
     *
     * @return string
     */
    public function navCssId(): string
    {
        return $this->navCssId;
    }

    /**
     * Get the css id.
     *
     * @return string
     */
    public function cssId(): string
    {
        return $this->cssId;
    }

    /**
     * Active state.
     *
     * @return bool
     */
    public function active(): bool
    {
        return $this->active;
    }
}


<?php

namespace kato\web;

use backend\models\Block;
use backend\models\Page;
use Yii;
use yii\web\BadRequestHttpException;

class View extends \yii\web\View
{
    public $description;
    public $pageIcon;

    /**
     * Register required components for admin theme
     */
    /*public function registerTheme()
    {
        $this->registerMetaTag([
            'charset' => Yii::$app->charset,
        ]);
        $this->registerMetaTag([
            'name' => 'robots',
            'content' => 'noindex, nofollow',
        ]);
        $this->registerMetaTag([
            'name' => 'viewport',
            'content' => 'width=device-width, initial-scale=1',
        ]);

        //The Open Sans font is included from Google Web Fonts
        $this->registerLinkTag([
            'rel' => 'stylesheet',
            'href' => 'http://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,700,700italic',
        ]);
    }*/

    /**
     * finds and return content of requested block by name
     * @param $name
     * @param bool $isGlobal
     * @return bool|string
     * @throws BadRequestHttpException
     */
    public function loadBlock($name, $isGlobal = false)
    {
        if (is_null($name)) {
            throw new BadRequestHttpException('Block name not specified.');
        }

        $find = [
            'title' => $name,
        ];

        if ($isGlobal === false) {
            //if not global
            if (isset($this->params['block']['id'])) {
                $find['parent'] = $this->params['block']['id'];
            }
            if (isset($this->params['block']['layout'])) {
                $find['parent_layout'] = $this->params['block']['layout'];
            }

            if (isset($this->params['block']['slug'])) {
                //get parent page id
                /**
                 * @var $page \backend\models\Page
                 */
                if ($page = Page::findOne([
                    'slug' => $this->params['block']['slug'],
                ])) {
                    $find['parent'] = $page->id;
                }
            }
        }

        /**
         * @var $block \backend\models\Block
         */
        if ($block = Block::findOne($find)) {
            //if block found
            return $block->render();
        }

        return false;
    }
}


<?php

namespace kato\modules\sitemap\widgets;

use kato\modules\sitemap\Sitemap;
use Yii;
use yii\base\Widget;

class SitemapWidget extends Widget
{
    public $moduleName = 'sitemap';

    /**
     * Gets the module
     * @param $m
     * @return null|\yii\base\Module
     */
    public function getModule($m)
    {
        $mod = Yii::$app->controller->module;
        return $mod && $mod->getModule($m) ? $mod->getModule($m) : Yii::$app->getModule($m);
    }

    public function run()
    {
        /** @var \kato\modules\sitemap\Sitemap $module */
        $module = $this->getModule($this->moduleName);
        $sitemapData = $module->buildSitemap(true); //as array

        return $this->render('sitemap', [
            'data' => $sitemapData,
        ]);
    }
}


<?php

declare(strict_types=1);

namespace Mapado\RestClientSdk\Model;

use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;
use Mapado\RestClientSdk\Exception\SdkException;
use Mapado\RestClientSdk\Helper\ArrayHelper;
use Mapado\RestClientSdk\Mapping;
use Mapado\RestClientSdk\Mapping\ClassMetadata;
use Mapado\RestClientSdk\SdkClient;
use Mapado\RestClientSdk\UnitOfWork;

/**
 * Class Serializer
 *
 * @author Julien Deniau <julien.deniau@mapado.com>
 */
class Serializer
{
    /**
     * mapping
     *
     * @var Mapping
     */
    private $mapping;

    /**
     * @var SdkClient
     */
    private $sdk;

    /**
     * @var UnitOfWork
     */
    private $unitOfWork;

    public function __construct(Mapping $mapping, UnitOfWork $unitOfWork)
    {
        $this->mapping = $mapping;
        $this->unitOfWork = $unitOfWork;
    }

    /**
     * @required
     */
    public function setSdk(SdkClient $sdk): self
    {
        $this->sdk = $sdk;

        return $this;
    }

    /**
     * serialize entity for POST and PUT
     */
    public function serialize(
        object $entity,
        string $modelName,
        array $context = []
    ): array {
        $out = $this->recursiveSerialize($entity, $modelName, 0, $context);

        if (is_string($out)) {
            throw new \RuntimeException(
                'recursiveSerialize should return an array for level 0 of serialization. This should not happen.'
            );
        }

        return $out;
    }

    public function deserialize(array $data, string $className): object
    {
        $className = $this->resolveRealClassName($data, $className);

        $classMetadata = $this->mapping->getClassMetadata($className);

        $attributeList = $classMetadata->getAttributeList();

        $instance = new $className();

        if ($attributeList) {
            foreach ($attributeList as $attribute) {
                $key = $attribute->getSerializedKey();

                if (!ArrayHelper::arrayHas($data, $key)) {
                    continue;
                }

                $value = ArrayHelper::arrayGet($data, $key);

                $setter = 'set' . ucfirst($attribute->getAttributeName());

                if (method_exists($instance, $setter)) {
                    $relation = $classMetadata->getRelation($key);
                    if ($relation) {
                        if (is_string($value)) {
                            $value = $this->sdk->createProxy($value);
                        } elseif (is_array($value)) {
                            $targetEntity = $relation->getTargetEntity();
                            $relationClassMetadata = $this->mapping->getClassMetadata(
                                $targetEntity
                            );

                            if ($relation->isManyToOne()) {
                                $value = $this->deserialize(
                                    $value,
                                    $relationClassMetadata->getModelName()
                                );
                            } else {
                                // One-To-Many association
                                $list = [];
                                foreach ($value as $item) {
                                    if (is_string($item)) {
                                        $list[] = $this->sdk->createProxy(
                                            $item
                                        );
                                    } elseif (is_array($item)) {
                                        $list[] = $this->deserialize(
                                            $item,
                                            $relationClassMetadata->getModelName()
                                        );
                                    }
                                }

                                $value = $list;
                            }
                        }
                    }

                    if (isset($value)) {
                        if ('datetime' === $attribute->getType()) {
                            $value = new \DateTime($value);
                        }

                        $instance->{$setter}($value);
                    }
                }
            }
        }

        $classMetadata = $this->getClassMetadata($instance);
        if ($classMetadata->hasIdentifierAttribute()) {
            $idGetter = $classMetadata->getIdGetter();

            if ($idGetter) {
                $callable = [$instance, $idGetter];
                $identifier = is_callable($callable)
                    ? call_user_func($callable)
                    : null;

                if ($identifier) {
                    $this->unitOfWork->registerClean($identifier, $instance);
                }
            }
        }

        return $instance;
    }

    /**
     * If provided class name is abstract (a base class), the real class name (child class)
     * may be available in some data fields.
     */
    private function resolveRealClassName(
        array $data,
        string $className
    ): string {
        if (!empty($data['@id'])) {
            $classMetadata = $this->mapping->tryGetClassMetadataById(
                $data['@id']
            );

            if ($classMetadata) {
                return $classMetadata->getModelName();
            }
        }

        // Real class name could also be retrieved from @type property.
        return $className;
    }

    /**
     * @return array|string
     */
    private function recursiveSerialize(
        object $entity,
        string $modelName,
        int $level = 0,
        array $context = []
    ) {
        $classMetadata = $this->mapping->getClassMetadata($modelName);

        if ($level > 0 && empty($context['serializeRelation'])) {
            if ($classMetadata->hasIdentifierAttribute()) {
                $tmpId = $entity->{$classMetadata->getIdGetter()}();
                if ($tmpId) {
                    return $tmpId;
                }
            }
        }

        $attributeList = $classMetadata->getAttributeList();

        $out = [];
        if (!empty($attributeList)) {
            foreach ($attributeList as $attribute) {
                $method = 'get' . ucfirst($attribute->getAttributeName());

                if ($attribute->isIdentifier() && !$entity->{$method}()) {
                    continue;
                }
                $relation = $classMetadata->getRelation(
                    $attribute->getSerializedKey()
                );

                $data = $entity->{$method}();

                if (
                    null === $data &&
                    $relation &&
                    $relation->isManyToOne() &&
                    $level > 0
                ) {
                    /*
                        We only serialize the root many-to-one relations to prevent, hopefully,
                        unlinked and/or duplicated content. For instance, a cart with cartItemList containing
                        null values for the cart [{ cart => null, ... }] may lead the creation of
                        CartItem entities explicitly bound to a null Cart instead of the created/updated Cart.
                     */
                    continue;
                } elseif ($data instanceof \DateTime) {
                    $data = $data->format('c');
                } elseif (is_object($data) && $data instanceof PhoneNumber) {
                    $phoneNumberUtil = PhoneNumberUtil::getInstance();
                    $data = $phoneNumberUtil->format(
                        $data,
                        PhoneNumberFormat::INTERNATIONAL
                    );
                } elseif (
                    is_object($data) &&
                    $relation &&
                    $this->mapping->hasClassMetadata(
                        $relation->getTargetEntity()
                    )
                ) {
                    $relationClassMetadata = $this->mapping->getClassMetadata(
                        $relation->getTargetEntity()
                    );

                    if (!$relationClassMetadata->hasIdentifierAttribute()) {
                        $data = $this->recursiveSerialize(
                            $data,
                            $relation->getTargetEntity(),
                            $level + 1,
                            $context
                        );
                    } else {
                        $idAttribute = $relationClassMetadata->getIdentifierAttribute();
                        $idGetter =
                            'get' . ucfirst($idAttribute->getAttributeName());

                        if (
                            method_exists($data, $idGetter) &&
                            $data->{$idGetter}()
                        ) {
                            $data = $data->{$idGetter}();
                        } elseif ($relation->isManyToOne()) {
                            if ($level > 0) {
                                continue;
                            } else {
                                throw new SdkException(
                                    'Case not allowed for now'
                                );
                            }
                        }
                    }
                } elseif (is_array($data)) {
                    $newData = [];
                    foreach ($data as $key => $item) {
                        if ($item instanceof \DateTime) {
                            $newData[$key] = $item->format('c');
                        } elseif (
                            is_object($item) &&
                            $relation &&
                            $this->mapping->hasClassMetadata(
                                $relation->getTargetEntity()
                            )
                        ) {
                            $serializeRelation =
                                !empty($context['serializeRelations']) &&
                                in_array(
                                    $relation->getSerializedKey(),
                                    $context['serializeRelations']
                                );

                            $newData[$key] = $this->recursiveSerialize(
                                $item,
                                $relation->getTargetEntity(),
                                $level + 1,
                                ['serializeRelation' => $serializeRelation]
                            );
                        } else {
                            $newData[$key] = $item;
                        }
                    }
                    $data = $newData;
                }

                $key = $attribute->getSerializedKey();

                $out[$key] = $data;
            }
        }

        return $out;
    }

    private function getClassMetadataFromId(string $id): ?ClassMetadata
    {
        $key = $this->mapping->getKeyFromId($id);

        return $this->mapping->getClassMetadataByKey($key);
    }

    private function getClassMetadata(object $entity): ClassMetadata
    {
        return $this->mapping->getClassMetadata(get_class($entity));
    }
}


<?php

/**
 * Contao Bootstrap
 *
 * @package    contao-bootstrap
 * @subpackage Tab
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2013-2018 netzmacht David Molineus. All rights reserved.
 * @license    LGPL-3.0 https://github.com/contao-bootstrap/tab
 * @filesource
 */

declare(strict_types=1);

namespace ContaoBootstrap\Tab\View\Tab\Item;

use ContaoBootstrap\Tab\View\Tab\ItemList;

/**
 * Class Dropdown
 */
final class Dropdown extends NavItem implements ItemList
{
    /**
     * Dropdown items.
     *
     * @var array|NavItem[]
     */
    private $items = [];

    /**
     * {@inheritdoc}
     */
    public function items(): array
    {
        return $this->items;
    }

    /**
     * {@inheritdoc}
     */
    public function addItem(NavItem $navItem): ItemList
    {
        $this->items[] = $navItem;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function active(): bool
    {
        foreach ($this->items as $item) {
            if ($item->active()) {
                return true;
            }
        }

        return false;
    }
}


<?php

declare(strict_types=1);

namespace Mapado\RestClientSdk;

use Mapado\RestClientSdk\Exception\MappingException;
use Mapado\RestClientSdk\Mapping\ClassMetadata;

/**
 * Class Mapping
 *
 * @author Julien Deniau <julien.deniau@mapado.com>
 */
class Mapping
{
    public const DEFAULT_CONFIG = ['collectionKey' => 'hydra:member'];

    /**
     * @var string
     */
    private $idPrefix;

    /**
     * @var int
     */
    private $idPrefixLength;

    /**
     * @var array<ClassMetadata>
     */
    private $classMetadataList = [];

    /**
     * @var array
     */
    private $config;

    public function __construct(string $idPrefix = '', array $config = [])
    {
        $this->idPrefix = $idPrefix;
        $this->idPrefixLength = mb_strlen($idPrefix);
        $this->setConfig($config);
    }

    public function getIdPrefix(): string
    {
        return $this->idPrefix;
    }

    public function getConfig(): array
    {
        return $this->config;
    }

    public function setConfig(array $config): self
    {
        $this->config = array_merge(self::DEFAULT_CONFIG, $config);

        return $this;
    }

    /**
     * @param array<ClassMetadata> $classMetadataList
     */
    public function setMapping(array $classMetadataList): self
    {
        $this->classMetadataList = $classMetadataList;

        return $this;
    }

    /**
     * return a model class name for a given key
     */
    public function getModelName(string $key): string
    {
        $this->checkMappingExistence($key, true);

        /** @var ClassMetadata */
        $classMetadata = $this->getClassMetadataByKey($key);

        return $classMetadata->getModelName();
    }

    /**
     * return the list of mapping keys
     *
     * @return array<string>
     */
    public function getMappingKeys(): array
    {
        return array_map(function (ClassMetadata $classMetadata) {
            return $classMetadata->getKey();
        }, $this->classMetadataList);
    }

    /**
     * get the key from an id (path)
     */
    public function getKeyFromId(string $id): string
    {
        $key = $this->parseKeyFromId($id);
        if (null === $key) {
            throw new MappingException("Unable to parse key from id {$id}.");
        }

        $this->checkMappingExistence($key);

        return $key;
    }

    /**
     * @param string $modelName model name
     *
     * @throws MappingException
     */
    public function getKeyFromModel(string $modelName): string
    {
        foreach ($this->classMetadataList as $classMetadata) {
            if ($modelName === $classMetadata->getModelName()) {
                return $classMetadata->getKey();
            }
        }

        throw new MappingException(
            'Model name ' . $modelName . ' not found in mapping'
        );
    }

    /**
     * getClassMetadata for model name
     *
     * @throws MappingException
     */
    public function getClassMetadata(string $modelName): ClassMetadata
    {
        foreach ($this->classMetadataList as $classMetadata) {
            if ($modelName === $classMetadata->getModelName()) {
                return $classMetadata;
            }
        }

        throw new MappingException($modelName . ' model is not mapped');
    }

    /**
     * getClassMetadata for id
     */
    public function tryGetClassMetadataById(string $id): ?ClassMetadata
    {
        $key = $this->parseKeyFromId($id);

        foreach ($this->classMetadataList as $classMetadata) {
            if ($key === $classMetadata->getKey()) {
                return $classMetadata;
            }
        }

        return null;
    }

    public function hasClassMetadata(string $modelName): bool
    {
        foreach ($this->classMetadataList as $classMetadata) {
            if ($modelName === $classMetadata->getModelName()) {
                return true;
            }
        }

        return false;
    }

    public function getClassMetadataByKey(string $key): ?ClassMetadata
    {
        foreach ($this->classMetadataList as $classMetadata) {
            if ($key === $classMetadata->getKey()) {
                return $classMetadata;
            }
        }

        return null;
    }

    /**
     * Parse the key from an id (path)
     */
    private function parseKeyFromId(string $id): ?string
    {
        $id = $this->removePrefix($id);

        $matches = [];
        if (1 === preg_match('|/([^/]+)/[^/]+$|', $id, $matches)) {
            return $matches[1];
        }

        return null;
    }

    private function checkMappingExistence(
        string $key,
        bool $checkModelName = false
    ): void {
        if (empty($key)) {
            throw new MappingException('key is not set');
        }

        $metadata = $this->getClassMetadataByKey($key);
        if (!$metadata) {
            throw new MappingException($key . ' key is not mapped');
        }

        if ($checkModelName) {
            if ('' === $metadata->getModelName()) {
                throw new MappingException(
                    $key . ' key is mapped but the model name is empty'
                );
            }
        }
    }

    private function removePrefix(string $value): string
    {
        if (
            ($this->idPrefixLength > 0) &&
            (0 === mb_strpos($value, $this->idPrefix))
        ) {
            return mb_substr($value, $this->idPrefixLength);
        }

        return $value;
    }
}


<?php

namespace kato\widgets;

use yii\base\Widget;
use backend\models\Page;

class PageTreeWidget extends Widget
{
    /**
     * @return string
     */
    public function run()
    {
        return $this->render('pageTree', [
            'dataProvider' => $this->renderTree(),
        ]);
    }

    /**
     * Returns hierarchical data of pages
     * @param int $parentId
     * @return array
     */
    private function renderTree($parentId = 0)
    {
        $query = Page::find();
        $query->andWhere(['deleted' => 0, 'revision_to' => 0, 'parent_id' => $parentId]);
        $query->orderBy('title ASC');

        if (($pages = $query->all()) == null) {
            //empty array if no data found
            return [];
        }

        $tree = $this->getBranch($pages, true);

        return $tree;
    }

    /**
     * Returns the given pages as a branch.
     * @param $pages
     * @return array
     */
    protected function getBranch($pages)
    {
        $result = [];

        foreach ($pages as $page) {
            $result[] = array('model' => $page, 'children' => $this->renderTree($page->id));
        }

        return $result;
    }

    private function registerCss()
    {
        $this->registerCss("body { background: #f00; }");
    }
}


<?php

namespace bupy7\bbcode\validators;

use JBBCode\InputValidator;

/**
 * An NumberValidator for number values.
 *
 * @author Belosludcev Vasilij http://github.com/bupy7
 * @version 1.1
 */
class NumberValidator implements InputValidator
{

    /**
     * @var mixed Minimum value of input.
     */
    public $min;

    /**
     * @var mixed Maximum value of input.
     */
    public $max;

    /**
     * @var mixed Equal value of input.
     */
    public $eq;

    public $integerOnly = false;

    public function __construct($config = [])
    {
        foreach ($config as $name => $value) {
            if (property_exists($this, $name)) {
                $this->{$name} = $value;
            }
        }
    }

    /**
     * Returns true if $input uses only number value
     * characters.
     *
     * @param $input the string to validate
     */
    public function validate($input)
    {
        if (!preg_match('/^[\d]+$/', $input)) {
            return false;
        }
        if ($this->integerOnly) {
            if (!is_int($input + 0)) {
                return false;
            }
        }
        if (!isset($this->eq)) {
            if (isset($this->max) && !isset($this->min)) {
                if ($input > $this->max) {
                    return false;
                }
            }
            if (!isset($this->max) && isset($this->min)) {
                if ($input < $this->min) {
                    return false;
                }
            }
            if (isset($this->max) && isset($this->min)) {
                if ($input < $this->min || $input > $this->max) {
                    return false;
                }
            }
        } else {
            if ($input != $this->eq) {
                return false;
            }
        }
        return true;
    }

}


<?php

namespace kato\modules\media\components;

use kato\modules\media\models\Media;
use Yii;

/**
 * Usage
 * -----
 *
 * In your configuration file, add the setting component.
 *
 * ```php
 * 'components' => [
 *    ...
 *    'media' => 'kato\modules\media\components\MediaRender',
 *    ...
 * ]
 * ```
 */
class MediaRender extends \yii\base\Component
{

    /**
     * Render remote images
     * Usage: echo Yii::$app->media->render('HTTP://URL_TO_IMAGE_HERE.JPG')
     * @param $imgSrc
     * @param array $data
     * @return bool|string
     */
    public function render($imgSrc, $data = [])
    {
        $media = new Media();
        $media->mimeType = 'image/jpeg';
        $media->filename = basename($imgSrc);
        if (strpos($imgSrc,'files') !== false) {
            $media->source =  ltrim($imgSrc);
        } else {
            $media->source =  'frontend/web' . $imgSrc;
        }

        return $media->render($data);
    }

}


<?php

declare(strict_types=1);

namespace Mapado\RestClientSdk;

use Mapado\RestClientSdk\Collection\Collection;
use Mapado\RestClientSdk\Exception\HydratorException;
use Mapado\RestClientSdk\Exception\RestException;
use Mapado\RestClientSdk\Exception\SdkException;
use Mapado\RestClientSdk\Exception\UnexpectedTypeException;
use Mapado\RestClientSdk\Helper\ArrayHelper;
use Mapado\RestClientSdk\Mapping\ClassMetadata;

class EntityRepository
{
    /**
     * REST Client.
     *
     * @var RestClient
     */
    protected $restClient;

    /**
     * SDK Client.
     *
     * @var SdkClient
     */
    protected $sdk;

    /**
     * @var string
     */
    protected $entityName;

    /**
     * classMetadataCache
     *
     * @var ClassMetadata
     */
    private $classMetadataCache;

    /**
     * unitOfWork
     *
     * @var UnitOfWork
     */
    private $unitOfWork;

    /**
     * EntityRepository constructor
     *
     * @param SdkClient  $sdkClient  The client to connect to the datasource with
     * @param RestClient $restClient The client to process the http requests
     * @param string     $entityName The entity to work with
     */
    public function __construct(
        SdkClient $sdkClient,
        RestClient $restClient,
        UnitOfWork $unitOfWork,
        string $entityName
    ) {
        $this->sdk = $sdkClient;
        $this->restClient = $restClient;
        $this->unitOfWork = $unitOfWork;
        $this->entityName = $entityName;
    }

    /**
     * Adds support for magic finders.
     *
     * @return array|object|null the found entity/entities
     */
    public function __call(string $method, array $arguments)
    {
        switch (true) {
            case 0 === mb_strpos($method, 'findBy'):
                $fieldName = mb_strtolower(mb_substr($method, 6));
                $methodName = 'findBy';
                break;

            case 0 === mb_strpos($method, 'findOneBy'):
                $fieldName = mb_strtolower(mb_substr($method, 9));
                $methodName = 'findOneBy';
                break;

            default:
                throw new \BadMethodCallException(
                    'Undefined method \'' .
                    $method .
                    '\'. The method name must start with
                    either findBy or findOneBy!'
                );
        }

        if (empty($arguments)) {
            throw new SdkException(
                'You need to pass a parameter to ' . $method
            );
        }

        $mapping = $this->sdk->getMapping();
        $key = $mapping->getKeyFromModel($this->entityName);
        $prefix = $mapping->getIdPrefix();
        $path = empty($prefix) ? '/' . $key : $prefix . '/' . $key;

        if (!empty($fieldName)) {
            $queryParams = [$fieldName => current($arguments)];
        } else {
            $queryParams = current($arguments);
        }
        $path .=
            '?' . http_build_query($this->convertQueryParameters($queryParams));

        // if entityList is found in cache, return it
        $entityListFromCache = $this->fetchFromCache($path);
        if (false !== $entityListFromCache) {
            return $entityListFromCache;
        }

        $data = $this->restClient->get($path);
        // $data = $this->assertArray($data, $methodName);
        $hydrator = $this->sdk->getModelHydrator();

        if ('findOneBy' == $methodName) {
            // If more results are found but one is requested return the first hit.
            $collectionKey = $mapping->getConfig()['collectionKey'];

            $data = $this->assertArray($data, __METHOD__);
            $entityList = ArrayHelper::arrayGet($data, $collectionKey);
            if (!empty($entityList)) {
                $data = current($entityList);
                $hydratedData = $hydrator->hydrate($data, $this->entityName);

                $identifier = $hydratedData->{$this->getClassMetadata()->getIdGetter()}();
                if (null !== $hydratedData) {
                    $this->unitOfWork->registerClean(
                        $identifier,
                        $hydratedData
                    );
                }
                $this->saveToCache($identifier, $hydratedData);
            } else {
                $hydratedData = null;
            }
        } else {
            $data = $this->assertNotObject($data, __METHOD__);
            $hydratedData = $hydrator->hydrateList($data, $this->entityName);

            // then cache each entity from list
            foreach ($hydratedData as $entity) {
                $identifier = $entity->{$this->getClassMetadata()->getIdGetter()}();
                $this->saveToCache($identifier, $entity);
                $this->unitOfWork->registerClean($identifier, $entity);
            }
        }

        $this->saveToCache($path, $hydratedData);

        return $hydratedData;
    }

    /**
     * find - finds one item of the entity based on the @REST\Id field in the entity
     *
     * @param string|int|mixed $id          id of the element to fetch
     * @param array  $queryParams query parameters to add to the query
     */
    public function find($id, array $queryParams = []): ?object
    {
        $hydrator = $this->sdk->getModelHydrator();
        $id = $hydrator->convertId($id, $this->entityName);

        $id = $this->addQueryParameter($id, $queryParams);

        // if entity is found in cache, return it
        $entityFromCache = $this->fetchFromCache($id);
        if (false != $entityFromCache) {
            return $entityFromCache;
        }

        $data = $this->restClient->get($id);
        $data = $this->assertNotObject($data, __METHOD__);

        $entity = $hydrator->hydrate($data, $this->entityName);

        // cache entity
        $this->saveToCache($id, $entity);
        if (null !== $entity) {
            $this->unitOfWork->registerClean($id, $entity); // another register clean will be made in the Serializer if the id different from the called uri
        }

        return $entity;
    }

    public function findAll(): Collection
    {
        $mapping = $this->sdk->getMapping();
        $key = $this->getClassMetadata()->getKey();
        $prefix = $mapping->getIdPrefix();
        $path = empty($prefix) ? '/' . $key : $prefix . '/' . $key;

        $entityListFromCache = $this->fetchFromCache($path);

        // if entityList is found in cache, return it
        if (false !== $entityListFromCache) {
            if (!$entityListFromCache instanceof Collection) {
                throw new \RuntimeException(
                    'Entity list in cache should be an instance of ' .
                    Collection::class .
                    '. This should not happen.'
                );
            }

            return $entityListFromCache;
        }

        $data = $this->restClient->get($path);
        $data = $this->assertNotObject($data, __METHOD__);

        $hydrator = $this->sdk->getModelHydrator();
        $entityList = $hydrator->hydrateList($data, $this->entityName);

        // cache entity list
        $this->saveToCache($path, $entityList);

        // then cache each entity from list
        foreach ($entityList as $entity) {
            $identifier = $entity->{$this->getClassMetadata()->getIdGetter()}();
            $this->unitOfWork->registerClean($identifier, $entity);
            $this->saveToCache($identifier, $entity);
        }

        return $entityList;
    }

    /**
     * remove entity
     *
     * @TODO STILL NEEDS TO BE CONVERTED TO ENTITY MODEL
     */
    public function remove(object $model): void
    {
        $identifier = $model->{$this->getClassMetadata()->getIdGetter()}();
        $this->removeFromCache($identifier);
        $this->unitOfWork->clear($identifier);

        $this->restClient->delete($identifier);
    }

    public function update(
        object $model,
        array $serializationContext = [],
        array $queryParams = []
    ): object {
        $identifier = $model->{$this->getClassMetadata()->getIdGetter()}();
        $serializer = $this->sdk->getSerializer();
        $newSerializedModel = $serializer->serialize(
            $model,
            $this->entityName,
            $serializationContext
        );

        $oldModel = $this->unitOfWork->getDirtyEntity($identifier);
        if ($oldModel) {
            $oldSerializedModel = $serializer->serialize(
                $oldModel,
                $this->entityName,
                $serializationContext
            );
            $newSerializedModel = $this->unitOfWork->getDirtyData(
                $newSerializedModel,
                $oldSerializedModel,
                $this->getClassMetadata()
            );
        }

        $path = $this->addQueryParameter($identifier, $queryParams);

        $data = $this->restClient->put($path, $newSerializedModel);
        $data = $this->assertArray($data, __METHOD__);

        $this->removeFromCache($identifier);
        // $this->unitOfWork->registerClean($identifier, $data);
        $hydrator = $this->sdk->getModelHydrator();
        $out = $hydrator->hydrate($data, $this->entityName);

        if (null === $out) {
            throw new HydratorException(
                "Unable to convert data from PUT request ({$path}) to an instance of {$this->
                    entityName}. Maybe you have a custom hydrator returning null?"
            );
        }

        return $out;
    }

    public function persist(
        object $model,
        array $serializationContext = [],
        array $queryParams = []
    ): object {
        $mapping = $this->sdk->getMapping();
        $prefix = $mapping->getIdPrefix();
        $key = $mapping->getKeyFromModel($this->entityName);

        $path = empty($prefix) ? '/' . $key : $prefix . '/' . $key;

        $oldSerializedModel = $this->getClassMetadata()->getDefaultSerializedModel();
        $newSerializedModel = $this->sdk->getSerializer()->serialize(
            $model,
            $this->entityName,
            $serializationContext
        );

        $diff = $this->unitOfWork->getDirtyData(
            $newSerializedModel,
            $oldSerializedModel,
            $this->getClassMetadata()
        );

        $data = $this->restClient->post(
            $this->addQueryParameter($path, $queryParams),
            $diff
        );
        $data = $this->assertNotObject($data, __METHOD__);

        if (null === $data) {
            throw new RestException(
                "No data found after sending a `POST` request to {$path}. Did the server returned a 4xx or 5xx status code?",
                $path
            );
        }

        $hydrator = $this->sdk->getModelHydrator();

        $out = $hydrator->hydrate($data, $this->entityName);

        if (null === $out) {
            throw new HydratorException(
                "Unable to convert data from POST request ({$path}) to an instance of {$this->
                    entityName}. Maybe you have a custom hydrator returning null?"
            );
        }

        return $out;
    }

    /**
     * @return object|false
     */
    protected function fetchFromCache(string $key)
    {
        $key = $this->normalizeCacheKey($key);
        $cacheItemPool = $this->sdk->getCacheItemPool();
        if ($cacheItemPool) {
            $cacheKey = $this->sdk->getCachePrefix() . $key;
            if ($cacheItemPool->hasItem($cacheKey)) {
                $cacheItem = $cacheItemPool->getItem($cacheKey);
                $cacheData = $cacheItem->get();

                return $cacheData;
            }
        }

        return false;
    }

    protected function saveToCache(string $key, ?object $value): void
    {
        $key = $this->normalizeCacheKey($key);
        $cacheItemPool = $this->sdk->getCacheItemPool();
        if ($cacheItemPool) {
            $cacheKey = $this->sdk->getCachePrefix() . $key;

            if (!$cacheItemPool->hasItem($cacheKey)) {
                $cacheItem = $cacheItemPool->getItem($cacheKey);
                $cacheItem->set($value);
                $cacheItemPool->save($cacheItem);
            }
        }
    }

    /**
     * remove from cache
     *
     * @return bool true if no cache or cache successfully cleared, false otherwise
     */
    protected function removeFromCache(string $key): bool
    {
        $key = $this->normalizeCacheKey($key);
        $cacheItemPool = $this->sdk->getCacheItemPool();
        if ($cacheItemPool) {
            $cacheKey = $this->sdk->getCachePrefix() . $key;

            if ($cacheItemPool->hasItem($cacheKey)) {
                return $cacheItemPool->deleteItem($cacheKey);
            }
        }

        return true;
    }

    protected function addQueryParameter(
        string $path,
        array $params = []
    ): string {
        if (empty($params)) {
            return $path;
        }

        return $path . '?' . http_build_query($params);
    }

    private function convertQueryParameters(array $queryParameters): array
    {
        $mapping = $this->sdk->getMapping();

        return array_map(function ($item) use ($mapping) {
            if (is_object($item)) {
                $classname = get_class($item);

                if ($mapping->hasClassMetadata($classname)) {
                    $idGetter = $mapping->getClassMetadata(
                        $classname
                    )->getIdGetter();

                    return $item->{$idGetter}();
                }
            }

            return $item;
        }, $queryParameters);
    }

    private function normalizeCacheKey(string $key): string
    {
        $out = preg_replace('~[\\/\{\}@:\(\)]~', '_', $key);

        if (null === $out) {
            throw new \RuntimeException(
                'Unable to normalize cache key. This should not happen.'
            );
        }

        return $out;
    }

    private function getClassMetadata(): ClassMetadata
    {
        if (!isset($this->classMetadata)) {
            $this->classMetadataCache = $this->sdk->getMapping()->getClassMetadata(
                $this->entityName
            );
        }

        return $this->classMetadataCache;
    }

    /**
     * @var array|ResponseInterface|null
     */
    private function assertArray($data, string $methodName): array
    {
        if (is_array($data)) {
            return $data;
        }

        $type = null === $data ? 'null' : get_class($data);

        throw new UnexpectedTypeException(
            "Return of method {$methodName} should be an array. {$type} given."
        );
    }

    /**
     * @var array|ResponseInterface|null
     *
     * @return array|null
     */
    private function assertNotObject($data, string $methodName)
    {
        if (!is_object($data)) {
            return $data;
        }

        $type = get_class($data);

        throw new UnexpectedTypeException(
            "Return of method {$methodName} should be an array. {$type} given."
        );
    }
}


<?php

namespace kato\modules\tag\models;

use kato\ActiveRecord;

/**
 * This is the model class for table "kato_tag".
 *
 * @property string $id
 * @property string $name
 * @property integer $frequency
 * @property string $tag_type
 */
class Tag extends ActiveRecord
{
    const DEFAULT_FREQUENCY = 1;

	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return 'kato_tag';
	}

	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			[['frequency'], 'integer'],
			[['name'], 'string', 'max' => 255],
			[['tag_type'], 'string', 'max' => 50],
            [['tags', 'match', 'pattern'=>'/^[\w\s,]+$/', 'message'=>'Tags can only contain word characters.']],
		];
	}

	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
		return [
			'id' => 'ID',
			'name' => 'Name',
			'frequency' => 'Frequency',
			'tag_type' => 'Tag Type',
		];
	}

    /**
     * Returns array of tags by tag type
     * @param null $tagType
     * @param int $limit
     * @return array
     */
    public static function listTags($tagType = null, $limit = 30)
    {
        $model = self::find()
            ->select('name')
            ->orderBy('frequency DESC, Name')
            ->limit($limit);
            if (!is_null($tagType)) {
                $data = $model->where('tag_type = :type', [':type' => $tagType])->all();
            } else {
                $data = $model->all();
            }

        $return = [''];
        if (!empty($data)) {
            foreach ($data as $tag) {
                $return[] = $tag->name;
            }
        }
        return $return;
    }

    /**
     * Returns tag names and their corresponding weights.
     * Only the tags with the top weights will be returned.
     * @param integer the maximum number of tags that should be returned
     * @return array weights indexed by tag names.
     */
    public function findTagWeights($limit = 20)
    {
        $models = self::find()
            ->orderBy('frequency DESC')
            ->limit($limit)
            -all();

        $total=0;
        foreach ($models as $model) {
            $total+=$model->frequency;
        }

        $tags=[];
        if ($total > 0)
        {
            foreach ($models as $model) {
                $tags[$model->name] = 8 + (int)(16*$model->frequency/($total+10));
            }
            ksort($tags);
        }

        return $tags;
    }

    /**
     * Update count of tags already exists
     * if tag does not exists, insert it
     * @param $tags
     * @param $tagType
     */
    public static function addTags($tags, $tagType)
    {
        foreach ($tags as $name) {
            $tag = self::find()
                ->where(['name' => $name])
                ->andWhere(['tag_type' => $tagType])
                ->one();

            //if tag does not exists, insert it
            if (is_null($tag)) {
                $tag = new self();
                $tag->name = $name;
                $tag->tag_type = $tagType;
                $tag->frequency = self::DEFAULT_FREQUENCY;
                $tag->save(false);
            } else {
                //Update count of tags already exists
                $tag->updateCounters(['frequency' => self::DEFAULT_FREQUENCY]);
            }
        }
    }

    /**
     * Decrement frequency
     * if less then or equal to zero then delete row
     * @param $tags
     * @param $tagType
     */
    public static function removeTags($tags, $tagType)
    {
        if (empty($tags)) {
            return;
        }

        foreach ($tags as $name) {
            $tag = self::find()
                ->where(['name' => $name])
                ->andWhere(['tag_type' => $tagType])
                ->one();
            if (!is_null($tag)) {
                $tag->updateCounters(['frequency' => '-' . self::DEFAULT_FREQUENCY]);

                if ($tag->frequency <= 0) {
                    $tag->delete();
                }
            }
        }
    }

}


<?php

/**
 * Contao Bootstrap
 *
 * @package    contao-bootstrap
 * @subpackage Tab
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2013-2018 netzmacht David Molineus. All rights reserved.
 * @license    LGPL-3.0 https://github.com/contao-bootstrap/tab
 * @filesource
 */

declare(strict_types=1);

namespace ContaoBootstrap\Tab\EventListener\Dca;

use Contao\ContentModel;
use Contao\CoreBundle\Framework\Adapter;
use Contao\CoreBundle\Framework\ContaoFrameworkInterface as ContaoFramework;
use Contao\Database\Result;
use Contao\DataContainer;
use Contao\Model;
use Contao\StringUtil;

/**
 * Class ContentListener
 *
 * @package ContaoBootstrap\Tab\EventListener\Dca
 */
final class ContentListener
{
    /**
     * Contao framework.
     *
     * @var ContaoFramework
     */
    private $framework;

    /**
     * Content Model repository.
     *
     * @var Adapter|ContentModel
     */
    private $repository;

    /**
     * ContentDataContainer constructor.
     *
     * @param ContaoFramework $framework Contao framework.
     */
    public function __construct(ContaoFramework $framework)
    {
        $this->framework  = $framework;
        $this->repository = $this->framework->getAdapter(ContentModel::class);
    }

    /**
     * Initialize the dca.
     *
     * @return void
     *
     * @SuppressWarnings(PHPMD.Superglobals)
     */
    public function initializeDca(): void
    {
        $GLOBALS['TL_CSS'][] = 'bundles/contaobootstraptab/css/backend.css';

        if (isset($GLOBALS['TL_DCA']['tl_content']['fields']['bs_grid'])) {
            $GLOBALS['TL_DCA']['tl_content']['fields']['bs_grid']['load_callback'][] = [
                'contao_bootstrap.tab.listener.dca.content',
                'configureGridField',
            ];
        }
    }

    /**
     * Get all tab parent options.
     *
     * @return array
     *
     * @SuppressWarnings(PHPMD.Superglobals)
     */
    public function getTabParentOptions(): array
    {
        $columns[] = 'tl_content.type = ?';
        $columns[] = 'tl_content.pid = ?';
        $columns[] = 'tl_content.ptable = ?';

        $values[] = 'bs_tab_start';
        $values[] = CURRENT_ID;
        $values[] = $GLOBALS['TL_DCA']['tl_content']['config']['ptable'];

        $collection = $this->repository->findBy($columns, $values);
        $options    = [];

        if ($collection) {
            foreach ($collection as $model) {
                $options[$model->id] = sprintf(
                    '%s [%s]',
                    $model->bs_tab_name,
                    $model->id
                );
            }
        }

        return $options;
    }

    /**
     * Configure the grid field.
     *
     * @param mixed              $value         The field value.
     * @param DataContainer|null $dataContainer The data container driver.
     *
     * @return mixed
     *
     * @SuppressWarnings(PHPMD.Superglobals)
     */
    public function configureGridField($value, $dataContainer)
    {
        if ($dataContainer->activeRecord->type === 'bs_tab_start') {
            $GLOBALS['TL_DCA']['tl_content']['fields']['bs_grid']['eval']['mandatory'] = false;
        }

        return $value;
    }

    /**
     * Generate the columns.
     *
     * @param DataContainer $dataContainer Data container driver.
     *
     * @return void
     */
    public function generateColumns($dataContainer)
    {
        if (!$dataContainer->activeRecord || $dataContainer->activeRecord->type !== 'bs_tab_start') {
            return;
        }

        /** @var ContentModel|Result $current */
        $current      = $dataContainer->activeRecord;
        $stopElement  = $this->getStopElement($current);
        $count        = $this->countRequiredSeparators($dataContainer->activeRecord->bs_tabs, $current);
        $nextElements = $this->getNextElements($stopElement);

        if ($count > 0) {
            $sorting = (int) $stopElement->sorting;
            $sorting = $this->createSeparators((int) $count, $current, $sorting);

            array_unshift($nextElements, $stopElement);
            $this->updateSortings($nextElements, $sorting);
        }
    }

    /**
     * Count the required separator fields which should be created.
     *
     * @param mixed        $definition The tab definitions.
     * @param ContentModel $current    The current content model.
     *
     * @return int
     */
    private function countRequiredSeparators($definition, $current): int
    {
        $definition = StringUtil::deserialize($definition, true);
        $count      = -1;

        foreach ($definition as $item) {
            if ($item['type'] !== 'dropdown') {
                $count++;
            }
        }

        $count -= $this->repository->countBy(
            [
                'tl_content.ptable=?',
                'tl_content.pid=?',
                '(tl_content.type = ? AND tl_content.bs_tab_parent = ?)',
            ],
            [$current->ptable, $current->pid, 'bs_tab_separator', $current->id],
            ['order' => 'tl_content.sorting ASC']
        );

        return $count;
    }

    /**
     * Create separators.
     *
     * @param int          $value   Number of separators being created.
     * @param ContentModel $current Current model.
     * @param int          $sorting Current sorting value.
     *
     * @return int
     */
    protected function createSeparators(int $value, $current, int $sorting): int
    {
        for ($count = 1; $count <= $value; $count++) {
            $sorting = ($sorting + 8);
            $this->createTabElement($current, 'bs_tab_separator', $sorting);
        }

        return $sorting;
    }

    /**
     * Update the sorting of given elements.
     *
     * @param Model[] $elements    Model collection.
     * @param int     $lastSorting Last sorting value.
     *
     * @return int
     */
    protected function updateSortings(array $elements, int $lastSorting): int
    {
        foreach ($elements as $element) {
            if ($lastSorting > $element->sorting) {
                $element->sorting = ($lastSorting + 8);
                $element->save();
            }

            $lastSorting = (int) $element->sorting;
        }

        return $lastSorting;
    }

    /**
     * Create the stop element.
     *
     * @param ContentModel $current Model.
     * @param int          $sorting Last sorting value.
     *
     * @return Model
     */
    protected function createStopElement($current, int $sorting): Model
    {
        $sorting = ($sorting + 8);

        return $this->createTabElement($current, 'bs_tab_end', $sorting);
    }

    /**
     * Create a tab element.
     *
     * @param ContentModel $current Current content model.
     * @param string       $type    Type of the content model.
     * @param int          $sorting The sorting value.
     *
     * @return Model
     */
    protected function createTabElement($current, string $type, int &$sorting): Model
    {
        $model                = new ContentModel();
        $model->tstamp        = time();
        $model->pid           = $current->pid;
        $model->ptable        = $current->ptable;
        $model->sorting       = $sorting;
        $model->type          = $type;
        $model->bs_tab_parent = $current->id;
        $model->save();

        return $model;
    }

    /**
     * Get the next content elements.
     *
     * @param ContentModel $current Current content model.
     *
     * @return ContentModel[]
     */
    protected function getNextElements($current): array
    {
        $collection = $this->repository->findBy(
            [
                'tl_content.ptable=?',
                'tl_content.pid=?',
                'tl_content.sorting > ?',
            ],
            [$current->ptable, $current->pid, $current->sorting],
            ['order' => 'tl_content.sorting ASC']
        );

        if ($collection) {
            return $collection->getIterator()->getArrayCopy();
        }

        return [];
    }

    /**
     * Get related stop element.
     *
     * @param ContentModel $current Current element.
     *
     * @return ContentModel|Model
     */
    protected function getStopElement($current): Model
    {
        $stopElement = $this->repository->findOneBy(
            ['tl_content.type=?', 'tl_content.bs_tab_parent=?'],
            ['bs_tab_end', $current->id]
        );

        if ($stopElement) {
            return $stopElement;
        }

        $nextElements = $this->getNextElements($current);
        $stopElement  = $this->createStopElement($current, (int) $current->sorting);
        $this->updateSortings($nextElements, (int) $stopElement->sorting);

        return $stopElement;
    }
}


<?php

/**
 * Contao Open Source CMS, Copyright (C) 2005-2018 Leo Feyer
 *
 * Module Backend User Online - DCA Helper Class DcaMemberOnlineIcon
 *
 * @copyright  Glen Langer 2012..2018 <http://contao.ninja>
 * @author     Glen Langer (BugBuster)
 * @package    BackendUserOnline
 * @license    LGPL
 * @filesource
 * @see	       https://github.com/BugBuster1701/contao-be_user_online-bundle
 */

/**
 * Run in a custom namespace, so the class can be replaced
 */
namespace BugBuster\BackendUserOnline;

/**
 * Class DcaMemberOnlineIcon
 *
 * @copyright  Glen Langer 2012..2018 <http://contao.ninja>
 * @author     Glen Langer (BugBuster)
 * @package    BackendUserOnline
 */
class DcaMemberOnlineIcon extends \Backend
{
    /**
     * Add an image to each record
     * @param array
     * @param string
     * @param DataContainer
     * @param array
     * @return string
     */
	public function addIcon($row, $label, \DataContainer $dc, $args)
	{
		$image = 'member';

		$time = \Date::floorToMinute();

		$disabled = $row['start'] !== '' && $row['start'] > $time || $row['stop'] !== '' && $row['stop'] < $time;

		if ($row['disable'] || $disabled)
		{
			$image .= '_';
		}

		$objUsers = \Database::getInstance()
		                    ->prepare("SELECT
                                            tlm.id
                                        FROM
		                                    tl_member tlm, tl_beuseronline_session tls
                                        WHERE
		                                    tlm.id = tls.pid
                                        AND tlm.id = ?
                                        AND tls.tstamp > ?
                                        AND tls.name = ?")
                            ->execute($row['id'], time()-300, 'FE_USER_AUTH');
		if ($objUsers->numRows < 1)
		{
			//offline
			$status = sprintf('', TL_ASSETS_URL, \Backend::getTheme());
		}
		else
		{
			//online
			$status = sprintf('', TL_ASSETS_URL, \Backend::getTheme());
		}

		$args[0] = sprintf('
%s
', TL_ASSETS_URL, \Backend::getTheme(), $image, $disabled ? $image : rtrim($image, '_'), rtrim($image, '_') . '_', $status);

		return $args;
	}

}


<?php

/**
 * Contao Bootstrap
 *
 * @package    contao-bootstrap
 * @subpackage Tab
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2013-2018 netzmacht David Molineus. All rights reserved.
 * @license    LGPL-3.0 https://github.com/contao-bootstrap/tab
 * @filesource
 */

declare(strict_types=1);

namespace ContaoBootstrap\Tab\Component\ContentElement;

/**
 * Class TabSeparatorElement
 */
final class TabSeparatorElement extends AbstractTabElement
{
    /**
     * Template name.
     *
     * @var string
     */
    protected $templateName = 'ce_bs_tab_separator';

    /**
     * {@inheritDoc}
     */
    protected function prepareTemplateData(array $data): array
    {
        $iterator = $this->getIterator();
        $parent   = $this->getParent();
        $data     = parent::prepareTemplateData($data);

        $data['fade'] = ($parent && $parent->bs_tab_fade) ? ' fade' : '';

        if ($iterator) {
            $iterator->next();

            if ($iterator->valid()) {
                $currentItem = $iterator->current();

                $data['currentItem'] = $currentItem;

                if ($parent->bs_tab_fade && $currentItem && $currentItem->active()) {
                    $data['fade'] = rtrim($data['fade'] . ' show');
                }
            }
        }

        return $data;
    }
}