<?php
/*
 * This file is part of the RedKite CMS Application and it is distributed
 * under the MIT License. To use this bundle you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://redkite-labs.com
 *
 * @license    MIT License
 */

namespace RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Autoloader;

use Symfony\Component\Finder\Finder;
use Symfony\Component\Filesystem\Filesystem;
use RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Exception\InvalidAutoloaderException;
use RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Json\JsonAutoloader;
use RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Json\JsonAutoloaderCollection;

/**
 * Parses bundles installed by composer, checks if the bundle has an autoload.json
 * file in its main root folder and when the file is present, copies the autoloader.json,
 * the routing.yml and config.yml under the app/config/bundles folder, to autoconfigure
 * the bundle.
 *
 * @author RedKite Labs <info@redkite-labs.com>
 */
class BundlesAutoloader
{
    private $bundles;
    private $instantiatedBundles;
    private $environment;
    private $kernelDir;
    private $vendorDir;
    private $autoloaderCollection = array();
    private $installedBundles = array();
    private $environmentsBundles = array();
    private $overridedBundles = array();
    private $basePath;
    private $autoloadersPath;
    private $configPath;
    private $routingPath;
    private $cachePath;
    private $filesystem;
    private $bootstrapped = false;
    private $searchFolders;

    /**
     * Constructor
     *
     * @param string     $kernelDir     The kernel directory path
     * @param string     $environment   The current environment
     * @param array      $bundles       The bundles already loaded
     * @param null|array $searchFolders Adds extra folders to be parsed to look for other budles to autoload. When null looks for RedKiteLabs's blocks
     */
    public function __construct($kernelDir, $environment, array $bundles, $searchFolders = null)
    {
        $this->environment = $environment;
        $this->kernelDir = $kernelDir;
        $this->vendorDir = $this->kernelDir . '/../vendor';
        $this->searchFolders = array(
            $this->kernelDir . '/../src/RedKiteCms/Block',
            $this->kernelDir . '/../src/RedKiteCms/Theme',
        );
        if (null !== $searchFolders) {
            $this->searchFolders = $searchFolders;
        }
        $this->filesystem = new Filesystem();

        $this->setupFolders();

        // @codeCoverageIgnoreStart
        $this->bundles = $bundles;
        foreach ($this->bundles as $bundle) {
            $this->instantiatedBundles[] = get_class($bundle);
        }
        // @codeCoverageIgnoreEnd
    }

    /**
     * Returns the instantiated bundles
     *
     * @return array
     */
    public function getBundles()
    {
        $this->run();

        return $this->bundles;
    }

    /**
     * Sets the vendor directory path
     *
     * @param  type                                                           $vendorDir
     * @return \RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Autoloader\BundlesAutoloader
     * @codeCoverageIgnore
     */
    public function setVendorDir($vendorDir)
    {
        $this->vendorDir = $vendorDir;

        return $this;
    }

    /**
     * Runs the process
     */
    protected function run()
    {
        if (! $this->bootstrapped) {
            $this->autoloaderCollection = new JsonAutoloaderCollection($this->vendorDir, $this->searchFolders);
            $this->retrieveInstalledBundles();
            $this->install();
            $this->uninstall();
            $this->arrangeBundlesForEnvironment();

            $this->bootstrapped = true;
        }
    }

    /**
     * Orders the bundles according to bundle's json param "overrided"
     */
    protected function orderBundles()
    {
        // Gives a score to each bundle
        $order = array();
        foreach ($this->overridedBundles as $overriderBundle => $overridedBundles) {

            // An overrider bundle enters in the compilation, but takes any point
            if (!array_key_exists($overriderBundle, $order)) {
                $order[$overriderBundle] = 0;
            }

            // An overrided gets a point everytime is found
            foreach ($overridedBundles as $overriderBundle => $overridedBundle) {
                $order[$overridedBundle] = 1;
                if (array_key_exists($overridedBundle, $order)) {
                    $order[$overridedBundle] = $order[$overridedBundle] + 1;
                }
            }
        }

        arsort($order);

        // Arranges the bundles entries
        foreach ($order as $bundleName => $pos) {
            $bundle = $this->bundles[$bundleName];
            unset($this->bundles[$bundleName]);
            $this->bundles[$bundleName] = $bundle;
        }
    }

    /**
     * Parsers the autoloaders and arranges the bundles for environment
     */
    protected function arrangeBundlesForEnvironment()
    {
        foreach ($this->autoloaderCollection as $autoloader) {
            $autoloaderBundles = $autoloader->getBundles();
            foreach ($autoloaderBundles as $environment => $bundles) {
                foreach ($bundles as $bundle) {
                    $this->environmentsBundles[$environment][] = $bundle;
                }
            }
        }

        $this->register('all');
        $this->register($this->environment);
        $this->orderBundles();
    }

    /**
     * Registers the bundles for the given environment
     *
     * @param string $environment
     */
    protected function register($environment)
    {
        if (isset($this->environmentsBundles[$environment])) {
            foreach ($this->environmentsBundles[$environment] as $bundle) {
                $bundleClass = $bundle->getClass();
                if (empty($this->instantiatedBundles) || !in_array($bundleClass, $this->instantiatedBundles)) {

                    if ( ! class_exists($bundleClass)) {
                        throw new InvalidAutoloaderException(sprintf("The bundle class %s does not exist. Check the bundle's autoload.json to fix the problem", $bundleClass, get_class($this)));
                    }

                    if ( ! in_array($bundle->getName(), $this->bundles)) {
                        $instantiatedBundle = new $bundleClass;
                        $this->bundles[$bundle->getName()] = $instantiatedBundle;
                        $overridedBundles = $bundle->getOverrides();
                        if ( ! empty($overridedBundles)) {
                            $this->overridedBundles[$bundle->getName()] = $overridedBundles;
                        }
                        $this->instantiatedBundles[] = $bundleClass;
                    }
                }
            }
        }
    }

    /**
     * Instantiates the bundles that must be autoconfigured, parsing the autoload_namespaces.php file
     * generated by composer
     */
    protected function install()
    {
        foreach ($this->autoloaderCollection as $dir => $jsonAutoloader) {
            $bundleName = $jsonAutoloader->getBundleName();
            $this->installPackage($dir, $jsonAutoloader);
            unset($this->installedBundles[$bundleName]);
        }
    }

    /**
     * Installs the autoloader.json, the routing and config files
     *
     * @param string         $sourceFolder The source folder where the autoloader is placed
     * @param JsonAutoloader $autoloader   The generated autoloader object
     */
    protected function installPackage($sourceFolder, JsonAutoloader $autoloader)
    {
        $bundleName = $autoloader->getBundleName();

        if (array_key_exists('all', $autoloader->getBundles()) || array_key_exists($this->environment, $autoloader->getBundles())) {
            $target = $this->autoloadersPath . '/' . $bundleName  . '.json';
            $this->copy($autoloader->getFilename(), $target);

            $sourceFolder = $sourceFolder . '/Resources/config';
            $filename = $bundleName . '.yml';
            $this->copyConfigurationFile('config', $filename, $sourceFolder, $this->configPath);
            $this->copy($sourceFolder . '/routing.yml', $this->routingPath . '/' . $filename);
        }
    }

    /**
     * Copies a configuration file from bundle to application folder
     *
     * @param string $section
     * @param string $filename
     * @param string $sourceFolder
     * @param string $targetFolder
     */
    protected function copyConfigurationFile($section, $filename, $sourceFolder, $targetFolder)
    {
        $envConfigFile = sprintf('%s/%s_%s.yml', $sourceFolder, $section, $this->environment);
        $sourceFile = (file_exists($envConfigFile)) ? $envConfigFile : $sourceFolder . '/' . $section . '.yml';
        $this->copy($sourceFile, $targetFolder . '/' . $this->environment . '/' . $filename);
    }

    /**
     * Removes the autoloader and the config from the app/config/bundles folder
     */
    protected function uninstall()
    {
        if (!empty($this->installedBundles)) {
            foreach ($this->installedBundles as $autoloader) {
                $bundleName = $autoloader->getBundleName();
                $this->filesystem->remove($this->autoloadersPath . '/' . $bundleName . '.json');
                $this->filesystem->remove($this->configPath);
                $this->filesystem->remove($this->routingPath);
            }
        }
    }

    /**
     * Retrieves the current installed bundles
     */
    protected function retrieveInstalledBundles()
    {
        $finder = new Finder();
        $autoloaders = $finder->files()->depth(0)->name('*.json')->in($this->autoloadersPath);
        foreach ($autoloaders as $autoloader) {
            $bundleName = strtolower(basename($autoloader->getFilename(), '.json'));
            $jsonAutoloader = new JsonAutoloader($bundleName, (string) $autoloader);
            $this->installedBundles[$bundleName] = $jsonAutoloader;
        }
    }

    /**
     * Retrieves the current bundle class
     *
     * @param  string $path The bundle's path
     * @return string
     */
    protected function getBundleName($path)
    {
        if (is_dir($path)) {
            $finder = new Finder();
            $bundles = $finder->files()->depth(0)->name('*Bundle.php')->in($path);
            foreach ($bundles as $bundle) {
                return basename($bundle->getFilename(), 'Bundle.php');
            }
        }

        return null;
    }

    /**
     * Checks if the bundle has an autoloader.json file
     *
     * @param  string  $path The bundle's path
     * @return boolean
     */
    protected function hasAutoloader($path)
    {
        if (is_dir($path)) {
            $finder = new Finder();
            $bundles = $finder->files()->depth(0)->name('autoload.json')->in($path);
            if (count($bundles) == 1) {
                return true;
            }
        }

        return false;
    }

