<?php

namespace Environaut\Config\Reader;

use Environaut\Config\Reader\IConfigReader;

/**
 * Reads a configuration from a PHP file that
 * returns the config data as an associative array.
 */
class PhpConfigReader implements IConfigReader
{
    /**
     * Reads the config from the given location and
     * returns the data as an associative array.
     *
     * @param mixed $location location to read config data from (usually file/directory path)
     *
     * @return array config data as associative array
     *
     * @throws \InvalidArgumentException in case of problems handling the given location
     */
    public function getConfigData($location)
    {
        return $this->getExampleConfiguration($location);

        if (is_dir($location)) {
            $location = $location . DIRECTORY_SEPARATOR . 'environaut.php';
        }

        if (!is_readable($location)) {
            throw new \InvalidArgumentException("Configuration file not readable: $location");
        }

        $config = include($location);

        return $config;
    }
}


<?php

declare(strict_types=1);

namespace NAttreid\Utils;

use Nette\SmartObject;
use Nette\Utils\Random;

/**
 * Docasny soubor
 *
 * @property string $delimiter
 * @property string $enclosure
 * @property string $escapeChar
 *
 * @author Attreid <attreid@gmail.com>
 */
class TempFile
{
	use SmartObject;

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

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

	/** @var resource */
	private $handler;

	/** @var string */
	private $delimiter = ';';

	/** @var string */
	private $enclosure = '"';

	/** @var string */
	private $escapeChar = "\\";

	protected function getDelimiter(): string
	{
		return $this->delimiter;
	}

	protected function setDelimiter(string $delimiter): void
	{
		$this->delimiter = $delimiter;
	}

	protected function getEnclosure(): string
	{
		return $this->enclosure;
	}

	protected function setEnclosure(string $enclosure): void
	{
		$this->enclosure = $enclosure;
	}

	protected function getEscapeChar(): string
	{
		return $this->escapeChar;
	}

	protected function setEscapeChar(string $escapeChar): void
	{
		$this->escapeChar = $escapeChar;
	}

	/**
	 *
	 * @param string $name pokud je null vygeneruje se random
	 * @param bool $timePrefix
	 */
	public function __construct(string $name = null, bool $timePrefix = false)
	{
		if ($name === null) {
			$name = Random::generate();
		}
		if ($timePrefix) {
			$date = new \DateTime;
			$name = $date->format('Y-m-d_H-i-s') . '_' . $name;
		}
		$this->name = $name;
		$this->file = $this->getUniqueFile($name);
		$this->handler = fopen($this->file, 'w+');
	}

	/**
	 * @param string $name
	 * @return string
	 */
	private function getUniqueFile(string $name): string
	{
		$file = sys_get_temp_dir() . '/' . $name;
		if (file_exists($file)) {
			$char = Random::generate(1);
			return $this->getUniqueFile($char . '_' . $name);
		} else {
			return $file;
		}
	}

	/**
	 * Zapise do souboru
	 * @param string $str
	 * @return self
	 */
	public function write(string $str): self
	{
		fwrite($this->handler, $str);
		return $this;
	}

	/**
	 * Zapise jako csv radek
	 * @param array $data
	 * @return self
	 */
	public function writeCsv(array $data): self
	{
		fputcsv($this->handler, $data, $this->delimiter, $this->enclosure, $this->escapeChar);
		return $this;
	}

	public function move(string $path): ?string
	{
		$file = $path . '/' . $this->name;
		if (@rename($this->file, $file)) {
			return $file;
		}
		return null;
	}

	public function copy(string $path): ?string
	{
		$file = $path . '/' . $this->name;
		if (@copy($this->file, $file)) {
			return $file;
		}
		return null;
	}

	public function __destruct()
	{
		fclose($this->handler);
		@unlink($this->file);
	}

	public function __toString()
	{
		return $this->file;
	}

}


<?php

namespace Tree6bee\Queue\Drivers;

use Pheanstalk\Pheanstalk;
use Pheanstalk\Job as PheanstalkJob;
use Pheanstalk\PheanstalkInterface;
use Tree6bee\Queue\Drivers\Jobs\BeanstalkdJob;

class Beanstalkd implements QueueInterface
{
    /**
     * @var Pheanstalk
     */
    protected $pheanstalk;

    public function __construct($host, $port = PheanstalkInterface::DEFAULT_PORT)
    {
        $this->pheanstalk = new Pheanstalk($host, $port);
    }

    /**
     * 立即分发到队列
     *
     * @param string $queue
     * @param string $payload
     * @param int $ttr
     *
     * @return int
     */
    public function push($queue, $payload, $ttr = PheanstalkInterface::DEFAULT_TTR)
    {
        return $this->pushRaw($queue, $payload, $ttr);
    }

    /**
     * 延时分发到队列
     *
     * @param $delay
     * @param $queue
     * @param $payload
     * @param int $ttr
     *
     * @return int
     */
    public function later($delay, $queue, $payload, $ttr = PheanstalkInterface::DEFAULT_TTR)
    {
        return $this->pushRaw($queue, $payload, $ttr, $delay);
    }

    /**
     * Push a raw payload onto the queue.
     *
     * @param string $queue 队列
     * @param string $payload job内容
     * @param int $priority 优先级，可以为0-2^32（4,294,967,295），值越小优先级越高，默认为1024。
     * @param int $delay 延迟ready的秒数，在这段时间job为delayed状态。
     * @param int $ttr retry_after 允许worker执行的最大秒数，
     *  如果worker在这段时间不能delete，release，bury job，那么job超时，服务器将release此job，此job的状态迁移为ready。
     *  最小为1秒，如果客户端指定为0将会被重置为1。
     *
     * @return int
     */
    protected function pushRaw(
        $queue,
        $payload,
        $ttr = PheanstalkInterface::DEFAULT_TTR,
        $delay = PheanstalkInterface::DEFAULT_DELAY,
        $priority = PheanstalkInterface::DEFAULT_PRIORITY
    ) {
        if (empty($ttr)) {
            $ttr = PheanstalkInterface::DEFAULT_TTR;
        }

        return $this->pheanstalk
            ->useTube($queue)
            ->put($payload, $priority, $delay, $ttr);
    }

    /**
     * @param $queue
     *
     * @return null|\Tree6bee\Queue\Drivers\Jobs\JobInterface
     */
    public function pop($queue)
    {
        $job = $this->pheanstalk->watchOnly($queue)->reserve(0);

        if ($job instanceof PheanstalkJob) {
            return new BeanstalkdJob($this->pheanstalk, $job, $queue);
        }

        return null;
    }
}


<?php

namespace Interpro\QuickStorage\Laravel;

use Interpro\QuickStorage\Concept\Exception\WrongGroupNameException;
use Interpro\QuickStorage\Concept\Repository as RepositoryInterface;
use Interpro\QuickStorage\Concept\QSource as QSourceInterface;
use Interpro\QuickStorage\Concept\StorageStructure as StorageStructureInterface;

class Repository implements RepositoryInterface
{
    private $qSource;
    private $storageStruct;

    private $blocks;
    private $groups_blended;
    private $groups_ordered;

    public function __construct(StorageStructureInterface $storageStruct, QSourceInterface $qSource)
    {
        $this->qSource = $qSource;
        $this->storageStruct = $storageStruct;
        $this->blocks = [];

        //Элементы групп запрашиваются в перемешку от разных владельцев
        $this->groups_blended = [];

        //Упорядочиваться будут по мере запроса для каждого владельца
        //Внутри массив групп с массивом элементов (массив) id_$id ключем со значением - массив полей
        $this->groups_ordered = [];
    }

    public function getBlock($block_name)
    {
        if(!array_key_exists($block_name, $this->blocks))
        {
            $block_array = $this->qSource->blockQuery($block_name);
            $this->blocks[$block_name] = $block_array;

            return $block_array;
        }else{

            return $this->blocks[$block_name];
        }
    }

    public function getGroup($block_name, $group_name, $owner_id=0)
    {
        $this->checkGroupOwnedExistence($block_name, $group_name, $owner_id);

        return $this->groups_ordered[$group_name]['id_'.$owner_id];
    }

    /**
     * @param string $block_name
     * @param string $group_name
     *
     * @return int
     */
    public function getGroupCount($block_name, $group_name)
    {
        return $this->qSource->groupCount($block_name, $group_name);
    }

    public function getGroupFlat($block_name, $group_name)
    {
        $this->checkGroupOwnedExistence($block_name, $group_name);

        return $this->groups_blended[$group_name];
    }

    //Ничего не кэширующий метод сквозняком в Querer
    public function getGroupItem($block_name, $group_name, $group_id)
    {
        if($this->storageStruct->groupInBlockExist(
            $block_name,
            $group_name
        ))
        {
            return $this->qSource->groupItemQuery($block_name, $group_name, $group_id);
        }else{
            throw new WrongGroupNameException('Группа '.$group_name.' в составе блока '.$block_name.' не найдена.');
        }
    }

    //Ничего не кэширующий метод сквозняком в Querer
    public function getGroupItemBySlug($block_name, $group_name, $slug)
    {
        return $this->qSource->groupItemBySlugQuery($block_name, $group_name, $slug);
    }

    private function orderGroup($group_name)
    {
        $ordered = & $this->groups_ordered[$group_name];

        foreach($this->groups_blended[$group_name] as $key => $fields)
        {
            $idkey = 'id_'.$fields['owner_id'];

            if(!array_key_exists($idkey, $ordered))
            {
                $ordered[$idkey] = [];
            }
            $ordered[$idkey][] = $fields;
        }
    }

    private function checkGroupExistence($block_name, $group_name)
    {
//Схема не работает, когда 2 запроса подряд с разными параметрами
//        if(!array_key_exists($group_name, $this->groups_blended))
//        {
        //Извлекаем из хранилища элементы целевой группы с полями
        $group_array = $this->qSource->groupQuery($block_name, $group_name);
        $this->groups_blended[$group_name] = $group_array;
//        }
    }

    private function checkGroupOwnedExistence($block_name, $group_name, $owner_id=0)
    {
        $this->checkGroupExistence($block_name, $group_name);
//Схема не работает, когда 2 запроса подряд с разными параметрами
//        if(!array_key_exists($group_name, $this->groups_ordered))
//        {
        $this->groups_ordered[$group_name]=[];

        $this->orderGroup($group_name);
//        }

        $ordered = & $this->groups_ordered[$group_name];

        $owner_key = 'id_'.$owner_id;

        if(!array_key_exists($owner_key, $ordered))
        {
            $ordered[$owner_key] = [];
        }

        return $ordered[$owner_key];
    }

}


<?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.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: InputDate.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
use Openbizx\Easy\Element\InputText;

/**
 * InputDate class is element for input date with date picker
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class InputDate extends InputText {
    public $dateFormat;

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr) {
        parent::readMetaData($xmlArr);
        $this->dateFormat  = isset($xmlArr["ATTRIBUTES"]["DATEFORMAT"]) ? $xmlArr["ATTRIBUTES"]["DATEFORMAT"] : null;
    }

    /**
     * Render / draw the element according to the mode
     *
     * @return string HTML text
     */
    public function render() {
        Openbizx::$app->getClientProxy()->includeCalendarScripts();

        $format = $this->dateFormat ? $this->dateFormat : "%Y-%m-%d";

        $sHTML = parent::render();

        $showTime = 'false';
        //$image = "getImageUrl()."/calendar.gif\" border=0 title=\"Select date...\" align='top' hspace='2'>";
        $sHTML .= "objectName','$format',$showTime,true);\">";
        return $sHTML;
    }

}


<?php

namespace Environaut\Command;

use Environaut\Cache\ICache;
use Environaut\Cache\IReadOnlyCache;
use Environaut\Cache\ReadOnlyCache;
use Environaut\Command\Command;
use Environaut\Config\Parameters;
use Environaut\Runner\IRunner;
use Environaut\Export\IExport;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Checks the environment according to the given configuration,
 * collects results in a report and exports the messages and
 * settings from the report via an exporter.
 */
class CheckCommand extends Command
{
    /**
     * @var \Environaut\Config\IConfig
     */
    protected $config;

    /**
     * @var \Environaut\Report\IReport
     */
    protected $report;

    /**
     * @var string config path from CLI option (or default fallback name)
     */
    protected $config_path;

    /**
     * @var \Environaut\Config\IConfigHandler
     */
    protected $config_handler;

    /**
     * @var \Environaut\Cache\IReadOnlyCache
     */
    protected $readonly_cache;

    /**
     * Define options supported by this command and set name, description and help texts.
     */
    protected function configure()
    {
        parent::configure();

        $this->setName('check');

        $this->addOption(
            'config',
            'c',
            InputOption::VALUE_OPTIONAL,
            'Path to config file that defines the checks to process.'
        );

        $this->addOption(
            'config-handler',
            null,
            InputOption::VALUE_OPTIONAL,
            'Classname of a custom config handler implementing Environaut\Config\IConfigHandler.'
        );

        $this->addOption(
            'cache-location',
            null,
            InputOption::VALUE_OPTIONAL,
            'File path and name for the cache location to read from. Overrides defaults and config file value.'
        );

        $this->addOption(
            'no-cache',
            null,
            InputOption::VALUE_NONE,
            'Disables the use of caching (reading/writing). Remember, that the old cache file still survives!'
        );

        $this->setDescription('Check environment according to a set of checks.');

        $this->setHelp(
<<<EOT

<info>This command checks the environment according to the checks from the configuration file.</info>

By default the <comment>current working directory</comment> will be used to find the configuration file and
all defined classes (checks and validators etc.).

Use
<comment>--autoload-dir [path/to/src]</comment> to change the autoload directory or
<comment>--config [path/to/environaut.(json|xml|php)]</comment> to set the configuration file lookup path or
<comment>--no-cache</comment> to disable to usage of a cache file.
EOT
        );
    }

    /**
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->displayIntro();

        $this->readConfig();

        $this->runChecks();

        $this->runExport();

        $this->displayOutro();
    }

    /**
     * Reads configuration via default or given config file handler
     */
    protected function readConfig()
    {
        $this->config = $this->getConfigHandler()->getConfig();

        if ($this->config->has('introduction')) {
            $this->output->writeln($this->config->get('introduction'));
            $this->output->writeln('');
        }
    }

    /**
     * Runs all checks and collects results in a report.
     */
    protected function runChecks()
    {
        $runner_impl = $this->config->getRunnerImplementor();

        $runner = new $runner_impl();

        if (!$runner instanceof IRunner) {
            throw new \InvalidArgumentException('The given runner "' . $runner_impl . '" must implement IRunner.');
        }

        $runner->setConfig($this->config);
        $runner->setCommand($this);
        $runner->setParameters(new Parameters($this->config->get('runner', array())));
        $runner->setCache($this->getLoadedCache());

        $run_was_successful = $runner->run();

        $this->report = $runner->getReport();

        $this->writeCache($run_was_successful);
    }

    /**
     * Runs the export with the collected report from the checks.
     */
    protected function runExport()
    {
        $export_impl = $this->config->getExportImplementor();

        $exporter = new $export_impl();

        if (!$exporter instanceof IExport) {
            throw new \InvalidArgumentException('The given exporter "' . $export_impl . '" must implement IExport.');
        }

        $exporter->setCommand($this);
        $exporter->setReport($this->report);
        $exporter->setParameters(new Parameters($this->config->get('export', array())));

        $exporter->run();
    }

    /**
     * Write the cachable settings from the run checks to a cache file for later reuse.
     *
     * @todo should cache only be written if all checks succeeded?
     *
     * @param boolean $run_was_successful whether or not the checks ran successfully
     */
    protected function writeCache($run_was_successful)
    {
        $disable_caching = $this->input->getOption('no-cache');
        if (!empty($disable_caching)) {
            return;
        }

        $cache_implementor = $this->config->getCacheImplementor();
        $cache = new $cache_implementor();

        if (!$cache instanceof ICache) {
            throw new \InvalidArgumentException(
                'The given cache class "' . $cache_implementor . '" does not implement ICache.'
            );
        }

        $cache_params = new Parameters($this->config->get('cache', array()));
        $cache->setParameters($cache_params);

        // TODO use something like getenv('ENVIRONAUT_CACHE_DIR')?
        $cache_location = $this->input->getOption('cache-location');
        if (!empty($cache_location)) {
            $cache->setLocation($cache_location);
        }

        $cache->addAll(
            $this->report->getCachableSettings() // gets only cachable settings from successful checks
        );

        if ($cache->save()) {
            $this->output->writeln(
                PHP_EOL . 'Writing cachable settings to "<comment>' . $cache->getLocation() .
                '</comment>" for subsequent runs...<info>ok</info>.' . PHP_EOL
            );
        } else {
            $this->output->writeln(
                PHP_EOL . 'Writing cachable settings to "<comment>' . $cache->getLocation() .
                '</comment>" for subsequent runs...<error>FAILED</error>.' . PHP_EOL
            );
        }
    }

    /**
     * Creates a cache instance and tries to load it according to command line argument or config.
     *
     * The cache is used in the runner to allow checks to access old values that may already have
     * been configured and thus improve their flow and e.g. not ask values again or just confirm them.
     *
     * @return IReadOnlyCache cache instance
     */
    protected function getLoadedCache()
    {
        if ($this->input->getOption('no-cache')) {
            $this->readonly_cache = new ReadOnlyCache();
            return $this->readonly_cache;
        }

        $cache_implementor = $this->config->getReadOnlyCacheImplementor();
        $cache = new $cache_implementor();

        if (!$cache instanceof IReadOnlyCache) {
            throw new \InvalidArgumentException(
                'The given cache class "' . $cache_implementor . '" does not implement IReadOnlyCache.'
            );
        }

        $cache_params = new Parameters($this->config->get('cache', array()));
        $cache_location = $this->input->getOption('cache-location');

        $this->readonly_cache = $cache;
        $this->readonly_cache->setParameters($cache_params);
        if (!empty($cache_location)) {
            if (is_readable($cache_location)) {
                $this->readonly_cache->setLocation($cache_location);
            } else {
                $this->output->writeln(
                    '<comment>Given cache location could not be read. ' .
                    'Using fallback from config or default location.</comment>'
                );
            }
        }

        $this->readonly_cache->load();

        $this->output->writeln(
            '<info>Loaded <comment>' . count($cache->getAll()) . '</comment> cached settings from:</info> ' .
            $cache->getLocation()
        );
        $this->output->writeln('');

        return $this->readonly_cache;
    }

    /**
     * Displays introductory text and some PHP configuration
     * and information (if --verbose was used as CLI option)
     */
    protected function displayIntro()
    {
        $input = $this->getInput();
        $output = $this->getOutput();

        $output->writeln('<info>Environment Check</info>');
        $output->writeln('=================' . PHP_EOL);

        if ($input->getOption('verbose')) {
            $output->writeln(
                '<info>PHP Version</info>: ' . PHP_VERSION . ' on ' . PHP_OS .
                ' (installed to ' . PHP_BINDIR . ')'
            );
            if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
                $output->writeln('<info>PHP Binary</info>: ' . PHP_BINARY);
            }
            $output->writeln(
                '<info>User owning this script</info>: ' . get_current_user() .
                ' (uid=' . getmyuid() . ')'
            );
            $output->writeln(
                '<info>User running this script</info>: uid=' . posix_getuid() .
                ' (effective uid=' . posix_geteuid() . ') gid=' . posix_getgid() .
                ' (effective gid=' . posix_getegid() . ')' . PHP_EOL
            );
            $output->writeln('<info>Loaded php.ini File</info>: ' . php_ini_loaded_file());
            $output->writeln('<info>Additionally Scanned Files</info>: ' . php_ini_scanned_files());
            $output->writeln('<info>PHP Include Path</info>: ' . ini_get('include_path') . PHP_EOL);

        }