    /**
     * Copies the source file
     *
     * @param string $source
     * @param string $target
     *
     * @return boolean
     */
    protected function copy($source, $target)
    {
        if (is_file($source)) {
            $exists = is_file($target) ? true :false;
            $this->filesystem->copy($source, $target);

            if (!$exists) {
                return true;
            }
        }

        return false;
    }

    /**
     * Sets up the paths and creates the folder when they not exist
     */
    private function setupFolders()
    {
        $this->basePath = $this->kernelDir . '/config/bundles';
        $this->autoloadersPath = $this->basePath . '/autoloaders';
        $this->configPath = $this->basePath . '/config';
        $this->routingPath = $this->basePath . '/routing';
        $this->cachePath = $this->basePath . '/cache';

        $this->filesystem->mkdir(array(
            $this->basePath,
            $this->autoloadersPath,
            $this->configPath,
            $this->routingPath,
            $this->cachePath,));
    }
}


<?php

namespace Environaut\Command;

use Symfony\Component\Console\Command\Command as BaseCommand;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Base class for environaut commands.
 */
abstract class Command extends BaseCommand
{
    /**
     * @var InputInterface
     */
    protected $input;

    /**
     * @var OutputInterface
     */
    protected $output;

    /**
     * Defines default options for all commands.
     */
    protected function configure()
    {
        parent::configure();

        $this->addOption(
            'bootstrap',
            'b',
            InputOption::VALUE_OPTIONAL,
            'Path to bootstrap file that should be required prior start.'
        );

        $this->addOption(
            'include-path',
            'i',
            InputOption::VALUE_OPTIONAL,
            'Path that should be prepended to the default PHP include_path.'
        );

        $this->addOption(
            'autoload-dir',
            'a',
            InputOption::VALUE_OPTIONAL,
            'Path from where to load custom classes specified in config etc.'
        );
    }

    /**
     * Handles the default options all commands have in common.
     *
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     *
     * @throws \InvalidArgumentException in case of configuration errors
     */
    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        parent::initialize($input, $output);

        $this->input = $input;
        $this->output = $output;

        // prepend include_path if demanded
        $path = $input->getOption('include-path');
        if (!empty($path)) {
            ini_set('include_path', $path . PATH_SEPARATOR . ini_get('include_path'));
        }

        // run given bootstrap file if necessary
        $bootstrap_path = $input->getOption('bootstrap');
        if (!empty($bootstrap_path)) {
            if (!is_readable($bootstrap_path)) {
                throw new \InvalidArgumentException('Bootstrap file "' . $bootstrap_path . '" is not readable.');
            }

            if ($this->input->getOption('verbose')) {
                $output->writeln('<comment>Requiring boostrap file from "' . $bootstrap_path . '".</comment>');
            }
            require $bootstrap_path;
        }

        // we autoload classes from the current working directory or the specified autoload_dir
        $autoload_dir = $input->getOption('autoload-dir');
        if (!empty($autoload_dir)) {
            if (!is_readable($autoload_dir)) {
                throw new \InvalidArgumentException(
                    'Autoload path "' . $autoload_dir . '" is not readable. Please specify an existing directory.'
                );
            }

            if ($this->input->getOption('verbose')) {
                $output->writeln('<comment>Classes will be autoloaded from "' . $autoload_dir . '".</comment>');
            }
        } else {
            if ($this->input->getOption('verbose')) {
                $output->writeln(
                    '<comment>No autoload_dir specified, using "' . $this->getCurrentWorkingDirectory() .
                    '" to autoload classes from.</comment>'
                );
            }
        }

        spl_autoload_register(array($this, 'autoload'));
    }

    /**
     * Autoloads the given class if it exists.
     *
     * @param string $class class name like 'Foo\Bar\Baz'
     *
     * @throws \InvalidArgumentException in case of errors (file
     */
    protected function autoload($class)
    {
        $class = str_replace('\\', DIRECTORY_SEPARATOR, $class);

        $autoload_dir = $this->getInput()->getOption('autoload-dir');
        if (empty($autoload_dir)) {
            $autoload_dir = $this->getCurrentWorkingDirectory();
        }

        $file_path = $autoload_dir . DIRECTORY_SEPARATOR . $class . '.php';

        if ($this->input->getOption('verbose')) {
            $this->output->write('<info>Autoloading</info>: ');
        }

        if (is_readable($file_path)) {
            if ($this->input->getOption('verbose')) {
                $this->output->writeln($file_path);
            }

            include_once($file_path);
        } else {
            $this->output->writeln('<error>Autoload error: "' . $file_path . '" not found!</error>' . PHP_EOL);
            // don't exit here to let other autoloaders get their chance
            //throw new \InvalidArgumentException('Could not include unreadable file: ' . $file_path);
        }
    }

    /**
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);
    }

    /**
     * @return \Symfony\Component\Console\Output\OutputInterface
     */
    public function getOutput()
    {
        return $this->output;
    }

    /**
     * @return \Symfony\Component\Console\Input\InputInterface
     */
    public function getInput()
    {
        return $this->input;
    }

    /**
     * @return \Symfony\Component\Console\Helper\DialogHelper
     */
    public function getDialogHelper()
    {
        return $this->getHelper('dialog');
    }

    /**
     * @return string current working directory
     */
    protected function getCurrentWorkingDirectory()
    {
        $dir = getcwd();

        if (false === $dir) {
            $dir = __DIR__; // fallback to folder of current class in case of strange errors
        }

        return $dir;
    }
}


<?php

/**
 * Nameless framework
 *
 * @package Nameless framework
 * @author  Corpsee <poisoncorpsee@gmail.com>
 * @license https://github.com/corpsee/nameless-source/blob/master/LICENSE
 * @link    https://github.com/corpsee/nameless-source
 */

namespace Nameless\Core;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Nameless\Modules\Database\Database;
use Symfony\Component\Routing\Generator\UrlGenerator;

/**
 * Base controller class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class Controller implements ControllerInterface
{
    /**
     * @var Container
     */
    protected $container;

    /**
     * @param Container $container
     */
    public function setContainer(Container $container)
    {
        $this->container = $container;
    }

    /**
     * @return Request
     */
    public function getRequest()
    {
        return $this->container['request'];
    }

    /**
     * @return Database
     * @throws \RuntimeException
     */
    protected function getDatabase()
    {
        if (isset($this->container['database.database'])) {
            return $this->container['database.database'];
        }
        throw new \RuntimeException('Don`t load module Database');
    }

    /**
     * @return Application
     */
    private function getKernel()
    {
        return $this->container['kernel'];
    }

    /**
     * Internal redirect without creating an instance of kernel
     *
     * @param string $route
     * @param array $attributes
     * @param array $query
     *
     * @return Response
     */
    public function forward($route, array $attributes = [], array $query = [])
    {
        return $this->getKernel()->forward($route, $attributes, $query);
    }

    /**
     * External redirect
     *
     * @param string $url
     * @param int $status
     * @param array $headers
     *
     * @return RedirectResponse
     */
    public function redirect($url, $status = 302, $headers = [])
    {
        return new RedirectResponse($url, $status, $headers);
    }

    /**
     * Exception for 404 error
     *
     * @param string $message
     * @param \Exception $previous
     *
     * @throws NotFoundHttpException
     */
    public function notFound($message = 'Page not found', \Exception $previous = null)
    {
        throw new NotFoundHttpException($message, $previous);
    }

    /**
     * @param string $route_name
     * @param array $parameters
     * @param boolean|string $referenceType
     *
     * @return string
     */
    public function generateURL($route_name, array $parameters = [], $referenceType = UrlGenerator::ABSOLUTE_PATH)
    {
        return $this->container['url-generator']->generate($route_name, $parameters, $referenceType);
    }

    /**
     * @param string $template
     * @param array $data
     * @param integer $template_filter
     * @param array $filters
     * @param Response $response
     * @param string $template_extension
     * @param string $template_path
     * @param boolean $compress
     *
     * @return Response
     */
    //TODO: $template_extension to config
    public function render($template, array $data = [], $template_filter = Template::FILTER_ESCAPE, array $filters = [], Response $response = null, $template_path = null, $template_extension = 'tpl', $compress = false)
    {
        if (is_null($template_path)) {
            $template_path = $this->container['templates_path'];
        }
        $template = new Template($template_path, $template, $data, $template_filter, $filters, $response, $template_extension);
        return $template->render($compress);
    }

    /**
     * Get "parameter" value. Order: GET, PATH, POST, COOKIE
     *
     * @param string $key
     * @param mixed $default
     * @param boolean $deep
     *
     * @return mixed
     */
    public function get($key, $default = null, $deep = false)
    {
        return $this->getRequest()->get($key, $default, $deep);
    }

    /**
     * Get value from POST array by key. If $key is NULL then method returns all POST array
     *
     * @param string $key
     * @param mixed $default
     * @param boolean $deep
     *
     * @return mixed
     */
    public function getPost($key = null, $default = null, $deep = false)
    {
        if (is_null($key)) {
            return $this->getRequest()->request->all();
        }
        return $this->getRequest()->request->get($key, $default, $deep);
    }

    /**
     * Get value from GET array by key. If $key is NULL then method returns all GET array
     *
     * @param string $key
     * @param mixed $default
     * @param boolean $deep
     *
     * @return mixed
     */
    public function getGet($key = null, $default = null, $deep = false)
    {
        if (is_null($key)) {
            return $this->getRequest()->query->all();
        }
        return $this->getRequest()->query->get($key, $default, $deep);
    }

    /**
     * Get value from FILES array by key. If $key is NULL then method returns all FILES array
     *
     * @param string $key
     * @param mixed $default
     * @param boolean $deep
     *
     * @return mixed
     */
    public function getFiles($key = null, $default = null, $deep = false)
    {
        if (is_null($key)) {
            return $this->getRequest()->files->all();
        }
        return $this->getRequest()->files->get($key, $default, $deep);
    }

    /**
     * Get value from COOKIES array by key. If $key is NULL then method returns all COOKIES array
     *
     * @param string $key
     * @param mixed $default
     * @param boolean $deep
     *
     * @return mixed
     */
    public function getCookies($key = null, $default = null, $deep = false)
    {
        if (is_null($key)) {
            return $this->getRequest()->cookies->all();
        }
        return $this->getRequest()->cookies->get($key, $default, $deep);
    }

    /**
     * @return SessionInterface
     */
    public function getSession()
    {
        return $this->getRequest()->getSession();
    }

    /**
     * Get value from SERVER array by key. If $key is NULL then method returns all SERVER array
     *
     * @param string $key
     * @param mixed $default
     * @param boolean $deep
     *
     * @return mixed
     */
    public function getServer($key = null, $default = null, $deep = false)
    {
        if (is_null($key)) {
            return $this->getRequest()->server->all();
        }
        return $this->getRequest()->server->get($key, $default, $deep);
    }

    /**
     * Get http-header value by key. If $key is NULL then method returns all http-headers
     *
     * @param string $key
     * @param mixed $default
     * @param boolean $deep
     *
     * @return mixed
     */
    public function getHeaders($key = null, $default = null, $deep = false)
    {
        if (is_null($key)) {
            return $this->getRequest()->headers->all();
        }
        return $this->getRequest()->headers->get($key, $default, $deep);
    }

    /**
     * Get request attribute value by key. If $key is NULL then method returns all request attributes
     *
     * @param string $key
     * @param mixed $default
     * @param boolean $deep
     *
     * @return mixed
     */
    public function getAttributes($key = null, $default = null, $deep = false)
    {
        if (is_null($key)) {
            return $this->getRequest()->attributes->all();
        }
        return $this->getRequest()->attributes->get($key, $default, $deep);
    }

    /**
     * Check for request method (POST, GET, PUT)
     *
     * @param string $method
     *
     * @return boolean
     */
    public function isMethod($method)
    {
        return $this->getRequest()->isMethod($method);
    }

    /**
     * Check for XmlHttpRequest (ajax)
     *
     * @return boolean
     */
    public function isAjax()
    {
        return $this->getRequest()->isXmlHttpRequest();
    }
}


<?php

namespace xz1mefx\adminlte\widgets;

use Symfony\Component\CssSelector\Exception\InternalErrorException;
use xz1mefx\adminlte\helpers\Html;
use yii\helpers\ArrayHelper;

/**
 * Class ActiveField
 * @package xz1mefx\adminlte\widgets
 */
class ActiveField extends \yii\bootstrap\ActiveField
{
    /**
     * @inheritdoc
     */
    public $template = "{label}\n{input}\n{glyphIcon}\n{hint}\n{error}";

    private $_glyphIconAllowed = false;

    /**
     * @inheritdoc
     */
    public function render($content = NULL)
    {
        if ($content === NULL) {
            if (!isset($this->parts['{beginWrapper}'])) {
                $options = $this->wrapperOptions;
                $tag = ArrayHelper::remove($options, 'tag', 'div');
                $this->parts['{beginWrapper}'] = Html::beginTag($tag, $options);
                $this->parts['{endWrapper}'] = Html::endTag($tag);
            }
            if (empty($this->parts['{glyphIcon}']) || !$this->_glyphIconAllowed) {
                $this->parts['{glyphIcon}'] = '';
            }
            if ($this->enableLabel === false) {
                $this->parts['{label}'] = '';
                $this->parts['{beginLabel}'] = '';
                $this->parts['{labelTitle}'] = '';
                $this->parts['{endLabel}'] = '';
            } elseif (!isset($this->parts['{beginLabel}'])) {
                $this->renderLabelParts();
            }
            if ($this->enableError === false) {
                $this->parts['{error}'] = '';
            }
            if ($this->inputTemplate) {
                $input = isset($this->parts['{input}']) ?
                    $this->parts['{input}'] : Html::activeTextInput($this->model, $this->attribute, $this->inputOptions);
                $this->parts['{input}'] = strtr($this->inputTemplate, ['{input}' => $input]);
            }
        }
        return parent::render($content);
    }

    /**
     * @inheritdoc
     */
    public function begin()
    {
        if ($this->form->enableClientScript) {
            $clientOptions = $this->getClientOptions();
            if (!empty($clientOptions)) {
                $this->form->attributes[] = $clientOptions;
            }
        }

        $inputID = $this->getInputId();
        $attribute = Html::getAttributeName($this->attribute);
        $options = $this->options;
        $class = isset($options['class']) ? [$options['class']] : [];
        $class[] = "field-$inputID";
        if ($this->model->isAttributeRequired($attribute)) {
            $class[] = $this->form->requiredCssClass;
        }
        if ($this->model->hasErrors($attribute)) {
            $class[] = $this->form->errorCssClass;
        }
        $options['class'] = implode(' ', $class);
        $tag = ArrayHelper::remove($options, 'tag', 'div');

        if (!empty($this->parts['{glyphIcon}'])) {
            $options['class'] = $options['class'] . (empty($options['class']) ? '' : ' ') . 'has-feedback';
        }

        return Html::beginTag($tag, $options);
    }

    /**
     * @inheritdoc
     */
    public function label($label = NULL, $options = [])
    {
        if (is_bool($label)) {
            $this->enableLabel = $label;
            if ($label === false && $this->form->layout === 'horizontal') {
                Html::addCssClass($this->wrapperOptions, $this->horizontalCssClasses['offset']);
            }
        } else {
            $this->enableLabel = true;
            $this->renderLabelParts($label, $options);
            parent::label($label, $options);
        }
        return $this;
    }

    /**
     * Working only with inputs where type is text or password
     *
     * You must set field first
     *
     * @param $glyphIcon string Icon name
     * @return $this
     * @throws InternalErrorException
     */
    public function glyphIcon($glyphIcon)
    {
        if (empty($this->parts['{input}'])) {
            throw new InternalErrorException('Firstly you must set field type!');
        }

        if (empty($glyphIcon) || !$this->_glyphIconAllowed) {
            $this->parts['{glyphIcon}'] = '';
            return $this;
        }

        $this->parts['{glyphIcon}'] = Html::tag('span', '', ['class' => "glyphicon glyphicon-$glyphIcon form-control-feedback"]);

        return $this;
    }

    /**
     * @inheritdoc
     */
    public function input($type, $options = [])
    {
        $this->_glyphIconAllowed = true;
        return parent::input($type, $options);
    }

    /**
     * @inheritdoc
     */
    public function textInput($options = [])
    {
        $this->_glyphIconAllowed = true;
        return parent::textInput($options);
    }

    /**
     * @inheritdoc
     */
    public function passwordInput($options = [])
    {
        $this->_glyphIconAllowed = true;
        return parent::passwordInput($options);
    }
}


<?php

namespace UMA\SchemaBundle\EventListener;

use Doctrine\Common\Annotations\Reader;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use UMA\SchemaBundle\Annotation\JsonSchema;
use UMA\SchemaBundle\Validation\JsonValidator;

class JsonRequestListener implements EventSubscriberInterface
{
    /**
     * @var Reader
     */
    private $reader;

    /**
     * @var JsonValidator
     */
    private $validator;

    /**
     * @param Reader        $reader
     * @param JsonValidator $validator
     */
    public function __construct(Reader $reader, JsonValidator $validator)
    {
        $this->reader = $reader;
        $this->validator = $validator;
    }