        $output->writeln('<info>Reading configuration from</info>: ' . $this->config_path . PHP_EOL);
    }

    /**
     * Display some text after the main command executed.
     */
    protected function displayOutro()
    {
        $output = $this->getOutput();

        $output->writeln('');
        $output->writeln('<info>Done.</info>');
    }

    /**
     * Initializes the command just after the input has been validated.
     *
     * @param InputInterface $input An InputInterface instance
     * @param OutputInterface $output An OutputInterface instance
     */
    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        parent::initialize($input, $output); // necessary to register autoloader

        $config = $input->getOption('config');
        if (!empty($config)) {
            if (!is_readable($config)) {
                throw new \InvalidArgumentException('Config file path "' . $config . '" is not readable.');
            }

            $this->config_path = $config;

            if ($input->getOption('verbose')) {
                $output->writeln('<comment>Config file path specified: ' . $this->config_path . '</comment>');
            }
        } else {
            $this->config_path = $this->getCurrentWorkingDirectory();

            if ($input->getOption('verbose')) {
                $output->writeln(
                    '<comment>Config file path not specified, using "' . $this->config_path .
                    '" as default lookup location.</comment>'
                );
            }
        }

        $config_handler_implementor = $input->getOption('config-handler');
        if (empty($config_handler_implementor)) {
            $config_handler_implementor = 'Environaut\Config\ConfigHandler';
        }

        $this->config_handler = new $config_handler_implementor();
        $this->config_handler->addLocation($this->config_path);

        // TODO allow multiple locations for config option?
        // $config_reader->setLocations(array($this->config_path));
    }

    /**
     * @return IConfigHandler currently used config handler instance
     */
    public function getConfigHandler()
    {
        return $this->config_handler;
    }

    /**
     * @return string path to default config file location
     */
    public function getConfigPath()
    {
        return $this->config_path;
    }
}


<?php
namespace TRex\Cli;

/**
 * Class Executor
 * Execute commands
 *
 * @package TRex\Cli
 * @author Raphaël Lefebvre <raphael@raphaellefebvre.be>
 */
class Executor
{
    /**
     * reads the result of a command.
     *
     * @param string $command
     * @param string $eol
     * @return string
     */
    public function read($command, $eol = PHP_EOL)
    {
        exec($command, $output);
        return implode($eol, $output);
    }

    /**
     * Links the command with the current STD streams.
     *
     * @param string $command
     * @param array $streams
     * @param array $pipes
     * @param string $cwd
     * @param array $env
     * @param array $options
     * @return int
     */
    public function flush(
        $command,
        array $streams,
        array &$pipes = [],
        $cwd = null,
        array $env = null,
        array $options = []
    ) {
        $process = proc_open($command, $streams, $pipes, $cwd, $env, $options);
        if (!is_resource($process)) {
            throw new \RuntimeException('Error to open the process');
        }
        return proc_close($process);
    }
}


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

use Illuminate\Support\Facades\Log;
use Interpro\ImageFileLogic\Concept\CropConfig;
use Interpro\ImageFileLogic\Concept\Croper;
use Interpro\ImageFileLogic\Concept\Exception\ImageFileSystemException;
use Interpro\ImageFileLogic\Concept\ImageConfig;
use Interpro\ImageFileLogic\Concept\PathResolver;
use Interpro\Placeholder\Concept\PlaceholderAgent;
use Interpro\QuickStorage\Concept\Exception\CropNotFoundException;
use Interpro\QuickStorage\Concept\QSource;
use Interpro\QuickStorage\Laravel\Model\Cropitem;
use Intervention\Image\Facades\Image;

abstract class CropCommandHandler
{
    protected $qSource;
    protected $crop_config;
    protected $image_config;
    protected $croper;
    protected $phAgent;
    protected $path_prefix;
    protected $pathResolver;

    /**
     * Interpro\ImageFileLogic\Concept\QSource $qSource
     * Interpro\ImageFileLogic\Concept\Croper $croper
     * Interpro\ImageFileLogic\Concept\CropConfig $crop_config
     * Interpro\ImageFileLogic\Concept\ImageConfig $image_config
     *
     * @return void
     */
    public function __construct(QSource $qSource, Croper $croper, CropConfig $crop_config, ImageConfig $image_config, PlaceholderAgent $phAgent, PathResolver $pathResolver)
    {
        $this->qSource      = $qSource;
        $this->croper       = $croper;
        $this->crop_config  = $crop_config;
        $this->image_config = $image_config;
        $this->phAgent      = $phAgent;
        $this->pathResolver = $pathResolver;

        $config_path_prefix = config('imagefilelogic.crop_path_prefix');

        if($config_path_prefix){
            $this->path_prefix = $config_path_prefix;
        }else{
            $this->path_prefix = 'crops/';
        }
    }

    //Тех. долг неправильной архитектуре картинок-кропов костыльный метод получения расширения
    private function getExt($path_wo_ext)
    {
        foreach (glob($path_wo_ext.'*.*') as $file)
        {
            $inf = pathinfo($file);
            return $inf['extension'];
        }

        throw new ImageFileSystemException('Не найден оригинал картинки для пути '.$path_wo_ext.'!');
    }

    public function refreshBlock($block_name)
    {
        $crop_models = $this->qSource->cropQueryForBlock($block_name);

        $this->cropBlock($crop_models);
    }

    public function refreshGroupItem($block_name, $group_name, $group_id)
    {
        $crop_models = $this->qSource->oneCropQueryForGroup($block_name, $group_name, $group_id);

        $this->cropGroupItems($crop_models);
    }

    public function refreshGroup($block_name, $group_name)
    {
        $crop_models = $this->qSource->cropQueryForGroup($block_name, $group_name);

        $this->cropGroupItems($crop_models);
    }

    private function cropBlock($crop_models)
    {
        foreach($crop_models as $item)
        {
//            $image_name = $item['block_name'].'_'.$item['image_name'];
//            $file_name = $image_name.'_0';
//            $target_name = $file_name.'_'.$item['target_sufix'];
//            $result_name = $file_name.'_'.$item['name'];
//
//            $color = $this->crop_config->getColor($image_name, $item['name']);
//
//            $this->croper->crop(
//                $file_name,
//                $target_name,
//                $result_name,
//                $item['target_x1'],
//                $item['target_y1'],
//                $item['target_x2'],
//                $item['target_y2'],
//                $color
//            );
//
            $cropModel = Cropitem::find($item['id']);
            $cropModel->cache_index++;
            $cropModel->save();
        }
    }

    private function cropGroupItems($crop_models)
    {
        foreach($crop_models as $item)
        {
//            $image_name = $item['group_name'].'_'.$item['image_name'];
//            $file_name = $image_name.'_'.$item['group_id'];
//            $target_name = $file_name.'_'.$item['target_sufix'];
//            $result_name = $file_name.'_'.$item['name'];
//
//            $color = $this->crop_config->getColor($image_name, $item['name']);
//
//            $this->croper->crop(
//                $file_name,
//                $target_name,
//                $result_name,
//                $item['target_x1'],
//                $item['target_y1'],
//                $item['target_x2'],
//                $item['target_y2'],
//                $color
//            );
//
            $cropModel = Cropitem::find($item['id']);
            $cropModel->cache_index++;
            $cropModel->save();
        }
    }

    public function initDBForBlock($block_name)
    {
        $config = $this->crop_config->getConfigAll();

        $images_collection = $this->qSource->imageQueryForBlock($block_name);

        foreach($images_collection as $image_fields)
        {
            $image_name = $image_fields['name'];

            $image_key  = $block_name.'_'.$image_name;
            $image_id   = $image_fields['id'];

            if(array_key_exists($image_key, $config))
            {
                $crops = &$config[$image_key];

                foreach($crops as $crop_name => $params)
                {
                    $crop = Cropitem::where('block_name', $block_name)->
                        where('name', $crop_name)->
                        where('image_name', $image_name)->
                        where('image_id', $image_id);

                    if(!$crop)
                    {
                        $man_width = $this->image_config->getWidth($image_key, $params['man']);
                        $man_height = $this->image_config->getHeight($image_key, $params['man']);

                        $target_width = $this->image_config->getWidth($image_key, $params['target']);
                        $target_height = $this->image_config->getHeight($image_key, $params['target']);

                        $result_width = floor($target_width*($params['width']/$man_width));
                        $result_height = floor($target_height*($params['height']/$man_height));

                        $crop = Cropitem::firstOrNew(['block_name' => $block_name, 'name' => $crop_name, 'image_name' => $image_name, 'image_id' => $image_id]);

                        $crop->link         = $this->phAgent->getLink($params['width'], $params['height'], $color = '#808080');
                        $crop->man_sufix    = $params['man'];
                        $crop->target_sufix = $params['target'];
                        $crop->cache_index  = 0;
                        $crop->man_x1       = 0;
                        $crop->man_y1       = 0;
                        $crop->man_x2       = $params['width'];
                        $crop->man_y2       = $params['height'];
                        $crop->target_x1    = 0;
                        $crop->target_y1    = 0;
                        $crop->target_x2    = $result_width;
                        $crop->target_y2    = $result_height;

                        $crop->save();
                    }
                }
            }
        }
    }