    /**
     * @param FilterControllerEvent $event
     */
    public function onKernelController(FilterControllerEvent $event)
    {
        foreach ($this->getActionAnnotations((array) $event->getController()) as $annotation) {
            if ($annotation instanceof JsonSchema) {
                $this->validator->validate($event->getRequest(), $annotation);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [KernelEvents::CONTROLLER => 'onKernelController'];
    }

    /**
     * @param array $controller
     *
     * @return object[]
     */
    private function getActionAnnotations(array $controller)
    {
        $actionMethod = (new \ReflectionClass(get_class($controller[0])))
            ->getMethod($controller[1]);

        return $this->reader->getMethodAnnotations($actionMethod);
    }
}


<?php

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.data
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: BizDataObj_Abstract.php 4108 2011-05-08 06:01:30Z jixian2003 $
 */

namespace Openbizx\Data;

use Openbizx\Openbizx;
use Openbizx\Helpers\MessageHelper;
use Openbizx\Object\Statefullable;
use Openbizx\Object\MetaObject;
use Openbizx\Object\MetaIterator;
use Openbizx\Event\EventManager;
use Openbizx\Data\Tools\BizRecord;

/**
 * BizDataObj_Abstract class contains data object metadata functions
 *
 * @package   openbiz.bin.data
 * @author rocky swen
 * @copyright Copyright (c) 2005
 * @access public
 */
abstract class BizDataObj_Abstract extends MetaObject implements Statefullable
{
    // metadata vars are public, necessary for metadata inheritance

    /**
     * Database name
     *
     * @var string
     */
    public $databaseAliasName;

    /**
     * Base search rule
     *
     * @var string
     */
    public $baseSearchRule = null;    // support expression

    /**
     * Base sort rule
     *
     * @var string
     */
    public $baseSortRule = null;      // support expression

    /**
     * Base other SQL rule
     *
     * @var string
     */
    public $baseOtherSQLRule = null;  // support expression

    /**
     * Name of main table
     *
     * @var string
     */
    public $mainTableName = "";

    /**
     * BizRecord object
     *
     * @var BizRecord
     */
    public $bizRecord = null;

    /**
     * Name of inherited form (meta-form)
     *
     * @var string
     */
    public $inheritFrom;

    /**
     * Access rule (visibility) of the records
     * Can be Openbizx query string or any expression
     * Example: [user_id]={@profile['Id']} or {@vis:self([user_id])} or {@vis:group([group_id])}
     * @var string
     */
    public $accessRule = null;

    /**
     * Condition of user ability to update a record
     * @var string
     */
    public $updateCondition = null;   // support expression

    /**
     * Condition of user ability to delete a record
     * @var string
     */
    public $deleteCondition = null;   // support expression

    /**
     * Record id generation option
     *
     * @var string
     */
    public $idGeneration = null;

    /**
     * MetaIterator of ObjReferences
     *
     * @var MetaIterator
     */
    public $objReferences = null;

    /**
     * MetaIterator of TableJoin
     *
     * @var MetaIterator
     */
    public $tableJoins = null;

    /**
     *
     * @var MetaIterator
     */
    public $parameters = null;
    public $stateless = null;
    public $uniqueness = null;

    /**
     * Search rule
     *
     * @var string
     */
    public $searchRule = null;        // support expression

    /**
     * Sort rule
     * @var string
     */
    public $sortRule = null;          // support expression

    /**
     * Other SQL rule
     *
     * @var string
     */
    public $otherSQLRule = null;      // support expression

    /**
     * Life time o cache
     *
     * @var number
     */
    public $cacheLifeTime = null;     // set 0 to disbale cache function

    /**
     * Message file path
     *
     * @var string
     */
    public $messageFile = null;        //

    /**
     * Limitation of query
     *   $this->queryLimit['count'] - count of record that loaded from database (per page)
     *   $this->queryLimit['offset'] - offset of record (for paging)
     *
     * @var array
     */
    protected $queryLimit = array();

    /**
     * Array messages that loaded from {@link $messageFile}
     *
     * @var array
     */
    protected $objectMessages;
    protected $queryParams = array();
    public $dataPermControl;
    public $eventManagerName;
    public $association;
    public $eventManager;

    /**
     * Initialize BizDataObj_Abstract with xml array
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
        $this->readMetadata($xmlArr);
        $this->inheritParentObj();
    }

    /**
     * Read Metadata from xml array
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->inheritFrom = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["INHERITFROM"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["INHERITFROM"] : null;
        $this->searchRule = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["SEARCHRULE"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["SEARCHRULE"] : null;
        $this->baseSearchRule = $this->searchRule;
        $this->sortRule = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["SORTRULE"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["SORTRULE"] : null;
        $this->baseSortRule = $this->sortRule;
        $this->otherSQLRule = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["OTHERSQLRULE"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["OTHERSQLRULE"] : null;
        $this->baseOtherSQLRule = $this->otherSQLRule;
        $this->accessRule = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["ACCESSRULE"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["ACCESSRULE"] : null;
        $this->updateCondition = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["UPDATECONDITION"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["UPDATECONDITION"] : null;
        $this->deleteCondition = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["DELETECONDITION"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["DELETECONDITION"] : null;
        $this->databaseAliasName = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["DBNAME"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["DBNAME"] : null;
        if ($this->databaseAliasName == null) {
            $this->databaseAliasName = "Default";
        }
        $this->mainTableName = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["TABLE"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["TABLE"] : null;
        $this->idGeneration = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["IDGENERATION"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["IDGENERATION"] : null;
        $this->stateless = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["STATELESS"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["STATELESS"] : null;

        // read in uniqueness attribute
        $this->uniqueness = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["UNIQUENESS"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["UNIQUENESS"] : null;

        $this->cacheLifeTime = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["CACHELIFETIME"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["CACHELIFETIME"] : "0";
        $this->objectName = $this->prefixPackage($this->objectName);
        if ($this->inheritFrom == '@sourceMeta') {
            $this->inheritFrom = '@' . $this->objectName;
        } else {
            $this->inheritFrom = $this->prefixPackage($this->inheritFrom);
        }

        // build BizRecord
        $this->bizRecord = new BizRecord($xmlArr["BIZDATAOBJ"]["BIZFIELDLIST"]["BIZFIELD"], "Openbizx\Data\BizField", $this);
        // build TableJoins
        $this->tableJoins = new MetaIterator($xmlArr["BIZDATAOBJ"]["TABLEJOINS"]["JOIN"], "Openbizx\Data\Tools\TableJoin", $this);
        // build ObjReferences
        $this->objReferences = new MetaIterator($xmlArr["BIZDATAOBJ"]["OBJREFERENCES"]["OBJECT"], "Openbizx\Data\Tools\ObjReference", $this);
        // read in parameters
        $this->parameters = new MetaIterator($xmlArr["BIZDATAOBJ"]["PARAMETERS"]["PARAMETER"], "Parameter");

        $this->messageFile = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["MESSAGEFILE"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["MESSAGEFILE"] : null;
        $this->objectMessages = MessageHelper::loadMessage($this->messageFile, $this->package);

        $this->eventManagerName = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["EVENTMANAGER"]) ? $xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["EVENTMANAGER"] : null;

        $this->dataPermControl = isset($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["DATAPERMCONTROL"]) ? strtoupper($xmlArr["BIZDATAOBJ"]["ATTRIBUTES"]["DATAPERMCONTROL"]) : 'N';
    }

    /**
     * Inherit from parent object. Name, Package, Class cannot be inherited
     *
     * @return void
     */
    protected function inheritParentObj()
    {
        if (!$this->inheritFrom) {
            return;
        }
        $parentObj = Openbizx::getObject($this->inheritFrom);

        $this->objectDescription = $this->objectDescription ? $this->objectDescription : $parentObj->objectDescription;
        $this->searchRule = $this->searchRule ? $this->searchRule : $parentObj->searchRule;
        $this->baseSearchRule = $this->searchRule;
        $this->sortRule = $this->sortRule ? $this->sortRule : $parentObj->sortRule;
        $this->baseSortRule = $this->sortRule;
        $this->otherSQLRule = $this->otherSQLRule ? $this->otherSQLRule : $parentObj->otherSQLRule;
        $this->accessRule = $this->accessRule ? $this->accessRule : $parentObj->accessRule;
        $this->updateCondition = $this->updateCondition ? $this->updateCondition : $parentObj->updateCondition;
        $this->deleteCondition = $this->deleteCondition ? $this->deleteCondition : $parentObj->deleteCondition;
        $this->databaseAliasName = $this->databaseAliasName ? $this->databaseAliasName : $parentObj->databaseAliasName;
        $this->mainTableName = $this->mainTableName ? $this->mainTableName : $parentObj->mainTableName;
        $this->idGeneration = $this->idGeneration ? $this->idGeneration : $parentObj->idGeneration;
        $this->stateless = $this->stateless ? $this->stateless : $parentObj->stateless;
        $this->dataPermControl = $this->dataPermControl ? $this->dataPermControl : $parentObj->dataPermControl;
        $this->bizRecord->merge($parentObj->bizRecord);

        foreach ($this->bizRecord as $field) {
            $field->adjustBizObjName($this->objectName);
        }

        $this->tableJoins->merge($parentObj->tableJoins);
        $this->objReferences->merge($parentObj->objReferences);
        $this->parameters->merge($parentObj->parameters);
    }

    /**
     * Get Message
     *
     * @param <type> $msgid message Id
     * @param array $params
     * @return string
     */
    protected function getMessage($msgid, $params = array())
    {
        $message = isset($this->objectMessages[$msgid]) ? $this->objectMessages[$msgid] : constant($msgid);
        //$message = I18n::getInstance()->translate($message);
        $message = I18n::t($message, $msgid, $this->getModuleName($this->objectName));
        return vsprintf($message, $params);
    }

    /**
     * Get session variables
     *
     * @param \Openbizx\Web\SessionContext $sessionContext
     */
    public function loadStatefullVars($sessionContext)
    {

    }

    /**
     * Set session variables
     *
     * @param \Openbizx\Web\SessionContext $sessionContext
     * @return void
     */
    public function saveStatefullVars($sessionContext)
    {

    }

    public function events()
    {
        if (!$this->eventManagerName && defined('EVENT_MANAGER')) {
            $this->eventManagerName = EVENT_MANAGER;
        } else {
            $this->eventManager = new EventManager();
        }
        if (!$this->eventManager) {
            $this->eventManager = Openbizx::getObject($this->eventManagerName);
        }
        return $this->eventManager;
    }

    /**
     * Reset rules
     *
     * @return void
     */
    public function resetRules()
    {
        $this->searchRule = $this->baseSearchRule;
        $this->sortRule = $this->baseSortRule;
        $this->otherSQLRule = $this->baseOtherSQLRule;
        return $this;
    }

    /**
     * Clear search rule.
     * Reset the search rule to default search rule set in metadata
     *
     * @return BizDataObj_Abstract
     */
    public function clearSearchRule()
    {
        $this->searchRule = $this->baseSearchRule;
        return $this;
    }

    /**
     * Clear sort rule.
     * Reset the sort rule to default sort rule set in metadata
     *
     * @return void
     */
    public function clearSortRule()  // reset sortrule
    {
        $this->sortRule = $this->baseSortRule;
        return $this;
    }

    /**
     * Clear other SQL rule.
     * Reset the other SQL rule to default other SQL rule set in metadata
     *
     * @return void
     */
    public function clearOtherSQLRule()
    {
        $this->otherSQLRule = $this->baseOtherSQLRule;
        return $this;
    }

    /**
     * Reset all rules (search, sort, other SQL rule)
     *
     * @return void
     */
    public function clearAllRules()
    {
        $this->searchRule = $this->baseSearchRule;
        $this->sortRule = $this->baseSortRule;
        $this->otherSQLRule = $this->baseOtherSQLRule;
        $this->queryLimit = array();
        return $this;
    }

    /**
     * Set search rule as text in sql where clause. i.e. [fieldName] opr Value
     *
     * @param string $rule search rule has format "[fieldName] opr Value"
     * @param boolean $overWrite specify if this rule should overwrite any existing rule
     * @return void
     * */
    public function setSearchRule($rule, $overWrite = false)
    {
        if (!$rule || $rule == "")
            return;
        if (!$this->searchRule || $overWrite == true) {
            $this->searchRule = $rule;
        } elseif (strpos($this->searchRule, $rule) === false) {
            $this->searchRule .= " AND " . $rule;
        }
    }

    /**
     * Set query parameter for parameter binding in the query
     *
     * @param array {fieldname:value} list
     * @return void
     * */
    public function setQueryParameters($paramValues)
    {
        foreach ($paramValues as $param => $value)
            $this->queryParams[$param] = $value;
    }

    public function getQueryParameters()
    {
        return $this->queryParams;
    }

    /**
     * Set search rule as text in sql order by clause. i.e. [fieldName] DESC|ASC
     *
     * @param string $rule sort rule has format "[fieldName] DESC|ASC"
     * @return void
     * */
    public function setSortRule($rule)
    {
        // sort rule has format "[fieldName] DESC|ASC", replace [fieldName] with table.column
        $this->sortRule = $rule;
    }

    /**
     * Set other SQL rule, append extra SQL statment in sql. i.e. GROUP BY [fieldName]
     *
     * @param string $rule search rule with SQL format "GROUP BY [fieldName] HAVING ..."
     * @return void
     * */
    public function setOtherSQLRule($rule)
    {
        // $rule has SQL format "GROUP BY [fieldName] HAVING ...". replace [fieldName] with table.column
        $this->otherSQLRule = $rule;
    }

    /**
     * Set limit of the query.
     *
     * @param int $count the number of records to return
     * @param int $offset the starting position of the result records
     * @return void
     */
    public function setLimit($count, $offset = 0)
    {
        if ($count < 0) {
            $count = 0;
        }
        if ($offset < 0) {
            $offset = 0;
        }
        $this->queryLimit['count'] = $count;
        $this->queryLimit['offset'] = $offset;
    }

    /**
     * Get database connection
     *
     * @return \Zend_Db_Adapter_Abstract
     * */
    public function getDBConnection($type = 'default')
    {
        switch (strtolower($type)) {
            case "default":
            case "read":
                if (isset($this->databaseAliasNameforRead)) {
                    $dbName = $this->databaseAliasNameforRead;
                } else {
                    $dbName = $this->databaseAliasName;
                }
                break;
            case "write":
                if (isset($this->databaseAliasNameforWrite)) {
                    $dbName = $this->databaseAliasNameforWrite;
                } else {
                    $dbName = $this->databaseAliasName;
                }
                break;
        }
        return Openbizx::$app->getDbConnection($dbName);
    }

    /**
     * Get the property of the object. Used in expression language
     *
     * @param string $propertyName name of the property
     * @return BizField|string property value
     */
    public function getProperty($propertyName)
    {
        $ret = parent::getProperty($propertyName);
        if ($ret)
            return $ret;
        if ($propertyName == "Table")
            return $this->table;
        if ($propertyName == "SearchRule")
            return $this->searchRule;
        // get control object if propertyName is "Field[fldname]"
        $pos1 = strpos($propertyName, "[");
        $pos2 = strpos($propertyName, "]");
        if ($pos1 > 0 && $pos2 > $pos1) {
            $propType = substr($propertyName, 0, $pos1);
            $fieldName = substr($propertyName, $pos1 + 1, $pos2 - $pos1 - 1);
            if ($propType == "param") {   // get parameter
                return $this->parameters->get($fieldName);
            }
            return $this->getField($fieldName);
        }
    }

    /**
     * Get object parameter value
     *
     * @param string $paramName name of the parameter
     * @return string parameter value
     */
    public function getParameter($paramName)
    {
        return $this->parameters[$paramName]->value;
    }

    /**
     * Get the object instance defined in the object reference
     *
     * @param string $objName the object name list in the ObjectReference part
     * @return BizDataObj object instance
     */
    public function getRefObject($objName)
    {
        // see if there is such object in the ObjReferences
        $objRef = $this->objReferences->get($objName);
        if (!$objRef)
            return null;

        // apply association on the object
        // $assc = $this->EvaluateExpression($objRef->association);
        // get the object instance
        $obj = Openbizx::getObject($objName);
        $obj->setAssociation($objRef, $this);
        return $obj;
    }

    /**
     * Get the Association (array)
     *
     * @return array array of association
     * */
    public function getAssociation()
    {
        return $this->association;
    }

    /**
     * Set the association of the object
     *
     * @param ObjReference $objRef
     * @param BizDataObj $asscObj
     * @return void
     */
    protected function setAssociation($objRef, $asscObj)
    {
        $this->association["AsscObjName"] = $asscObj->objectName;
        $this->association["Relationship"] = $objRef->relationship;
        $this->association["Table"] = $objRef->table;
        $this->association["Column"] = $objRef->column;
        $this->association["FieldRef"] = $objRef->fieldRef;
        $this->association["FieldRefVal"] = $asscObj->getFieldValue($objRef->fieldRef);
        $this->association["CondColumn"] = $objRef->condColumn;
        $this->association["CondValue"] = $objRef->condValue;
        $this->association["Condition"] = $objRef->condition;
        if ($objRef->relationship == "M-M" || $objRef->relationship == "Self-Self") {
            $this->association["XTable"] = $objRef->xTable;
            $this->association["XColumn1"] = $objRef->xColumn1;
            $this->association["XColumn2"] = $objRef->xColumn2;
            $this->association["XKeyColumn"] = $objRef->xKeyColumn;
            $this->association["XDataObj"] = $objRef->xDataObj;
        }
    }

    /**
     * Create an new (empty) record
     *
     * @return array - empty record array with default values
     * */
    abstract public function newRecord();

    /**
     * Insert record using given input record array
     *
     * @param array $recArr - associated array whose keys are field names of this BizDataObj
     * @return boolean - if return false, the caller can call GetErrorMessage to get the error.
     * */
    abstract public function insertRecord($recArr);

    /**
     * Update record using given input record array
     *
     * @param array $recArr - associated array whose keys are field names of this BizDataObj
     * @param array $oldRec - associated array who is the old record field name / value pairs
     * @return boolean - if return false, the caller can call GetErrorMessage to get the error.
     * */
    abstract public function updateRecord($recArr, $oldRec = null);

    /**
     * Delete current record or delete the given input record
     *
     * @param array $recArr - associated array whose keys are field names of this BizDataObj
     * @return boolean - if return false, the caller can call GetErrorMessage to get the error.
     * */
    abstract public function deleteRecord($recArr);

    /**
     * Fetches SQL result rows as a sequential array according the query rules set before.
     * Sample code:
     * <pre>
     *   $do->resetRules();
     *   $do->setSearchRule($search_rule1);
     *   $do->setSearchRule($search_rule2);
     *   $do->setSortRule($sort_rule);
     *   $do->SetOtherRule($groupby);
     *   $total = $do->count();
     *   $do->setLimit($count, $offset=0);
     *   $recordSet = $do->fetch();
     * </pre>
     *
     * @return array array of records
     */
    abstract public function fetch();

    /**
     * Fetches SQL result rows as a sequential array without using query rules set before.
     * Sample code:
     * <pre>
     *   // fetch all record with firstname starting with Mike
     *   $do->directFetch("[FirstName] LIKE 'Mike%'");
     *   // fetch first 10 records with firstname starting with Mike
     *   $do->directFetch("[FirstName] LIKE 'Mike%'", 10);
     *   // fetch 20th-30th records with firstname starting with Mike
     *   $do->directFetch("[FirstName] LIKE 'Mike%'", 10, 20);
     * </pre>
     *
     * @param string $searchRule the search rule string
     * @param int $count number of records to return
     * @param int $offset the starting point of the return records
     * @return array array of records
     */
    abstract public function directFetch($searchRule = "", $count = -1, $offset = 0);

    /**
     * Do the search query and return results set as PDOStatement.
     * Sample code:
     * <pre>
     *   $do->resetRules();
     *   $do->setSearchRule($search_rule1);
     *   $do->setSearchRule($search_rule2);
     *   $do->setSortRule($sort_rule);
     *   $do->SetOtherRule($groupby);
     *   $total = $do->count();
     *   $do->setLimit($count, $offset=0);
     *   $resultSet = $do->find();
     *   $do->getDBConnection()->setFetchMode(PDO::FETCH_ASSOC);
     *   while ($record = $resultSet->fetch())
     *   {
     *       print_r($record);
     *   }
     * </pre>
     *
     * @return PDOStatement PDO statement object
     */
    abstract public function find();

    /**
     * Count the number of record according to the search results set before.
     * it ignores limit setting
     *
     * @return int number of records
     */
    abstract public function count();
}


<?php
/**
 * Annotations
 *
 * @package     Chrisguitarguy\Annotation
 * @copyright   Christopher Davis <http://christopherdavis.me>
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace Chrisguitarguy\Annotation;

/**
 * The default reader implementation.
 *
 * @since   0.1
 * @author  Christopher Davis <http://christopherdavis.me>
 */
class DefaultReader implements ReaderInterface
{
    /**
     * The parser.
     *
     * @since   0.1
     * @access  protected
     * @var     ParserInterface
     */
    protected $parser;

    /**
     * The annotation collection.
     *
     * @since   0.1
     * @access  protected
     * @var     AnnotationCollectionInterface
     */
    protected $collection;

    /**
     * Constructor. Set up the collection and parser.
     *
     * @since   0.1
     * @access  public
     * @param   AnnotationCollectionInterface $collection
     * @param   ParserInterface $parser
     * @return  void
     */
    public function __construct(
        AnnotationCollectionInterface $collection=null,
        ParserInterface $parser=null
    ) {
        $this->setCollection($collection ?: new AnnotationCollection());
        $this->setParser($parser ?: new Parser());
    }

    /**
     * Set the collection.
     *
     * @since   0.1
     * @access  public
     * @param   AnnotationCollectionInterface $col
     * @return  ReaderInterface
     * @chainable
     */
    public function setCollection(AnnotationCollectionInterface $col)
    {
        $this->collection = $col;
        return $this;
    }

    /**
     * Get the collection.
     *
     * @since   0.1
     * @access  public
     * @return  AnnotationCollectionInterface
     */
    public function getCollection()
    {
        return $this->collection;
    }

    /**
     * Set the parser.
     *
     * @since   0.1
     * @access  public
     * @param   ParserInterface $parser
     * @return  ReaderInterface
     * @chainable
     */
    public function setParser(ParserInterface $parser)
    {
        $this->parser = $parser;
        return $this;
    }

    /**
     * Get the parser.
     *
     * @since   0.1
     * @access  public
     * @return  ParserInterface
     */
    public function getParser()
    {
        return $this->parser;
    }

    /**
     * {@inheritdoc}
     */
    public function readProperty($cls, $name)
    {
        try {
            $ref = new \ReflectionProperty($cls, $name);
        } catch (\Exception $e) {
            throw new \InvalidArgumentException(
                sprintf('Could not create ReflectionProperty: %s', $e->getMessage()),
                $e->getCode(),
                $e
            );
        }

        return $this->fromDocBlock($ref->getDocComment(), array(
            'property'  => $ref,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function readProperties($cls, $filter=null)
    {
        $cls = $this->createReflectionClass($cls);

        $rv = array();
        $props = $filter ? $cls->getProperties($filter) : $cls->getProperties();
        foreach ($props as $prop) {
            $rv[$prop->getName()] = $this->fromDocBlock($prop->getDocComment(), array(
                'class'     => $cls,
                'property'  => $prop,
            ));
        }

        return $rv;
    }

    /**
     * {@inheritdoc}
     */
    public function readClass($cls)
    {
        $ref = $this->createReflectionClass($cls);

        return $this->fromDocBlock($ref->getDocComment(), array(
            'class'     => $ref,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function readMethod($cls, $meth)
    {
        try {
            $ref = new \ReflectionMethod($cls, $meth);
        } catch (\Exception $e) {
            throw new \InvalidArgumentException(
                sprintf('Unable to create ReflectionMethod: %s', $e->getMessage()),
                $e->getCode(),
                $e
            );
        }

        return $this->fromDocBlock($ref->getDocComment(), array(
            'method'     => $ref,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function readMethods($cls, $filter=null)
    {
        $ref = $this->createReflectionClass($cls);

        $rv = array();
        $methods = $filter ? $ref->getMethods($filter) : $ref->getMethods();
        foreach ($methods as $meth) {
            $rv[$meth->getName()] = $this->fromDocBlock($meth->getDocComment(), array(
                'class'     => $ref,
                'method'    => $meth,
            ));
        }

        return $rv;
    }

    /**
     * {@inheritdoc}
     */
    public function readFunction($func)
    {
        try {
            $ref = new \ReflectionFunction($func);
        } catch (\Exception $e) {
            throw new \InvalidArgumentException(
                sprintf('Could not create ReflectionFunction: %s', $e->getMessage()),
                $e->getCode(),
                $e
            );
        }

        return $this->fromDocBlock($ref->getDocComment(), array(
            'function'  => $ref,
        ));
    }

    protected function createReflectionClass($cls)
    {
        try {
            return new \ReflectionClass($cls);
        } catch (\Exception $e) {
            throw new \InvalidArgumentException(
                sprintf('Could not create reflection class: %s', $e->getMessage()),
                $e->getCode(),
                $e
            );
        }
    }

    /**
     * Use the parser to parse a docblock into annotations and create annotation
     * objects.
     *
     * @since   0.1
     * @access  protected
     * @param   string $docblock The docblock to parse.
     * @param   array $context This is the place from where the docblock came
     *          This particular reader uses the keys `class`, `method`, `property`,
     *          and `function`. One or more of them will be present. Each would
     *          would be the appropriate Reflection(Class|Method|Property|Function)
     *          object. The array is converted into an AnnotationContextInterface
     *          implentation here, and, in this reader, passed as the second
     *          argument to the constructor.
     * @return  object[]
     */
    protected function fromDocblock($docblock, array $context=array())
    {
        $annotations = $this->getParser()->parse($docblock);

        $col = $this->getCollection();
        $rv = array();
        foreach ($annotations as $annot) {
            list($name, $positional, $named) = $annot;

            if ($obj = $col->create($name, $positional, $named, $context)) {
                $rv[] = $obj;
            }
        }

        return $rv;
    }
}


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace DoctrineModule\Stdlib\Hydrator\Strategy;

/**
 * When this strategy is used for Collections, if the new collection does not contain elements that are present in
 * the original collection, then this strategy remove elements from the original collection. For instance, if the
 * collection initially contains elements A and B, and that the new collection contains elements B and C, then the
 * final collection will contain elements B and C (while element A will be asked to be removed).
 *
 * This strategy is by reference, this means it won't use public API to add/remove elements to the collection
 *
 * @license MIT
 * @link    http://www.doctrine-project.org/
 * @since   0.7.0
 * @author  Michael Gallego <mic.gallego@gmail.com>
 */
class AllowRemoveByReference extends AbstractCollectionStrategy
{
    /**
     * {@inheritDoc}
     */
    public function hydrate($value)
    {
        $collection      = $this->getCollectionFromObjectByReference();
        $collectionArray = $collection->toArray();

        $toAdd    = array_udiff($value, $collectionArray, array($this, 'compareObjects'));
        $toRemove = array_udiff($collectionArray, $value, array($this, 'compareObjects'));

        foreach ($toAdd as $element) {
            $collection->add($element);
        }

        foreach ($toRemove as $element) {
            $collection->removeElement($element);
        }

        return $collection;
    }
}


<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
use D4rk4ng3l\Container\ContainerLoader;
use D4rk4ng3l\Oxid\Commands\CompileCommand;
use D4rk4ng3l\Console\Application;

class AOM
{
    private static $appPath;

    private static $registered = false;

    public static function getEnv()
    {
        return getenv('AOM_ENV') ?: 'prod';
    }

    /**
     * @return string
     */
    public static function getAppPath()
    {
        if (null === self::$appPath) {
            $paths = array(
                __DIR__ . '/..',
                __DIR__ . '/../../../..',
            );

            foreach ($paths as $path) {
                if (file_exists($path . '/vendor/autoload.php')) {
                    self::$appPath        = realpath($path);
                    break;
                }
            }

            if (!isset(self::$appPath)) {
                throw new \RuntimeException("Can't determine the application path.");
            }
        }

        return self::$appPath;
    }

    /**
     *
     */
    public static function registerAutoloader()
    {
        if (!self::$registered) {
            $classLoader = self::getAutoloader();
            AnnotationRegistry::registerLoader(array($classLoader, 'loadClass'));
        }
    }

    /**
     * @return CompiledContainer
     */
    public static function getContainer()
    {
        return ContainerLoader::getContainer(self::getAppPath());
    }

    /**
     * @throws Exception
     */
    public static function run()
    {
        self::registerAutoloader();

        $app = new Application();
        $app->add(new CompileCommand());
        $app->setContainer(self::getContainer());
        $app->setDefaultCommand('compile');
        $app->run();
    }

    /**
     * @throws \RuntimeException
     *
     * @return \Composer\Autoload\ClassLoader
     */
    public static function getAutoloader()
    {
        $autoLoaderFile = self::getAppPath() . '/vendor/autoload.php';

        if (!file_exists($autoLoaderFile)) {
            throw new \RuntimeException("Can't find autoloader.");
        }

        /** @var \Composer\Autoload\ClassLoader $loader */
        $loader = include $autoLoaderFile;

        return $loader;
    }
}


<?php

namespace CatLab\Charon\Laravel\Controllers;

use CatLab\Charon\Enums\Action;
use CatLab\Charon\Exceptions\ResourceException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Http\Request;

/**
 * Class ChildCrudController
 * @package CatLab\Charon\Laravel\Controllers
 */
trait ChildCrudController
{
    use CrudController;

    /**
     * ChildCrudController constructor.
     */
    public function __construct()
    {
        if (!defined('static::RESOURCE_DEFINITION')) {
            throw new ResourceException("All classes using CrudController must define a constant called RESOURCE_DEFINITION");
        }

        parent::__construct(static::RESOURCE_DEFINITION);
    }

    /**
     * @param Request $request
     * @return Relation
     */
    public abstract function getRelationship(Request $request) : Relation;

    /**
     * @param Request $request
     * @return Model
     */
    public abstract function getParent(Request $request) : Model;

    /**
     * @return string
     */
    public abstract function getRelationshipKey() : string;

    /**
     * @param Request $request
     * @return mixed
     */
    protected function getIndexQuery(Request $request)
    {
        return $this->getRelationship($request);
    }

    /**
     * Called before saveEntity
     * @param \Illuminate\Database\Eloquent\Model $entity
     */
    protected function beforeSaveEntity(Request $request, \Illuminate\Database\Eloquent\Model $entity)
    {
        $relationship = $this->getRelationship($request);
        if ($relationship instanceof HasMany) {
            $this->getInverseRelationship($entity)->associate($this->getParent($request));
        }
    }

    /**
     * Get the inverse relationship.
     * @param Model $entity
     * @return mixed
     */
    protected function getInverseRelationship(\Illuminate\Database\Eloquent\Model $entity)
    {
        return $entity->{$this->getRelationshipKey()}();
    }

    /**
     * Checks if user is authorized to watch an index of the entities.
     * @param Request $request
     */
    protected function authorizeIndex(Request $request)
    {
        $this->authorizeCrudRequest(Action::INDEX, null, $this->getParent($request));
    }

    /**
     * Checks if user is authorized to create an entity.
     * @param Request $request
     */
    protected function authorizeCreate(Request $request)
    {
        $this->authorizeCrudRequest(Action::CREATE, null, $this->getParent($request));
    }
}


<?php namespace Interpro\QuickStorage\Laravel\Handle\Flat;

use Illuminate\Support\Facades\Log;
use Interpro\QuickStorage\Concept\Command\Flat\UpdateGroupItemFlatCommand;
use Interpro\QuickStorage\Concept\FieldProviding\FieldSaveMediator;
use Interpro\QuickStorage\Laravel\Model\Bool;
use Interpro\QuickStorage\Laravel\Model\Group;
use Interpro\QuickStorage\Laravel\Model\Imageitem;
use Interpro\QuickStorage\Laravel\Model\Numb;
use Interpro\QuickStorage\Laravel\Model\Pdatetime;
use Interpro\QuickStorage\Laravel\Model\Stringfield;
use Interpro\QuickStorage\Laravel\Model\Textfield;

class UpdateGroupItemFlatCommandHandler {

    private $saveMediator;

    /**
     * Create the command handler.
     *
     * @return void
     */
    public function __construct(FieldSaveMediator $saveMediator)
    {
        $this->saveMediator = $saveMediator;
    }

    /**
     * Handle the command.
     *
     * @param  UpdateGroupItemFlatCommand  $command
     * @return void
     */
    public function handle(UpdateGroupItemFlatCommand $command)
    {
        $qstorage = config('qstorage');

        $data_arr = &$command->data_arr;

        $block_name = $data_arr['block_name'];
        $group_id   = $data_arr['group_id'];
        $group_name = $data_arr['group_name'];

        $group_item = Group::find($group_id);

        if($group_item)
        {
            if(array_key_exists($block_name, $qstorage))
            {
                $blockstruct = &$qstorage[$block_name];
                $groupstruct = &$blockstruct['groups'][$group_name];

                $field_types = [];
                foreach(['stringfields', 'textfields', 'numbs', 'images', 'bools', 'pdatetimes'] as $typename) {
                    if (array_key_exists($typename, $groupstruct)){
                        foreach($groupstruct[$typename] as $field_name){
                            $field_types[$field_name] = $typename;
                        }
                    }
                }

                if(array_key_exists('show', $data_arr))
                {
                    $group_item->show = $data_arr['show'] == "true" ? true : false;
                }

                if(array_key_exists('sorter', $data_arr))
                {
                    $group_item->sorter = $data_arr['sorter'];
                }

                if(array_key_exists('owner', $data_arr))
                {
                    $group_item->owner_id = $data_arr['owner'];
                }

                if(array_key_exists('slug', $data_arr))
                {
                    $group_item->slug = $data_arr['slug'];
                }

                $group_item->save();

                foreach($data_arr as $field_name => $field_val)
                {
                    if($field_name == 'block_name' or $field_name == 'group_name' or $field_name == 'show' or $field_name == 'sorter' or $field_name == 'owner' or $field_name == 'slug'){
                        continue;
                    }

                    if(array_key_exists($field_name, $field_types)){

                        $typename = $field_types[$field_name];

                        if($typename == 'stringfields'){
                            $field = Stringfield::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>$group_id, 'group_name'=>$group_name]);
                            $field->value = $field_val;
                            $group_item->stringfields()->save($field);

                        }else if($typename == 'textfields'){
                            $field = Textfield::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>$group_id, 'group_name'=>$group_name]);
                            $field->value = $field_val;
                            $group_item->textfields()->save($field);

                        }else if($typename == 'numbs'){
                            $field = Numb::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>$group_id, 'group_name'=>$group_name]);
                            $field->value = $field_val;
                            $group_item->numbs()->save($field);

                        }else if($typename == 'bools'){
                            $field = Bool::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>$group_id, 'group_name'=>$group_name]);
                            $field->value = $field_val == "true" ? true : false;
                            $group_item->bools()->save($field);

                        }else if($typename == 'pdatetimes'){
                            $field = Pdatetime::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>$group_id, 'group_name'=>$group_name]);
                            $field->value = $field_val;
                            $group_item->pdatetimes()->save($field);

                        }else if($typename == 'images'){
                            $field = Imageitem::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>$group_id, 'group_name'=>$group_name]);

                            if(array_key_exists('alt', $field_val)){
                                $field->alt = $field_val['alt'];
                            }
                            if(array_key_exists('original_link', $field_val)){
                                $field->original_link = $field_val['original_link'];
                            }
                            if(array_key_exists('primary_link', $field_val)){
                                $field->primary_link = $field_val['primary_link'];
                            }
                            if(array_key_exists('secondary_link', $field_val)){
                                $field->secondary_link = $field_val['secondary_link'];
                            }
                            if(array_key_exists('icon_link', $field_val)){
                                $field->icon_link = $field_val['icon_link'];
                            }
                            if(array_key_exists('preview_link', $field_val)){
                                $field->preview_link = $field_val['preview_link'];
                            }
                            if(array_key_exists('prefix', $field_val)){
                                $field->prefix = $field_val['prefix'];
                            }

                            $field->cache_index++;

                            $group_item->images()->save($field);

                        }

                    }else{
                        Log::info('Ошибка при сохранении элемента группы('.$group_name.'): нет поля '.$field_name.' ни в одном типе в настройках блока!');
                    }

                }

                //С доп. полями пока не ясно

                /*Сохраняем все внешние (отностиельно quickstorage поля)
                foreach($this->saveMediator->list as $suffix=>$saver) {
                    if(array_key_exists($suffix, $dataobj)){
                        $dataobj['entity_name'] = $block_name;
                        $saver->save($suffix, $dataobj[$suffix]);
                    }
                }*/

            }else{
                throw new \Exception('Не нашел блок по имени '.$block_name);
            }
        }else{
            throw new \Exception('Не нашел элемент группы по id в БД '.$group_id);
        }
    }

}


<?php
namespace Webdevvie\Nestis;

/**
 * @author John Bakker <me@johnbakker.name>
 * built using information from http://unicode.org/emoji/charts/full-emoji-list.html
 *
 *
 *Copyright 2016 John Bakker <me@johnbakker.name>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
class Nestis
{
    /**
     * Gets a nested value from an object
     *
     * @param string $pattern
     * @param mixed  $object
     * @param mixed  $default
     * @return mixed|null
     */
    public function getNestedItem($pattern, $object, $default = null)
    {
        $parts = explode("/", $pattern);
        $lastObject = $object;
        $nr = 0;
        $totalParts = count($parts);
        $item = null;
        foreach ($parts as $part) {
            $item = null;
            $nr++;
            $found = false;
            if ($part == '') {
                return $default;
            }
            try {
                if (is_object($lastObject)) {
                    $mthd = 'get' . ucfirst($part);
                    $mthdIs = 'is' . ucfirst($part);
                    if (substr($part, 0, 2) == '::') {
                        $reflect = new \ReflectionObject($lastObject);
                        $props = $reflect->getStaticProperties();
                        $nm = substr($part, 2);
                        if (isset($props[$nm])) {
                            $prop = $reflect->getProperty($nm);
                            if ($prop->isPublic()) {
                                $item = $lastObject::$$nm;
                            }
                        }
                    } elseif (is_callable([$lastObject, $mthd])) {
                        $item = $lastObject->$mthd();
                    } elseif (is_callable([$lastObject, $mthdIs])) {
                        $item = $lastObject->$mthdIs();
                    } elseif (is_callable([$lastObject, $part])) {
                        $item = $lastObject->$part();
                    } else {
                        $reflect = new \ReflectionObject($lastObject);
                        $prop = $reflect->getProperty($part);
                        if ($prop->isPublic()) {
                            $item = $lastObject->$part;
                        }
                    }
                    $found = true;
                } elseif (is_array($lastObject)) {
                    if (array_key_exists($part, $lastObject)) {
                        $item = $lastObject[$part];
                        $found = true;
                    }
                }
            } catch (\Exception $e) {
                return $default;
            }
            if ((!is_null($item) && !is_object($item) && !is_array($item) && $nr < $totalParts) || !$found) {
                //its a string,boolean or integer , but we're not at the end of the list so we can't find the end
                return $default;
            }
            $lastObject = $item;
        }
        return $item;
    }
}