    public function initDBForGroup($block_name, $group_name)
    {
        $config = $this->crop_config->getConfigAll();

        $images_collection = $this->qSource->imageQueryForGroup($block_name, $group_name);

        foreach($images_collection as $image_fields)
        {
            $image_name = $image_fields['name'];
            $group_id = $image_fields['group_id'];
            $image_id   = $image_fields['id'];

            $image_key  = $group_name.'_'.$image_name;

            if(array_key_exists($image_key, $config))
            {
                $crops = &$config[$image_key];

                foreach($crops as $crop_name => $params)
                {
                    $crop = Cropitem::where('block_name', $block_name)->
                        where('group_name', $group_name)->
                        where('group_id', $group_id)->
                        where('name', $crop_name)->
                        where('image_name', $image_name)->
                        where('image_id', $image_id);

                    if(!$crop)
                    {
                        $man_width = $this->image_config->getWidth($image_key, $params['man']);
                        $man_height = $this->image_config->getHeight($image_key, $params['man']);

                        $target_width = $this->image_config->getWidth($image_key, $params['target']);
                        $target_height = $this->image_config->getHeight($image_key, $params['target']);

                        $result_width = floor($target_width*($params['width']/$man_width));
                        $result_height = floor($target_height*($params['height']/$man_height));

                        $crop = Cropitem::firstOrNew(['block_name' => $block_name, 'group_name' => $group_name, 'group_id' => $group_id, 'name' => $crop_name, 'image_name' => $image_name]);

                        $crop->image_id     = $image_id;
                        $crop->link         = $this->phAgent->getLink($params['width'], $params['height'], $color = '#808080');
                        $crop->man_sufix    = $params['man'];
                        $crop->target_sufix = $params['target'];
                        $crop->cache_index  = 0;
                        $crop->man_x1       = 0;
                        $crop->man_y1       = 0;
                        $crop->man_x2       = $params['width'];
                        $crop->man_y2       = $params['height'];
                        $crop->target_x1    = 0;
                        $crop->target_y1    = 0;
                        $crop->target_x2    = $result_width;
                        $crop->target_y2    = $result_height;

                        $crop->save();
                    }
                }
            }
        }
    }

    public function initDBForGroupItem($block_name, $group_name, $group_id)
    {
        $config = $this->crop_config->getConfigAll();

        $images_collection = $this->qSource->oneImageQueryForGroup($block_name, $group_name, $group_id);

        foreach($images_collection as $image_fields)
        {
            $image_name = $image_fields['name'];
            $image_id   = $image_fields['id'];

            $image_key  = $group_name.'_'.$image_name;

            if(array_key_exists($image_key, $config))
            {
                $crops = &$config[$image_key];

                foreach($crops as $crop_name => $params)
                {
                    $crop = Cropitem::where('block_name', $block_name)->
                        where('group_name', $group_name)->
                        where('group_id', $group_id)->
                        where('name', $crop_name)->
                        where('image_name', $image_name)->
                        where('image_id', $image_id)->first();

                    if(!$crop)
                    {
                        $man_width = $this->image_config->getWidth($image_key, $params['man']);
                        $man_height = $this->image_config->getHeight($image_key, $params['man']);

                        $target_width = $this->image_config->getWidth($image_key, $params['target']);
                        $target_height = $this->image_config->getHeight($image_key, $params['target']);

                        $result_width = floor($target_width*($params['width']/$man_width));
                        $result_height = floor($target_height*($params['height']/$man_height));

                        $crop = Cropitem::firstOrNew(['block_name' => $block_name, 'group_name' => $group_name, 'group_id' => $group_id, 'name' => $crop_name, 'image_name' => $image_name]);

                        $crop->image_id     = $image_id;
                        $crop->link         = $this->phAgent->getLink($params['width'], $params['height'], $color = '#808080');
                        $crop->man_sufix    = $params['man'];
                        $crop->target_sufix = $params['target'];
                        $crop->cache_index  = 0;
                        $crop->man_x1       = 0;
                        $crop->man_y1       = 0;
                        $crop->man_x2       = $params['width'];
                        $crop->man_y2       = $params['height'];
                        $crop->target_x1    = 0;
                        $crop->target_y1    = 0;
                        $crop->target_x2    = $result_width;
                        $crop->target_y2    = $result_height;

                        $crop->save();
                    }
                }
            }
        }

    }

    public function updateDBForBlock($block_name)
    {
        $images_collection = $this->qSource->imageQueryForBlock($block_name);

        $crop_dir = $this->pathResolver->getImageCropDir();

        foreach($images_collection as $image_fields)
        {
            $image_name = $image_fields['name'];

            $image_key  = $block_name.'_'.$image_name;
            $image_id   = $image_fields['id'];

            $crops = $this->crop_config->getConfig($image_key);

            foreach($crops as $crop_name => $params)
            {
                $man_name = $this->crop_config->getMan($image_key, $crop_name);
                $target_name = $this->crop_config->getTarget($image_key, $crop_name);

                $crop = Cropitem::where('block_name',$block_name)->
                    where('group_id', 0)->
                    where('name', $crop_name)->
                    where('image_name', $image_name)->first();

                $crop_half_path = $crop_dir.'/'.$image_key.'_0_'.$crop_name;

                $crop_file = $this->phAgent->getLink($params['width'], $params['height'], $color = '#808080');

                foreach (glob($crop_half_path.'*.*') as $file)
                {
                    $inf = pathinfo($file);
                    $ext = $inf['extension'];

                    $crop_file = 'crops/'.$image_key.'_0_'.$crop_name.'.'.$ext;
                }

                if(!$crop)
                {
                    $crop = new Cropitem();
                    $crop->name = $crop_name;
                    $crop->block_name = $block_name;
                    $crop->image_name = $image_name;
                    $crop->group_id = 0;
                    $crop->cache_index = 0;
                }

                $crop->image_id = $image_id;
                $crop->man_sufix = $man_name;
                $crop->target_sufix = $target_name;
                $crop->cache_index++;
                $crop->image_id    = $image_id;
                $crop->link        = $crop_file;

                $crop->save();
            }
        }
    }

    public function updateDBForGroupItem($block_name, $group_name, $group_id)
    {
        $image_dir = $this->pathResolver->getImageDir();

        //На середину - по умолчанию
        $images_collection = $this->qSource->oneImageQueryForGroup($block_name, $group_name, $group_id);

        $crop_dir = $this->pathResolver->getImageCropDir();

        foreach($images_collection as $image_fields)
        {
            $image_name = $image_fields['name'];

            $image_key  = $group_name.'_'.$image_name;
            $image_id   = $image_fields['id'];

            $crops = $this->crop_config->getConfig($image_key);

            foreach($crops as $crop_name => $params)
            {
                $man_name = $this->crop_config->getMan($image_key, $crop_name);
                $target_name = $this->crop_config->getTarget($image_key, $crop_name);

                $crop = Cropitem::where('block_name',$block_name)->
                    where('group_name', $group_name)->
                    where('group_id', $group_id)->
                    where('name', $crop_name)->
                    where('image_name', $image_name)->first();

                $crop_half_path = $crop_dir.'/'.$image_key.'_'.$group_id.'_'.$crop_name;

                $crop_file = $this->phAgent->getLink($params['width'], $params['height'], $color = '#808080');

                foreach (glob($crop_half_path.'*.*') as $file)
                {
                    $inf = pathinfo($file);
                    $ext = $inf['extension'];

                    $crop_file = 'crops/'.$image_key.'_'.$group_id.'_'.$crop_name.'.'.$ext;
                }

                if(!$crop)
                {
                    $crop = new Cropitem();
                    $crop->block_name = $block_name;
                    $crop->group_name = $group_name;
                    $crop->group_id   = $group_id;
                    $crop->name       = $crop_name;
                    $crop->image_name = $image_name;
                    $crop->cache_index = 0;
                }

                $crop->image_id = $image_id;
                $crop->man_sufix = $man_name;
                $crop->target_sufix = $target_name;
                $crop->cache_index++;
                $crop->link        = $crop_file;

                $crop->save();
            }
        }
    }

}


<?php

namespace Interpro\Entrance\Agents;

use Interpro\Core\Contracts\Mediator\UpdateMediator;
use Interpro\Core\Contracts\Taxonomy\Taxonomy;
use Interpro\Core\Ref\ARef;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\Entrance\Contracts\CommandAgent\UpdateAgent as UpdateAgentInterface;
use Interpro\Entrance\Exception\EntranceException;

class UpdateAgent implements UpdateAgentInterface
{
    private $updateMediator;
    private $taxonomy;

    public function __construct(
        UpdateMediator $updateMediator,
        Taxonomy $taxonomy
    )
    {
        $this->updateMediator = $updateMediator;
        $this->taxonomy       = $taxonomy;
    }

    /**
     * @param string $type_name
     * @param int $id
     * @param array $values
     *
     * @return void
     */
    public function update($type_name, $id = 0, array $values = [])
    {
        if(!is_string($type_name))
        {
            throw new EntranceException('Название А-типа) должно быть задано строкой!');
        }

        if(!is_int($id))
        {
            throw new EntranceException('Id А-типа должно быть задано целым числом!');
        }

        $type = $this->taxonomy->getType($type_name);

        $typeMode = $type->getMode();

        if($typeMode !== TypeMode::MODE_A)
        {
            throw new EntranceException('Агент удаления может удалять только тип (A) уровня, передан тип:'.$type->getName().'('.$typeMode.')!');
        }

        $family = $type->getFamily();

        $updator = $this->updateMediator->getAUpdateExecutor($family);

        $ref = new ARef($type, $id);

        $updator->update($ref, $values);
    }
}


<?php