<?php

namespace GetOlympus\Field;

use GetOlympus\Zeus\Field\Controller\Field;
use GetOlympus\Zeus\Translate\Controller\Translate;

/**
 * Builds Code field.
 *
 * @package Field
 * @subpackage Code
 * @author Achraf Chouk <achrafchouk@gmail.com>
 * @since 0.0.1
 *
 * @see https://olympus.readme.io/v1.0/docs/code-field
 *
 */

class Code extends Field
{
    /**
     * Prepare variables.
     */
    protected function setVars()
    {
        $this->getModel()->setFaIcon('fa-code');
        $this->getModel()->setScript('js'.S.'code.js');
        $this->getModel()->setStyle('css'.S.'code.css');
        $this->getModel()->setTemplate('code.html.twig');
    }

    /**
     * Prepare HTML component.
     *
     * @param array $content
     * @param array $details
     */
    protected function getVars($content, $details = [])
    {
        // Build defaults
        $defaults = [
            'id' => '',
            'title' => Translate::t('code.title', [], 'codefield'),
            'description' => '',
            'change' => true,
            'readonly' => false,
            'rows' => 4,
            'modes' => $this->getCodeModes(),
            'default' => [
                'mode' => 'application/json',
                'code' => ''
            ],
        ];

        // Build defaults data
        $vars = array_merge($defaults, $content);
        $vars['default']['mode'] = $this->retrieveMode($vars['default']['mode']);

        // Retrieve field value
        $vars['val'] = $this->getValue($content['id'], $details, $vars['default']);

        // Update vars
        $this->getModel()->setVars($vars);
    }