/**
 * Instaphp
 *
 * Copyright (c) 2011 randy sesser <randy@instaphp.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author randy sesser <randy@instaphp.com>
 * @copyright 2011, randy sesser
 * @license http://www.opensource.org/licenses/mit-license The MIT License
 * @package Instaphp
 * @filesource
 */

namespace Instaphp\Instagram;

use Instaphp\Request;
use Instaphp\Response;

/**
 * Locations class
 * Handles all Location based API requests
 * @package Instaphp
 * @version 1.0
 * @author randy sesser <randy@instaphp.com>
 */
class Locations extends InstagramBase
{

    public function __construct($token = null, $config = array())
    {
        parent::__construct($token, $config);
        $this->api_path = '/locations';
    }

    /**
     * Gets information about a particular location
     * @access public
     * @param int $location_id A location ID
     * @param string $token An access token
     * @return Response
     */
    public function Info($location_id)
    {
        return $this->Get($this->buildUrl($location_id));
    }

    /**
     * Get recent media associated with a particular media
     * @access public
     * @param int $location_id A location ID
     * @param string $token An access token
     * @param Array $params An associative array of key/value pairs to pass to the API
     * @return Response
     */
    public function Recent($location_id, Array $params = array())
    {
		if (!empty($params))
			$this->AddParams($params);

        return $this->Get($this->buildUrl($location_id . '/media/recent'));
    }

    /**
     * Search for media by latitude/longitude
     * @access public
     * @param string $token An access token
     * @param Array $params An associative array of key/value pairs to pass to the API
     * @return Response
     */
    public function Search(Array $params = array())
    {
        if (isset($params['lat'])) {
            if (!isset($params['lng']) || empty($params['lng']))
                trigger_error('Longitude and Latitude are mutually inclusive in ' . __METHOD__, E_USER_ERROR);
        }
        if (isset($params['lng'])) {
            if (!isset($params['lat']) || empty($params['lat']))
                trigger_error('Longitude and Latitude are mutually inclusive in ' . __METHOD__, E_USER_ERROR);
        }

		if (!empty($params))
			$this->AddParams($params);

        return $this->Get($this->buildUrl('search'));
    }

}


<?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: DataRecord.php 4086 2011-05-03 06:00:35Z rockys $
 */

namespace Openbizx\Data;

/**
 * DataRecord class  is the wrapper class of record array.
 * It is recommmended to be used in data update and deletion.
 *
 * @package openbiz.bin.data
 * @author Rocky Swen
 * @copyright Copyright (c) 2007-2009
 * @access public
 **/
class DataRecord implements \Iterator, \ArrayAccess
{
    /**
     * Record in array format
     *
     * @var array
     */
    protected $varValue = array();

    /**
     * Old record in array format
     *
     * @var array
     */
    protected $oldVarValue = array();

    /**
     * Reference of {@link BizDataObj}
     *
     * @var BizDataObj
     */
    protected $bizDataObj = null;

    /**
     * Initialize DataRecord with record array.
     * Creat a new record - new {@link DataRecord(null, $bizObj)}
     * Get a current record - new {@link DataRecord($recArr, $bizObj)}
     *
     * @param array $recArray record array.
     * @param BizDataObj $bizObj BizDataObj instance
     * @return void
     * @todo fix for non array and non DataRecord condition
     */
    public function __construct($recArray, $bizObj)
    {
        //echo __METHOD__ . '-' . __LINE__ . 'B EGIN ==========
';
        if ($recArray != null) {
            if (is_array($recArray)) {
                $this->varValue = $recArray;
                $this->oldVarValue = $recArray;
            } else if (is_a($recArray, "Openbizx\Data\DataRecord")) {
                $this->varValue = $recArray->toArray();
                $this->oldVarValue = $this->varValue;
            } else {
                // please fix here
            }
        } else {
            $this->varValue = $bizObj->newRecord();
        }
        $this->bizDataObj = $bizObj;
    }

    /**
     * Get item value of array
     *
     * @param mixed $key
     * @return mixed
     */
    public function get($key)
    {
        return isset($this->varValue[$key]) ? $this->varValue[$key] : null;
    }

    public function getOldValue($key)
    {
    	return isset($this->oldVarValue[$key]) ? $this->oldVarValue[$key] : null;
    }

	public function getDataObj()
    {
    	return $this->bizDataObj;
    }
    /**
     * Set item value of array
     *
     * @param mixed $key
     * @param mixed $val
     */
    public function set($key, $val)
    {
        $this->varValue[$key] = $val;
    }

    // Iterator methods BEGIN---------

    /**
     * Rewind, Send pointer to start of list
     *
     * @return void
     */
    public function rewind()
    {
        reset($this->varValue);
    }

    /**
     * Return element at current pointer position
     *
     * @return mixed
     */
    public function current()
    {
        return current($this->varValue);
    }

    /**
     * Return current key (i.e., pointer value)
     *
     * @return mixed
     */
    public function key()
    {
        return key($this->varValue);
    }

    /**
     * Return element at current pointer and advance pointer
     *
     * @return mixed
     */
    public function next()
    {
        return next($this->varValue);
    }

    /**
     * Confirm that there is an element at the current pointer position
     *
     * @return boolean
     */
    public function valid()
    {
        return $this->current() !== false;
    }

    // Iterator method END

    // ArrayAccess methods Begin
    //========================================

    /**
     * Check is offset value (by key) exist?
     *
     * @param mixed $key
     * @return mixed
     */
    public function offsetExists($key)
    {
        return isset($this->varValue[$key]);
    }

    /**
     * Get value of offset (by key)
     *
     * @param mixed $key
     * @return mixed
     */
    public function offsetGet($key)
    {
        return $this->get($key);
    }

    /**
     * Set value of offset by key
     *
     * @param mixed $key
     * @param mixed $value
     */
    public function offsetSet($key, $value)
    {
        $this->set($key, $value);
    }

    /**
     * Unset element by key
     *
     * @param mixed $key key of element
     */
    public function offsetUnset($key)
    {
        unset($this->varValue[$key]);
    }

    /**
     * Get field value with property format
     *

     *   $value = $obj->get($fieldName); => $value = $obj->fieldName;
     *

     *
     * @param string $fieldName name of a field
     * @return mixed value of the field
     */
    public function __get($fieldName)
    {
        return $this->get($fieldName);
    }

    /**
     * Set field value with property format
     *

     *   $obj->set($fieldName, $value); => $obj->fieldName = $value;
     *

     *
     * @param string $fieldName name of a field
     * @param mixed value of the field
     * @return avoid
     */
    public function __set($fieldName, $value)
    {
        $this->set($fieldName, $value);
    }

    /**
     * Save record. This function calls {@link BizDataObj::updateRecord} method internally
     *
     * @return boolean true for success
     */
    public function save()
    {
        if (count($this->oldVarValue) > 0) {
            $ok = $this->bizDataObj->updateRecord($this->varValue, $this->oldVarValue);
        } else {
            $ok = $this->bizDataObj->insertRecord($this->varValue);
        }

        // repopulate current record with bizdataobj activerecord
        if ($ok) {
            $this->varValue = $this->bizDataObj->getActiveRecord();
            $this->oldVarValue = $this->varValue;
        }
        return $ok;
    }

    /**
     * Delete record. This function calls {@link BizDataObj::deleteRecord} method internally
     *
     * @return boolean true for success
     */
    public function delete()
    {
        return $this->bizDataObj->deleteRecord($this->varValue);
    }

    /**
     * Get error message
     *
     * @return string error message
     */
    public function getError()
    {
        return $this->bizDataObj->getErrorMessage();
    }

    /**
     * Return record in array
     *
     * @return array record array
     */
    public function toArray()
    {
        return $this->varValue;
    }

    /**
     * Get reference object with given object name
     *
     * @param string $objName name of the object reference
     * @return obejct the instance of reference object
     */
    public function getRefObject($objName)
    {
        return $this->bizDataObj->getRefObject($objName);
    }

}
?>


<?php
/**
 * InputForm class
 *
 * @package
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */

namespace Openbizx\View;

use Openbizx\View\BaseForm;

 /*
  * protected methods: validateForm, readInputRecord, readInputs
  */
class InputForm extends BaseForm
{
	//list of method that can directly from browser
	protected $directMethodList = array('saverecord','switchform');

	public $recordId;
	public $activeRecord;

    /**
     * Read user input data from UI
     *
     * @return array - record array
     */
    protected function readInputRecord()
    {
        $recArr = array();
        foreach ($this->dataPanel as $element)
        {
            $value = Openbizx::$app->getClientProxy()->getFormInputs($element->objectName);
            if ($value ===null && (
            	   !is_a($element,"FileUploader")
            	&& !is_subclass_of($element,"FileUploader")
            	&& !is_a($element,"Checkbox")
            	&& !is_a($element,"FormElement")
            	)){
            	continue;
            }
            $element->setValue($value);
            $this->formInputs[$element->objectName] = $value;
            $value = $element->getValue();
            if ( $element->fieldName)
                $recArr[$element->fieldName] = $value;
        }
		$this->activeRecord = $recArr;
		return $recArr;
    }

    /**
     * Read inputs
     *
     * @return array array of input
     */
    protected function readInputs()
    {
        $inputArr = array();
        foreach ($this->dataPanel as $element)
        {
            $value = Openbizx::$app->getClientProxy()->getFormInputs($element->objectName);
            $element->setValue($value);
            $inputArr[$element->objectName] = $value;
        }

        foreach ($this->searchPanel as $element)
        {
            $value = Openbizx::$app->getClientProxy()->getFormInputs($element->objectName);
            $element->setValue($value);
            $inputArr[$element->objectName] = $value;
        }
        return $inputArr;
    }

	/**
     * Validate input on EasyForm level
     * default form validation do nothing.
     * developers need to override this method to implement their logic
     *
     * @return boolean
     */
    protected function validateForm($cleanError = true)
    {
        if($cleanError == true)
        {
            $this->validateErrors = array();
        }
        $this->dataPanel->rewind();
        while($this->dataPanel->valid())
        {
            /* @var $element Element */
            $element = $this->dataPanel->current();
            if($element->label)
            {
                $elementName = $element->label;
            }
            else
            {
                $elementName = $element->text;
            }
            if ($element->checkRequired() === true &&
                    ($element->value==null || $element->value == ""))
            {
                $errorMessage = $this->getMessage("FORM_ELEMENT_REQUIRED",array($elementName));
                $this->validateErrors[$element->objectName] = $errorMessage;
                //return false;
            }
            elseif ($element->value!==null && $element->Validate() == false)
            {
                $validateService = Openbizx::getService(VALIDATE_SERVICE);
                $errorMessage = $this->getMessage("FORM_ELEMENT_INVALID_INPUT",array($elementName,$value,$element->validator));
                if ($errorMessage == false)
                { //Couldn't get a clear error message so let's try this
                    $errorMessage = $validateService->getErrorMessage($element->validator, $elementName);
                }
                $this->validateErrors[$element->objectName] = $errorMessage;
                //return false;
            }
            $this->dataPanel->next() ;
        }
        if (count($this->validateErrors) > 0)
        {
            throw new Openbizx\Validation\Exception($this->validateErrors);
            return false;
        }
        return true;
    }
}
?>


<?php

namespace Interpro\QuickStorage\Laravel\Specification;

use Interpro\QuickStorage\Concept\Item\GroupItem;

class GroupSpecificationEq extends GroupSpecification
{
    private $val;

    public function __construct($group_name, $field_name, $val)
    {
        parent::__construct($group_name, $field_name);

        $this->val = $val;
    }

    /**
     * Checks if given item meets all criteria
     *
     * @param GroupItem $item
     *
     * @return bool
     */
    public function isSatisfiedBy(GroupItem $item)
    {
        $field_name = $this->field_name;

        if(in_array($item->$field_name, $this->val)){
            return ($item->$field_name == $this->val);
        }else{
            return ($item->$field_name == $this->val);
        }
    }

    /**
     * Checks scope
     *
     * @param $query
     *
     * @return mixed
     */
    public function asScope($query)
    {
        if(is_array($this->val)){
            return $query->whereIn($this->getFieldName(), $this->val);
        }else{
            return $query->where($this->getFieldName(), '=', $this->val);
        }
    }

}


<?php
namespace D4rk4ng3l\Oxid\CodeGenerator\Php;

use D4rk4ng3l\Oxid\CodeGenerator\GeneratorInterface;

/**
 * Class PhpClass
 *
 * @package D4rk4ng3l\Oxid\CodeGenerator\Php
 */
class PhpClass implements GeneratorInterface
{

    /**
     * @var bool
     */
    private $final = false;

    /**
     * @var bool
     */
    private $abstract = false;

    /**
     * @var string
     */
    private $namespace = "";

    /**
     * @var array
     */
    private $phpUse = array();

    /**
     * @var string
     */
    private $name = "";

    /**
     * @var string
     */
    private $extension = "";

    /**
     * @var array
     */
    private $implementations = array();

    /**
     * @var Constant[]
     */
    private $constants = array();

    /**
     * @var Property[]
     */
    private $properties = array();

    /**
     * @var Method[]
     */
    private $methods = array();

    /**
     * @param string $name
     * @param PhpUse $phpUse
     */
    public function __construct($name, PhpUse $phpUse = null)
    {
        $this->name = (string) $name;
        if (null === $phpUse) {
            $phpUse = new PhpUse();
        }

        $this->phpUse = $phpUse;
    }

    /**
     * @param $className
     *
     * @return $this
     */
    public function addImplementation($className)
    {
        $this->implementations[$className] = $this->phpUse->getClassAlias($className);

        return $this;
    }

    /**
     * @param $extension
     *
     * @return $this
     */
    public function setExtension($extension)
    {
        $this->extension = $this->phpUse->getClassAlias($extension);

        return $this;
    }

    /**
     * @param Constant $constant
     *
     * @return $this
     */
    public function addConstant(Constant $constant)
    {
        $this->constants[] = $constant;

        return $this;
    }

    /**
     * @param Property $property
     *
     * @return $this
     */
    public function addProperty(Property $property)
    {
        $this->properties[] = $property;

        return $this;
    }

    /**
     * @param Method $method
     *
     * @return $this
     */
    public function addMethod(Method $method)
    {
        $this->methods[$method->getName()] = $method;

        return $this;
    }

    /**
     * @return string
     */
    public function generate()
    {
        if ($this->final && $this->abstract) {
            throw new \InvalidArgumentException("A class can not be 'abstract' and 'final' together!");
        }

        $code = "class {$this->name}";

        if (0 < strlen($this->extension)) {
            $code .= " extends {$this->extension}";
        }

        if (0 < count($this->implementations)) {
            $code .= " implements " . implode($this->implementations);
        }

        $code .= "\n{\n";

        foreach ($this->constants as $constant) {
            $code .= $constant->generate();
        }

        foreach ($this->properties as $property) {
            $code .= $property->generate();
        }

        foreach ($this->methods as $method) {
            $code .= $method->generate();
        }

        $code .= "\n}\n";

        return $code;
    }
}


<?php
/**
 * OAuth 2.0 Client credentials grant
 *
 */

namespace OAuth2\Server\Grant;

use OAuth2\Server\Entity\AccessTokenEntity;
use OAuth2\Server\Entity\ClientEntity;
use OAuth2\Server\Entity\SessionEntity;
use OAuth2\Server\Exception;
use OAuth2\Server\Util\SecureKey;

/**
 * Client credentials grant class
 */
class ClientCredentialsGrant extends AbstractGrant
{
    /**
     * Grant identifier
     *
     * @var string
     */
    protected $identifier = 'client_credentials';

    /**
     * Response type
     *
     * @var string
     */
    protected $responseType = null;

    /**
     * AuthServer instance
     *
     * @var \OAuth2\Server\AuthorizationServer
     */
    protected $server = null;

    /**
     * Access token expires in override
     *
     * @var int
     */
    protected $accessTokenTTL = null;

    /**
     * Complete the client credentials grant
     *
     * @return array
     *
     * @throws
     */
    public function completeFlow(ClientEntity $client)
    {
        // Validate any scopes that are in the request
        $scopeParam = $this->server->getRequestHandler()->getParam('scope');
        $scopes = $this->validateScopes($scopeParam, $client);

        // Create a new session
        $session = new SessionEntity($this->server);
        $session->setOwner('client', $client->getId());
        $session->associateClient($client);

        // Generate an access token
        $accessToken = new AccessTokenEntity($this->server);
        $accessToken->setId();
        $accessToken->setExpireTime($this->getAccessTokenTTL() + time());

        // Associate scopes with the session and access token
        foreach ($scopes as $scope) {
            $session->associateScope($scope);
        }

        foreach ($session->getScopes() as $scope) {
            $accessToken->associateScope($scope);
        }

        // Save everything
        $session->save();
        $accessToken->setSession($session);
        $accessToken->save();

        $this->server->getTokenType()->setSession($session);
        $this->server->getTokenType()->setParam('access_token', $accessToken->getId());
        $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());

        return $this->server->getTokenType()->generateResponse();
    }
}


<?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\Response;