    /**
     * Return all available modes.
     *
     * @return array $codes
     */
    protected function getCodeModes()
    {
        // List all modes
        $modes = $this->getModes();
        $codemodes = [];

        // Build select
        foreach ($modes as $mode) {
            $codemodes[$mode['mode'][0]] = $mode['title'];
        }

        return $codemodes;
    }

    /**
     * Return all available modes.
     *
     * @return array $modes
     */
    protected function getModes()
    {
        return [
            [
                'title' => Translate::t('code.modes.css', [], 'codefield'),
                'mode' => ['text/css', 'css'],
            ],
            [
                'title' => Translate::t('code.modes.diff', [], 'codefield'),
                'mode' => ['text/x-diff','x-diff','diff'],
            ],
            [
                'title' => Translate::t('code.modes.html', [], 'codefield'),
                'mode' => ['text/html','html'],
            ],
            [
                'title' => Translate::t('code.modes.js', [], 'codefield'),
                'mode' => ['text/javascript','javascript','js'],
            ],
            [
                'title' => Translate::t('code.modes.json', [], 'codefield'),
                'mode' => ['application/json','json'],
            ],
            [
                'title' => Translate::t('code.modes.md', [], 'codefield'),
                'mode' => ['text/x-markdown','markdown','md'],
            ],
            [
                'title' => Translate::t('code.modes.php', [], 'codefield'),
                'mode' => ['application/x-httpd-php','x-httpd-php','php'],
            ],
            [
                'title' => Translate::t('code.modes.python', [], 'codefield'),
                'mode' => ['text/x-python','x-python','python'],
            ],
            [
                'title' => Translate::t('code.modes.ruby', [], 'codefield'),
                'mode' => ['text/x-ruby','x-ruby','ruby'],
            ],
            [
                'title' => Translate::t('code.modes.sh', [], 'codefield'),
                'mode' => ['text/x-sh','x-sh','sh'],
            ],
            [
                'title' => Translate::t('code.modes.mysql', [], 'codefield'),
                'mode' => ['text/x-mysql','x-mysql','mysql'],
            ],
            [
                'title' => Translate::t('code.modes.mariadb', [], 'codefield'),
                'mode' => ['text/x-mariadb','x-mariadb','mariadb'],
            ],
            [
                'title' => Translate::t('code.modes.xml', [], 'codefield'),
                'mode' => ['application/xml','xml'],
            ],
            [
                'title' => Translate::t('code.modes.yaml', [], 'codefield'),
                'mode' => ['text/x-yaml','x-yaml','yaml'],
            ],
        ];
    }