/**
 * Template class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class Template
{
    const FILTER_RAW    = 0;
    const FILTER_ESCAPE = 1;
    const FILTER_XSS    = 2;

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

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

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

    /**
     * @var array
     */
    protected $data;

    /**
     * @var boolean
     */
    protected $template_filter;

    /**
     * @var array
     */
    protected $filters;

    /**
     * @var Response
     */
    protected $response;

    /**
     * @param string $template_path
     * @param string $template
     * @param array $data
     * @param integer $template_filter
     * @param array $filters
     * @param Response $response
     * @param string $template_extension
     */
    //TODO: Page layout instead of subtemplates (or together)
    public function __construct($template_path, $template, $data = [], $template_filter = self::FILTER_ESCAPE, array $filters = [], Response $response = null, $template_extension = 'tpl')
    {
        $this->template_path      = $template_path;
        $this->template_extension = $template_extension;
        $this->template           = $template;
        $this->template_filter    = $template_filter;
        $this->response           = $response;
        $this->filters            = $filters;

        $this->setData($data);
    }

    /**
     * @param array|string $name
     * @param mixed $value
     * @param integer $filter
     *
     * @return $this
     *
     * @throws \InvalidArgumentException
     */
    //TODO: make filters is a preffixes in the $data_name
    public function setData($name, $value = null, $filter = null)
    {
        if ($name && !is_null($value)) {
            $this->data[$name] = $value;
            if (!is_null($filter)) {
                $this->filters[$name] = $filter;
            }
        } elseif (is_array($name)) {
            $this->data = $name;
        } else {
            throw new \InvalidArgumentException('Invalid argument for set template data');
        }
        return $this;
    }

    /**
     * @return mixed
     *
     * @throws \OutOfBoundsException
     */
    public function getData()
    {
        $data = [];
        foreach ($this->data as $name => $data_value) {
            $filter = isset($this->filters[$name]) ? $this->filters[$name] : $this->template_filter;
            switch ($filter) {
                case 0:
                    $data[$name] = $data_value;
                    break;
                case 1:
                    $data[$name] = self::escape($data_value);
                    break;
                case 2:
                    $data[$name] = $this->cleanXSS($data_value);
            }
        }
        return $data;
    }

    /**
     * @param string $name
     * @param mixed $value
     * @param integer $filter
     *
     * @throws \InvalidArgumentException
     *
     * @return $this
     */
    public function bindData($name, &$value, $filter = null)
    {
        $this->data[$name] = $value;
        if (!is_null($filter)) {
            $this->filters[$name] = $filter;
        }
        if (!$name && !$value) {
            throw new \InvalidArgumentException('Invalid argument for bind template data');
        }
        return $this;
    }

    /**
     * @param string $template
     */
    public function subTemplate($template)
    {
        $subtemplate_instance = new static($this->template_path, $template, $this->data, $this->template_filter, $this->filters, $this->response, $this->template_extension);
        return $subtemplate_instance->renderTemplate();
    }

    /**
     * @param bool $compress
     *
     * @return Response
     */
    public function render($compress = false)
    {
        if (is_null($this->response)) {
            $this->response = new Response();
        }

        $content = $this->renderTemplate();
        if ($compress) {
            $content = $this->compressHTML($content);
        }

        $this->response->setContent($content);
        return $this->response;
    }

    /**
     * @return string
     * @throws \RuntimeException
     * @throws \Exception
     */
    protected function renderTemplate()
    {
        extract($this->getData(), EXTR_REFS);

        $template_path = $this->template_path . $this->template . '.' . $this->template_extension;
        if (!file_exists($template_path)) {
            throw new \RuntimeException('Template file: ' . $template_path . ' doesn`t exist.');
        }

        ob_start();

        try {
            include_once $template_path;
        } catch (\Exception $exception) {
            ob_end_clean();
            throw $exception;
        }
        return ob_get_clean();
    }

    /**
     * @param string $content
     *
     * @return string
     */
    protected function compressHTML($content)
    {
        $content_parts = preg_split(
            '#(</?pre[^>]*>)|(</?script[^>]*>)|(</?style[^>]*>)|(</?textarea[^>]*>)#i',
            $content,
            -1,
            PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
        );

        $content = '';
        $preserve_next = false;
        $optimize_next = false;

        foreach ($content_parts as $part) {
            if (strncasecmp($part, '<pre', 4) === 0 || strncasecmp($part, '<textarea', 9) === 0) {
                $preserve_next = true;
            } elseif (strncasecmp($part, '


<?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 © 2005-2009, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: BizField.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Data;

use Openbizx\Openbizx;
use Openbizx\Core\Expression;
use Openbizx\Object\MetaObject;
/**
 * Class BizField is the class of a logic field which mapps to a table column
 *
 * @package openbiz.bin.data
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 * */
class BizField extends MetaObject
{

    /**
     * Name of {@link BizDataObj}
     *
     * @var string
     */
    public $bizDataObjName;
    public $index;
    public $join = null;
    public $column = null;
    public $aliasName = null;
    public $fieldIndex;

    /**
     * Type of field in string
     *
     * @var string
     */
    public $type = null;

    /**
     * Format of field
     *
     * @var string
     */
    public $format = null;

    /**
     * Length of field
     *
     * @var number
     */
    public $length = null;
    public $valueExpression = null; // support expression

    /**
     * Is field required?
     *
     * @var mixed
     */
    public $required = null;       // support expression
    public $validator = null;      // support expression
    public $sqlExpression = null;  // support expression
    public $encrypted = "N";
    public $clearText = null;

    /**
     * Default value of field
     *
     * @var mixed
     */
    public $defaultValue = null;
    public $valueOnCreate = null;
    public $valueOnUpdate = null;

    /**
     * Is on Audit?
     *
     * @var boolean
     */
    public $onAudit = false;

    /**
     * The real value of the field, not from metadata
     *
     * @var mixed
     */
    public $value = null;

    public $oldValue = null; // the old value of the field
    public $ignoreInQuery = false;
    protected $_prevValue, $_getValueCache;

    /**
     * Initialize BizField with xml array
     *
     * @param array $xmlArr xml array
     * @param BizDataObj $bizObj BizDataObj instance
     * @return void
     */
    function __construct(&$xmlArr, $bizObj)
    {
        $this->objectName = isset($xmlArr["ATTRIBUTES"]["NAME"]) ? $xmlArr["ATTRIBUTES"]["NAME"] : null;
        $this->bizDataObjName = $bizObj->objectName;
        $this->package = $bizObj->package;
        $this->join = isset($xmlArr["ATTRIBUTES"]["JOIN"]) ? $xmlArr["ATTRIBUTES"]["JOIN"] : null;
        $this->column = isset($xmlArr["ATTRIBUTES"]["COLUMN"]) ? $xmlArr["ATTRIBUTES"]["COLUMN"] : null;
        $this->aliasName = isset($xmlArr["ATTRIBUTES"]["ALIAS"]) ? $xmlArr["ATTRIBUTES"]["ALIAS"] : null;
        $this->valueExpression = isset($xmlArr["ATTRIBUTES"]["VALUE"]) ? $xmlArr["ATTRIBUTES"]["VALUE"] : null;
        $this->defaultValue = isset($xmlArr["ATTRIBUTES"]["DEFAULTVALUE"]) ? $xmlArr["ATTRIBUTES"]["DEFAULTVALUE"] : null;
        $this->type = isset($xmlArr["ATTRIBUTES"]["TYPE"]) ? $xmlArr["ATTRIBUTES"]["TYPE"] : null;
        $this->format = isset($xmlArr["ATTRIBUTES"]["FORMAT"]) ? $xmlArr["ATTRIBUTES"]["FORMAT"] : null;
        $this->length = isset($xmlArr["ATTRIBUTES"]["LENGTH"]) ? $xmlArr["ATTRIBUTES"]["LENGTH"] : null;
        $this->required = isset($xmlArr["ATTRIBUTES"]["REQUIRED"]) ? $xmlArr["ATTRIBUTES"]["REQUIRED"] : null;
        $this->encrypted = isset($xmlArr["ATTRIBUTES"]["ENCRYPTED"]) ? strtoupper($xmlArr["ATTRIBUTES"]["ENCRYPTED"]) : "N";
//        if($this->encrypted=='Y'){
//        	$this->clearText="N";
//        }else{
//        	$this->clearText="Y";
//        }
        $this->validator = isset($xmlArr["ATTRIBUTES"]["VALIDATOR"]) ? $xmlArr["ATTRIBUTES"]["VALIDATOR"] : null;
        $this->sqlExpression = isset($xmlArr["ATTRIBUTES"]["SQLEXPR"]) ? $xmlArr["ATTRIBUTES"]["SQLEXPR"] : null;
        $this->valueOnCreate = isset($xmlArr["ATTRIBUTES"]["VALUEONCREATE"]) ? $xmlArr["ATTRIBUTES"]["VALUEONCREATE"] : null;
        $this->valueOnUpdate = isset($xmlArr["ATTRIBUTES"]["VALUEONUPDATE"]) ? $xmlArr["ATTRIBUTES"]["VALUEONUPDATE"] : null;
        if (isset($xmlArr["ATTRIBUTES"]["ONAUDIT"]) && $xmlArr["ATTRIBUTES"]["ONAUDIT"] == 'Y') {
            $this->onAudit = true;
        }

        $this->bizDataObjName = $this->prefixPackage($this->bizDataObjName);

        if (!$this->format) {
            $this->useDefaultFormat();
        }
    }

    /**
     * Use default format if no format is given
     *
     * @return void
     */
    protected function useDefaultFormat()
    {
        if ($this->type == "Date") {
            $this->format = '%Y-%m-%d';
        } elseif ($this->type == "Datetime") {
            $this->format = '%Y-%m-%d %H:%M:%S';
        }
    }

    /**
     * Get property value
     *
     * @param string $propertyName property name
     * @return mixed property value
     */
    public function getProperty($propertyName)
    {
        $ret = parent::getProperty($propertyName);
        if ($ret) {
            return $ret;
        }
        //if ($propertyName == "Value") return $this->getValue();
        if ($propertyName == "Value") {
            return $this->lookupValue();
        }
        return $this->$propertyName;
    }

    /**
     * Change the {@link BizDataObj} name. This function is used in case of the current {@link BizDataObj}
     * inheriting from another {@link BizDataObj}, BizField's {@link BizDataObj} name should be changed to
     * current {@link BizDataObj} name, not the parent object name.
     *
     * @param string $bizObjName the name of {@link BizDataObj} object
     * @return void
     */
    public function adjustBizObjName($bizObjName)
    {
        if ($this->bizDataObjName != $bizObjName) {
            $this->bizDataObjName = $bizObjName;
        }
    }

    /**
     * Get string used in sql - with single quote, or without single quote in case of number
     *
     * @param mixed $input the value to add quote. If null, use the current field value
     * @return string string used in sql
     */
    public function getSqlValue($input = null)
    {
        $value = ($input !== null) ? $input : $this->value;
        if ($value === null) {
            return "";
        }
        /*
          if ($this->type != 'Number')
          {
          if (get_magic_quotes_gpc() == 0) {
          $val = addcslashes($value, "\000\n\r\\'\"\032");
          }
          return "'$value'";
          }
         */

        return $value;
    }

    /**
     * Check if the field is a LOB type column
     *
     * @return boolean true if the field points a LOB type column
     */
    public function isLobField()
    {
        return ($this->type == 'Blob' || $this->type == 'Clob');
    }

    /**
     * Get insert lob value when execute insert SQL. For a lob column, insert SQL first inserts
     * an empty entry in the lob column. Then use update to actually add the lob data.
     *
     * @param string $dbType database type
     * @return string the insert string for the lob column
     */
    public function getInsertLobValue($dbType)
    {
        if ($dbType == 'oracle' || $dbType == 'oci8') {
            if ($this->type != 'Blob') {
                return 'empty_blob()';
            }
            if ($this->type != 'Clob') {
                return 'empty_clob()';
            }
        }
        return 'null';
    }

    /**
     * Lookup the value of the field. Typically used in expression @:Field[name].Value
     *
     * @param boolean $formatted true if want to get the formatted value
     * @return mixed string or number depending on the field type
     */
    public function lookupValue()
    {
        $this->getDataObj()->getActiveRecord();
        return $this->getValue();
    }

    /**
     * Get the value of the field.
     *
     * @param boolean $formatted true if want to get the formatted value
     * @return mixed string or number depending on the field type
     */
    public function getValue($formatted = true)
    {
        // need to ensure that value are retrieved from source/cache
        //if ($this->getDataObj()->CheckDataRetrieved() == false)
        //$this->getDataObj()->getActiveRecord();

        if ($this->_prevValue == $this->value) {
            return $this->_getValueCache;
        }
        //$value = stripcslashes($this->value);
        $value = $this->value;
        if ($this->valueExpression && trim($this->column) == "") {
            $value = Expression::evaluateExpression($this->valueExpression, $this->getDataObj());
        }
        if ($this->format && $formatted) {
            $value = Openbizx::$app->getTypeManager()->valueToFormattedString($this->type, $this->format, $value);
        }
        $this->_prevValue = $this->value;
        $this->_getValueCache = $value;
        return $value;
    }

    /**
     * Set the value of the field.
     *
     * @param mixed $value
     * @return void
     */
    public function setValue($value)
    {
        $this->value = $value;
    }

    /**
     * Save the old value to an internal variable
     *
     * @param mixed $value
     * @return void
     */
    public function saveOldValue($value = null)
    {
        if ($value) {
            $this->oldValue = $value;
        } else {
            $this->oldValue = $this->value;
        }
    }

    /**
     * Get default value of the field
     *
     * @return string the default value of the field
     */
    public function getDefaultValue()
    {
        if ($this->defaultValue !== null) {
            return Expression::evaluateExpression($this->defaultValue, $this->getDataObj());
        }
        return "";
    }

    /**
     * Get the value when a new record is created
     *
     * @return mixed the value of the field
     */
    public function getValueOnCreate()
    {
        if ($this->valueOnCreate !== null) {
            return $this->getSqlValue(Expression::evaluateExpression($this->valueOnCreate, $this->getDataObj()));
        }
        return "";
    }

    /**
     * Get the value when a record is updated
     *
     * @return mixed the value of the field
     */
    public function getValueOnUpdate()
    {
        if ($this->valueOnUpdate !== null)
            return $this->getSqlValue(Expression::evaluateExpression($this->valueOnUpdate, $this->getDataObj()));
        return "";
    }

    /**
     * Get the {@link BizDataObj} instance
     *
     * @return BizDataObj {@link BizDataObj} instance
     */
    protected function getDataObj()
    {
        return Openbizx::getObject($this->bizDataObjName);
    }

    /**
     * Check if the field is a required field
     *
     * @return boolean true if the field is a required field
     */
    public function checkRequired()
    {
        if (!$this->required || $this->required == "") {
            return false;
        } elseif ($this->required == "Y") {
            $required = true;
        } elseif ($required != "N") {
            $required = false;
        } else {
            $required = Expression::evaluateExpression($this->required, $this->getDataObj());
        }
        return $required;
    }

    /**
     * Check value type
     *
     * @param mixed $value
     * @return mixed|boolean
     */
    public function checkValueType($value = null)
    {
        if (!$value) {
            $value = $this->value;
        }
        $validator = Openbizx::getService(VALIDATE_SERVICE);
        switch ($this->type) {
            case "Number":
                $result = is_numeric($value);
                break;

            case "Text":
                $result = is_string($value);
                break;

            case "Date":
                $result = $validator->date($value);
                break;
            /*
              case "Datetime":    // zend doesn't support date time
              $result = $validator->date($value);
              break;

              case "Currency":
              $result = $validator->date($value);
              break;
             */
            case "Phone":
                $result = $validator->phone($value);
                break;

            default:
                $result = true;
                break;
        }

        return $result;
    }

    /**
     * Check if the field has valid value
     *
     * @return boolean true if validation is good
     */
    public function validate()
    {
        $ret = true;
        if ($this->validator)
            $ret = Expression::evaluateExpression($this->validator, $this->getDataObj());
        return $ret;
    }

}

?>


<?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\Service;

use InvalidArgumentException;
use Doctrine\Common\EventManager;
use Doctrine\Common\EventSubscriber;
use DoctrineModule\Service\AbstractFactory;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Factory responsible for creating EventManager instances
 */
class EventManagerFactory extends AbstractFactory
{
    /**
     * {@inheritDoc}
     */
    public function createService(ServiceLocatorInterface $sl)
    {
        /** @var $options \DoctrineModule\Options\EventManager */
        $options      = $this->getOptions($sl, 'eventmanager');
        $eventManager = new EventManager();

        foreach ($options->getSubscribers() as $subscriberName) {
            $subscriber = $subscriberName;

            if (is_string($subscriber)) {
                if ($sl->has($subscriber)) {
                    $subscriber = $sl->get($subscriber);
                } elseif (class_exists($subscriber)) {
                    $subscriber = new $subscriber();
                }
            }

            if ($subscriber instanceof EventSubscriber) {
                $eventManager->addEventSubscriber($subscriber);
                continue;
            }

            $subscriberType = is_object($subscriberName) ? get_class($subscriberName) : $subscriberName;

            throw new InvalidArgumentException(
                sprintf(
                    'Invalid event subscriber "%s" given, must be a service name, '
                    . 'class name or an instance implementing Doctrine\Common\EventSubscriber',
                    is_string($subscriberType) ? $subscriberType : gettype($subscriberType)
                )
            );
        }

        return $eventManager;
    }

    /**
     * Get the class name of the options associated with this factory.
     *
     * @return string
     */
    public function getOptionsClass()
    {
        return 'DoctrineModule\Options\EventManager';
    }
}


<?php

namespace Simphotonics\Utils;

/**
 * @author D Reschner <d.reschner@simphotonics.com>
 * @copyright 2015 Simphotonics
 * Description: Array helper functions.
 */
class ArrayUtils
{
    /**
     * Return the array offset corresponding to an array key.
     * @param  Array  &$arr
     * @param  strin|int $key
     * @return int
     */
    public static function key2offset(array &$arr, $key)
    {
        return isset($arr[$key]) ? array_flip(array_keys($arr))[$key] : false;
    }

    /**
     * Returns the array key corresponding to a given array offset.
     * @param  Array  &$arr
     * @param  int $offset
     * @return string|int
     */
    public static function offset2key(array &$arr, $offset)
    {
        $keys = array_keys($arr);
        return isset($keys[$offset]) ? $keys[$offset] : false;
    }

    /**
     * Returns an array of random integers: $first <= random int <= $last.
     * @param  int  $length
     * @param  integer $first
     * @param  integer $last
     * @return array
     */
    public static function randArray($length, $first = 0, $last = 255)
    {
        for ($i = 0; $i < $length; $i++) {
            $arr[] = mt_rand($first, $last);
        }
        return $arr;
    }

    /**
     * Returns the mean of numeric array values.
     * @param  array  $arr
     * @return float|null
     */
    public static function mean(array $arr)
    {
        if (!is_array($arr)) {
            return null;
        }
        return array_sum($arr)/sizeof($arr);
    }

    /**
     * Returns the standard deviation of numeric array values.
     * @param  array  $arr
     * @return float|null
     */
    public static function stDeviation(array $arr)
    {
        if (!is_array($arr) || sizeof($arr) < 2) {
            return null;
        }
        $mean = self::mean($arr);
        array_walk($arr, function (&$x) use ($mean) {
            $x = ($x - $mean)*($x -$mean);

        });
        return sqrt(array_sum($arr)/(sizeof($arr)-1));
    }
}


<?php

namespace Interpro\QuickStorage\Laravel\Sorting;

use Interpro\QuickStorage\Concept\Exception\BuildQueryException;
use Interpro\QuickStorage\Concept\Sorting\GroupSorting as GroupSortingInterface;
use Interpro\QuickStorage\Concept\Sorting\GroupSortingSet as GroupSortingSetInterface;
use Interpro\QuickStorage\Laravel\GroupSet;

class GroupSortingSet implements GroupSortingSetInterface
{
    use GroupSet;

    /**
     * @param string $groupName
     *
     * @param string $field_name
     *
     * @param string $way
     *
     * @return void
     */
    private function rawAdd($group_name, $field_name, $way='ASC')
    {
        //Вызываем из конструктора
        //Вызываем из конструктора
        //Вызываем из конструктора
        //Вызываем из конструктора

    }

    public function __construct()
    {
        //Забираем из сессии установки сортировки
        //Забираем из сессии установки сортировки
        //Забираем из сессии установки сортировки
        //Забираем из сессии установки сортировки
        //Забираем из сессии установки сортировки
    }

    /**
     * @param string $group_name
     *
     * @param GroupSortingInterface $sorting
     *
     * @return void
     */
    public function add($group_name, GroupSortingInterface $sorting)
    {
        $field_name = $sorting->getFieldName();

        if(!($sorting->getGroup() == $group_name))
        {
            throw new BuildQueryException('Добавление сортировки по полю '.$field_name.' не в ту группу '.$group_name);
        }

        $this->addEmptyGroup($group_name);

        if(array_key_exists($field_name, $this->keys[$group_name]))
        {
            $this->items[$group_name][$this->keys[$group_name][$field_name]] = $sorting;
        }else{
            $this->items[$group_name][] = $sorting;
            $this->keys[$group_name][$field_name] = count($this->items[$group_name])-1;
        }

    }

}