    /**
     * Return all available modes.
     *
     * @param   string $search  Mode we are looking for
     * @return  string $good    Real mode name
     */
    protected function retrieveMode($search)
    {
        // List all modes
        $modes = $this->getModes();

        // Build select
        foreach ($modes as $mode) {
            if (in_array($search, $mode['mode'])) {
                return $mode['mode'][0];
            }
        }

        return 'application/json';
    }
}


<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Openbizx\Web;

//namespace Openbizx\web;
/**
 * Description of UserAgent
 *
 * @author agus
 */
class UserAgent
{

    private $_userAgent;
    private $_style;
    private $_device;
    private $_isTouch = false;

    //put your code here

    public function init()
    {
        $device = '';
        $style = '';
        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
            return;
        }
        if (stristr($_SERVER['HTTP_USER_AGENT'], 'ipad')) {
            $device = "ipad";
            $style = "touch";
        } else if (stristr($_SERVER['HTTP_USER_AGENT'], 'iphone')
                || strstr($_SERVER['HTTP_USER_AGENT'], 'ipod')) {
            $device = "iphone";
            $style = "touch";
        } else if (stristr($_SERVER['HTTP_USER_AGENT'], 'blackberry')) {
            $device = "blackberry";
            $style = "touch";
        } else if (stristr($_SERVER['HTTP_USER_AGENT'], 'android')) {
            $device = "android";
            $style = "touch";
        }

        $this->_userAgent = $device;
        $this->_style = $style;
        if ($device != '' && $style == 'touch') {
            $this->_isTouch = true;
            $this->_device = 'mobile';
        } else {
            $this->_isTouch = false;
            $this->_device = 'desktop';
        }
    }

    public function getUserAgent()
    {
        if ($this->_userAgent !== null) {
            $this->init();
        }
        return $this->_userAgent;
    }

    public function getStyle()
    {
        if ($this->_style !== null) {
            $this->init();
        }
        return $this->_style;
    }

    public function isTouch()
    {
        if ($this->_isTouch !== null) {
            $this->init();
        }
        return $this->_isTouch;
    }

    public function getDevice()
    {
        if ($this->_device !== null) {
            $this->init();
        }
        return $this->_device;
    }

}


<?php

namespace Environaut\Config;

use Environaut\Config\IConfig;
use Environaut\Config\Parameters;

/**
 * Default representation of the config file data.
 */
class Config implements IConfig
{
    /**
     * @var Parameters config data as array wrapped in a Parameters instance
     */
    protected $config;

    /**
     * Create new instance with some default config data.
     *
     * @param array $config_data
     */
    public function __construct(array $config_data = array())
    {
        $this->config = new Parameters($config_data);
    }

    /**
     * @return array of parameters to create checks
     */
    public function getCheckDefinitions()
    {
        return $this->config->get('checks', array());
    }

    /**
     * Defaults to "Environaut\Export\Export".
     *
     * @return string (namespaced) class name to use for exporting a report
     */
    public function getExportImplementor()
    {
        $export = new Parameters($this->config->get('export', array()));
        return $export->get(self::PARAM_CLASS, 'Environaut\Export\Export');
    }

    /**
     * Defaults to "Environaut\Report\Report".
     *
     * @return string (namespaced) class name to use for a report
     */
    public function getReportImplementor()
    {
        $report = new Parameters($this->config->get('report', array()));
        return $report->get(self::PARAM_CLASS, 'Environaut\Report\Report');
    }

    /**
     * Defaults to "Environaut\Runner\Runner".
     *
     * @return string (namespaced) class name to use for running checks read from the config
     */
    public function getRunnerImplementor()
    {
        $runner = new Parameters($this->config->get('runner', array()));
        return $runner->get(self::PARAM_CLASS, 'Environaut\Runner\Runner');
    }

    /**
     * Defaults to "Environaut\Cache\ReadOnlyCache".
     *
     * @return string (namespaced) class name to use for cache given to checks
     */
    public function getReadOnlyCacheImplementor()
    {
        $cache = new Parameters($this->config->get('cache', array()));
        return $cache->get('readonly_class', 'Environaut\Cache\ReadOnlyCache');
    }

    /**
     * Defaults to "Environaut\Cache\Cache".
     *
     * @return string (namespaced) class name to use for writing cachable settings after report generation
     */
    public function getCacheImplementor()
    {
        $cache = new Parameters($this->config->get('cache', array()));
        return $cache->get(self::PARAM_CLASS, 'Environaut\Cache\Cache');
    }

    /**
     * Returns the config value for the given key.
     *
     * @param string $key name of config key
     * @param mixed $default value to return if key doesn't exist
     *
     * @return mixed value for that key or default given
     */
    public function get($key, $default = null)
    {
        return $this->config->get($key, $default);
    }

    /**
     * Returns whether the config key exists or not.
     *
     * @param string $key name of config key to check
     *
     * @return bool true, if key exists; false otherwise
     */
    public function has($key)
    {
        return $this->config->has($key);
    }

    /**
     * Sets a given value to the config under the specified key.
     *
     * @param string $key name of config entry
     * @param mixed $value value to set for the given key
     *
     * @return mixed the value set
     */
    public function set($key, $value)
    {
        return $this->config->set($key, $value);
    }

    /**
     * Returns the config data as an associative array.
     *
     * @return array with all config data
     */
    public function toArray()
    {
        return $this->config->getAll();
    }
}