<?php

/**
 * @file
 *
 * @package In2pire
 * @subpackage Cli
 * @author Nhat Tran <nhat.tran@inspire.vn>
 */

namespace In2pire\Cli;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\ListCommand;
use In2pire\Cli\Command\HelpCommand;
use In2pire\Cli\Command\BashCompletionCommand;

class Application extends \Symfony\Component\Console\Application
{
    /**
     * Description.
     *
     * @var string
     */
    protected $description = null;

    /**
     * Application alias.
     */
    protected $alias = null;

    /**
     * Commmands.
     *
     * @var array
     */
    protected $commands = [];

    /**
     * Commmand Aliases.
     *
     * @var array
     */
    protected $commandAliases = [];

    /**
     * {@inheritdoc}
     */
    public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN', $description = null, $alias = null)
    {
        parent::__construct($name, $version);
        $this->description = $description;
        $this->alias = $alias;
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultCommands()
    {
        return array(new HelpCommand(), new ListCommand());
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultInputDefinition()
    {
        $definition = parent::getDefaultInputDefinition();
        $definition->addOption(new InputOption('--bash-completion', null, InputOption::VALUE_NONE, 'Generate bash completion for application'));
        return $definition;
    }

    /**
     * Get default options id.
     *
     * @return array
     *   Option IDs.
     */
    protected function getDefaultOptionIds()
    {
        $optionIds = [];
        $defaultDefinition = $this->getDefaultInputDefinition();

        foreach ($defaultDefinition->getOptions() as $option) {
            $optionIds[] = $option->getName();
        };

        return $optionIds;
    }

    /**
     * {@inheritdoc}
     */
    public function getHelp()
    {
        $help = $this->getLongVersion();

        if (!empty($this->description)) {
            $help .= "\n\n" . $this->description;
        }

        return $help;
    }

    /**
     * Set description.
     *
     * @param string $description
     *   New description.
     *
     * @return \Symfony\Component\Console\Application
     *   The called object.
     */
    public function setDescription($description)
    {
        $this->description = $description;
        return $this;
    }

    /**
     * Get description.
     *
     * @return string
     *   Application description.
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set alias.
     *
     * @param string $alias
     *   New alias.
     *
     * @return \Symfony\Component\Console\Application
     *   The called object.
     */
    public function setAlias($alias)
    {
        $this->alias = $alias;
        return $this;
    }

    /**
     * Get alias.
     *
     * @return string
     *   Application alias.
     */
    public function getAlias()
    {
        return $this->alias;
    }

    /**
     * {@inheritdoc}
     */
    public function add(\Symfony\Component\Console\Command\Command $command)
    {
        parent::add($command);

        // Add to command list.
        $commandName = $command->getName();
        $this->commands[$commandName] = $command;
        $this->commandAliases[$commandName][] = $commandName;

        foreach ($command->getAliases() as $alias) {
            $this->commands[$alias] = $command;
            $this->commandAliases[$commandName][] = $alias;
        }

        return $command;
    }

    /**
     * Get bash completion.
     *
     * @return string
     *   Bash completion.
     */
    protected function getBashCompletion()
    {
        // Bash completion variables.
        $completion = '';
        $function = '';
        $tab = str_repeat(' ', 4);

        // Application variables.
        $appName = $this->getName();
        $appVersion = $this->getVersion();
        $appId = basename($_SERVER['SCRIPT_NAME']);

        // Command variables.
        $commands = '"' . implode('" "', array_keys($this->commands)) . '"';
        $defaulOptions = '"--' . implode('" "--', $this->getDefaultOptionIds()) . '"';

        // Headers.
        $headers = <<<HEADERS
#!/bin/bash

# Bash Completion for $appName ($appVersion)
# Generated by IN2PIRE CLI Framework (https://github.com/in2pire/in2pire-cli)
HEADERS;

        // Function.
        $function .= $tab . 'COMPREPLY=()' . PHP_EOL;
        $function .= $tab . 'local cur=${COMP_WORDS[COMP_CWORD]}' . PHP_EOL;
        $function .= $tab . 'local prev=${COMP_WORDS[COMP_CWORD-1]}' . PHP_EOL;
        $function .= $tab . 'local options=(' . $defaulOptions . ')' . PHP_EOL;
        $function .= $tab . 'local arrayOptions=()' . PHP_EOL;
        $function .= PHP_EOL;
        $function .= $tab . 'if [ $COMP_CWORD -eq 1 ]; then' . PHP_EOL;
        $function .= $tab . $tab . 'if [[ ${cur} == -* ]] ; then' . PHP_EOL;
        $function .= $tab . $tab . $tab . 'COMPREPLY=( $( compgen -W "${options[*]}" -- $cur) )' . PHP_EOL;
        $function .= $tab . $tab . 'else' . PHP_EOL;
        $function .= $tab . $tab . $tab . 'commands=(' . $commands . ')' . PHP_EOL;
        $function .= $tab . $tab . $tab . 'COMPREPLY=( $( compgen -W "${commands[*]}" -- $cur) )' . PHP_EOL;
        $function .= $tab . $tab . 'fi' . PHP_EOL;
        $function .= $tab . $tab . 'return 0' . PHP_EOL;
        $function .= $tab . 'fi' . PHP_EOL;
        $function .= PHP_EOL;

        $cases = [];
        $caseContents = [];

        foreach ($this->commandAliases as $commandId => $aliases) {
            $command = $this->commands[$commandId];
            $definition = $command->getDefinition();
            $options = [];
            $arrayOptions = [];
            $possibleOptionValues = [];

            foreach ($definition->getOptions() as $option) {
                $optionName = $option->getName();

                if ($option instanceof \In2pire\Cli\Input\InputOption) {
                    if ($option->isFlag() || !$option->acceptValue()) {
                        $options[] = '--' . $optionName;
                        continue;
                    }

                    $possibleValues = $option->getPossibleValues();

                    if (!empty($possibleValues)) {
                        $possibleOptionValues[$optionName] = array_filter($possibleValues, function ($value) {
                            return $value !== '';
                        });
                    }
                }

                $options[] = '--' . $optionName;

                if ($option->isArray()) {
                    $arrayOptions[] = $optionName;
                }
            }

            if (!empty($options)) {
                $signature = md5(serialize($options) . serialize($arrayOptions) . serialize($possibleOptionValues));

                if (isset($cases[$signature])) {
                    $cases[$signature] = array_merge($cases[$signature], $aliases);
                } else {
                    $cases[$signature] = $aliases;
                    $caseContents[$signature]['options'] = $options;
                    $caseContents[$signature]['arrayOptions'] = $arrayOptions;
                    $caseContents[$signature]['possibleOptionValues'] = $possibleOptionValues;
                }
            }
        }

        if (!empty($cases)) {
            $function .= $tab . 'case "${COMP_WORDS[1]}" in' . PHP_EOL;

            foreach ($cases as $case => $conditions) {
                $function .= $tab . $tab . '"' . implode('"|"', $conditions) . '")' . PHP_EOL;

                if (empty($caseContents[$case]['possibleOptionValues'])) {
                    $function .= $tab . $tab . $tab . 'options+=("' . implode('" "', $caseContents[$case]['options']) . '")' . PHP_EOL;

                    if (!empty($caseContents[$case]['arrayOptions'])) {
                        $function .= $tab . $tab . $tab . 'arrayOptions+=("' . implode('" "', $caseContents[$case]['arrayOptions']) . '")' . PHP_EOL;
                    }
                } else {
                    $function .= $tab . $tab . $tab . 'if [[ ${cur} == -* ]] ; then' . PHP_EOL;
                    $function .= $tab . $tab . $tab . $tab . 'options+=("' . implode('" "', $caseContents[$case]['options']) . '")' . PHP_EOL;

                    if (!empty($caseContents[$case]['arrayOptions'])) {
                        $function .= $tab . $tab . $tab . $tab . 'arrayOptions+=("' . implode('" "', $caseContents[$case]['arrayOptions']) . '")' . PHP_EOL;
                    }

                    $function .= $tab . $tab . $tab . 'else' . PHP_EOL;
                    $function .= $tab . $tab . $tab . $tab . 'case "$prev" in' . PHP_EOL;

                    foreach ($caseContents[$case]['possibleOptionValues'] as $option => $possibleOptionValue) {
                        $function .= $tab . $tab . $tab . $tab . $tab . '"--' . $option . '")' . PHP_EOL;
                        $function .= $tab . $tab . $tab . $tab . $tab . $tab . 'options=("' . implode('" "', $possibleOptionValue) . '")' . PHP_EOL;
                        $function .= $tab . $tab . $tab . $tab . $tab . ';;' . PHP_EOL;
                    }

                    $function .= $tab . $tab . $tab . $tab . $tab . '*)' . PHP_EOL;
                    $function .= $tab . $tab . $tab . $tab . $tab . $tab . 'options+=("' . implode('" "', $caseContents[$case]['options']) . '")' . PHP_EOL;

                    if (!empty($caseContents[$case]['arrayOptions'])) {
                        $function .= $tab . $tab . $tab . $tab . $tab . $tab . 'arrayOptions+=("' . implode('" "', $caseContents[$case]['arrayOptions']) . '")' . PHP_EOL;
                    }

                    $function .= $tab . $tab . $tab . $tab . $tab . ';;' . PHP_EOL;

                    $function .= $tab . $tab . $tab . $tab . 'esac' . PHP_EOL;
                    $function .= $tab . $tab . $tab . 'fi' . PHP_EOL;
                }

                $function .= $tab . $tab . ';;' . PHP_EOL;
            }

            $function .= $tab . 'esac' . PHP_EOL;
            $function .= PHP_EOL;
        }

        $function .= $tab . 'filteredOptions=()' . PHP_EOL;
        $function .= $tab . 'for opt in "${options[@]}"; do' . PHP_EOL;
        $function .= $tab . $tab . 'skip=' . PHP_EOL;
        $function .= $tab . $tab . 'for word in "${COMP_WORDS[@]}"; do' . PHP_EOL;
        $function .= $tab . $tab . $tab . 'if [[ $opt == $word ]]; then' . PHP_EOL;
        $function .= $tab . $tab . $tab . $tab . 'skip=1' . PHP_EOL;
        $function .= $tab . $tab . $tab . $tab . 'for optArr in "${arrayOptions[@]}"; do' . PHP_EOL;
        $function .= $tab . $tab . $tab . $tab . $tab . '[[ $opt == $optArr ]] && { skip=; break; }' . PHP_EOL;
        $function .= $tab . $tab . $tab . $tab . 'done' . PHP_EOL;
        $function .= $tab . $tab . $tab . $tab . '[[ -n $skip ]] && break;' . PHP_EOL;
        $function .= $tab . $tab . $tab . 'fi' . PHP_EOL;
        $function .= $tab . $tab . 'done' . PHP_EOL;
        $function .= $tab . $tab . '[[ -n $skip ]] || filteredOptions+=("$opt");' . PHP_EOL;
        $function .= $tab . 'done' . PHP_EOL;
        $function .= PHP_EOL;

        $function .= $tab . 'COMPREPLY=( $( compgen -W "${filteredOptions[*]}" -- $cur) )' . PHP_EOL;

        // Bash Completion.
        $completion .= $headers . PHP_EOL;
        $completion .= PHP_EOL;
        $completion .= "_$appId() {" . PHP_EOL;
        $completion .= $function;
        $completion .= '}' . PHP_EOL;
        $completion .= PHP_EOL;
        $completion .= "complete -F _$appId $appId" . PHP_EOL;

        if (!empty($this->alias)) {
            $completion .= "complete -F _$appId " . $this->alias . PHP_EOL;
        }

        $completion .= PHP_EOL;

        return $completion;
    }

    /**
     * {@inheritdoc}
     */
    public function doRun(InputInterface $input, OutputInterface $output)
    {
        if (true === $input->hasParameterOption(array('--bash-completion'))) {
            $output->writeln($this->getBashCompletion());
            return 0;
        }

        return parent::doRun($input, $output);
    }
}


<?php
namespace app\manage\logic;

use think\Url;
use cms\Common;
use lookfeel\file\FileManager;

class RuntimeLogic
{

    /**
     * 上级目录
     *
     * @param string $path
     * @return string
     */
    public static function dirName($path = '/')
    {
        // 真实路径
        $path_runtime = realpath(RUNTIME_PATH);
        $path_list = dirname(realpath(RUNTIME_PATH . $path));

        // 上级路径
        if (strpos($path_list, $path_runtime) !== false) {
            return self::processDirName($path_list, $path_runtime);
        } else {
            return '/';
        }
    }

    /**
     * 缓存文件
     *
     * @param string $path
     * @return array
     */
    public static function getRuntime($path = '/')
    {
        // 真实路径
        $path_runtime = realpath(RUNTIME_PATH);
        $path_list = realpath(RUNTIME_PATH . $path);

        // 判断越界
        if (strpos($path_list, $path_runtime) === false) {
            return [];
        }

        // 列出文件
        $list = FileManager::listDir($path_list);
        foreach ($list as &$vo) {
            $vo['file_str'] = self::fileDir($vo['file'], $path_runtime);
            $vo['file'] = str_replace([
                $path_runtime,
                '\\'
            ], [
                '',
                '/'
            ], realpath($vo['file']));
            $vo['size'] = Common::formatBytes($vo['size']);
        }

        return $list;
    }

    /**
     * 删除缓存
     *
     * @param string $path
     * @return boolean
     */
    public static function delRuntime($path = '/', $self = false)
    {
        // 真实路径
        $path_runtime = realpath(RUNTIME_PATH);
        $path_list = realpath(RUNTIME_PATH . $path);

        // 判断越界
        if (strpos($path_list, $path_runtime) === false) {
            return false;
        }

        // 删除文件
        try {
            FileManager::delFile($path_list, $self);

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 文件目录
     *
     * @param string $file
     * @return array
     */
    public static function fileDir($file, $base)
    {
        // 真实路径
        $file = realpath($file);
        $base = realpath($base);

        $file_str = '';
        while (1) {
            if ($file == $base) {
                $file_str = '/runtime' . $file_str;
                break;
            }

            $file_parent = dirname($file);
            $file_current = iconv('gbk', 'utf-8', str_replace($file_parent, '', $file));
            if (is_dir($file)) {
                $file_path = self::processDirName($file, $base);
                $url = Url::build('index/runtime', [
                    'path' => base64_encode($file_path)
                ]);
                $file_str = '/' . str_replace(DS, '', $file_current) . '' . $file_str;
            } else {
                $file_str = $file_current . $file_str;
            }

            $file = $file_parent;
        }

        return str_replace('\\', '/', $file_str);
    }

    /**
     * 处理文件名称
     *
     * @param string $file
     * @param string $base
     * @return mixed
     */
    public static function processDirName($file, $base = null)
    {
        $base || $base = realpath(RUNTIME_PATH);
        return str_replace([
            $base,
            '\\'
        ], [
            '',
            '/'
        ], $file);
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\commands;

use cascade\models\Group;
use cascade\models\User;
use yii\helpers\Console;

/**
 * UsersController Manage users .
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class UsersController extends \canis\console\Controller
{
    /**
     * TBD.
     */
    public function actionIndex()
    {
        echo "Boom";
    }

    /**
     * Create a user.
     */
    public function actionCreate()
    {
        $groups = Group::find()->disableAccessCheck()->orderBy('name')->all();
        $this->out("Groups");
        $options = [];
        $i = 1;
        $defaultGroup = null;
        foreach ($groups as $group) {
            $extra = '';
            if ($group->system === 'users') {
                $defaultGroup = $group->primaryKey;
                $extra = '*';
            }
            $options[$i] = $group->primaryKey;
            $this->out("$i) {$group->descriptor}{$extra}");
            $i++;
        }
        $options[''] = $defaultGroup;
        $group = Console::select("Choose", $options);
        if (empty($group)) {
            $group = $defaultGroup;
        } else {
            $group = $options[$group];
        }

        $user =  new User();
        $user->scenario = 'creation';
        $user->first_name = $this->prompt("First name");
        $user->last_name = $this->prompt("Last name");
        $user->email = $this->prompt("Email");
        $user->status = 1;
        $user->username = $this->prompt("Username");
        $user->password = $this->prompt("Password");
        $user->registerRelationModel(['parent_object_id' => $group]);
        if (!$user->validate()) {
            \d($user->errors);
            $this->stderr("User didn't validate!");
            exit;
        }
        $individual = $user->guessIndividual();
        if (empty($individual)) {
            if (!Console::confirm("No matching individual was found. Continue?")) {
                $this->stderr("Bye!");
                exit;
            }
        } elseif (is_object($individual)) {
            $user->object_individual_id = $individual->primaryKey;
            if (!Console::confirm("Matching individual was found ({$individual->descriptor})! Continue?")) {
                $this->stderr("Bye!");
                exit;
            }
        } else {
            $options = [];
            $i = 1;
            $this->out("Possible Individual Matches...");
            foreach ($individual as $ind) {
                $options[$i] = $ind->primaryKey;
                $this->out("$i) {$ind->descriptor}");
                $i++;
            }
            $user->object_individual_id = Console::select("Choose", $options);
        }

        if ($user->save()) {
            $this->out("User created!");
        } else {
            \d($user->errors);
            $this->out("Error creating user!");
        }
    }
}


<?php

namespace Gaufrette\Core\Behavior;

use Gaufrette\Core\Adapter;
use Gaufrette\Core\Adapter\KnowsItsBehaviors;

class Guesser
{
    /**
     * Say if adapter has the given behavior.
     *
     * @param Adapter $adapter
     * @param string  $behavior
     *
     * @return bool
     */
    public function adapterHasBehavior(Adapter $adapter, $behavior)
    {
        if ($adapter instanceof KnowsItsBehaviors) {
            return in_array($behavior, $adapter->getBehaviors());
        }

        return true === is_a($adapter, $behavior);
    }

    /**
     * Get all behavior of an adapter.
     *
     * @param Adapter $adapter
     *
     * @return string[]
     */
    public function allFromAdapter(Adapter $adapter)
    {
        if ($adapter instanceof KnowsItsBehaviors) {
            return $adapter->getBehaviors();
        }

        $rfl       = new \ReflectionClass($adapter);
        $behaviors = array();

        foreach ($rfl->getInterfaces() as $interface) {
            if (true === $interface->isSubclassOf('Gaufrette\Core\Adapter\Behavior')) {
                $behaviors[] = $interface->getName();
            }
        }

        return $behaviors;
    }
}


<?php

/**
 * Jin Framework
 * Diatem
 */

namespace Jin2\Log;

use Jin2\FileSystem\File;

/**
 * Permet l'écriture de logs
 */
class Log
{

  /**
   * @var boolean  Service actif / inactif
   */
  protected static $enabled = false;

  /**
   * @var string Chemin d'accès relatif ou absolu au fichier de logs
   */
  protected static $logFilePath = '';

  /**
   * Active les logs
   *
   * @param  string  $writePath  Chemin relatif ou absolu du fichier dans lequel écrire les logs
   * @return boolean             Activation réussie ou non
   * @throws \Exception
   */
  public static function enableLogging($writePath)
  {
    if (is_file($writePath)) {
      self::$enabled = true;
      self::$logFilePath = $writePath;
      return true;
    }
    throw new \Exception('Impossible d\'activer les logs dans le fichier '.$writePath.' : celui ci n\'existe pas.');
    return false;
  }

  /**
   * Désactive les logs
   */
  public static function disableLogging()
  {
    self::$enabled = false;
  }

  /**
   * Ecrire dans les logs
   *
   * @param string $output  Ligne à écrire
   */
  public static function write($output)
  {
    if (self::$enabled) {
      $d = new \DateTime();
      $f = new File(self::$logFilePath, true);
      $f->write($d->format('d/m/Y H:i:s') . ' - ' . $output . "\n", true);
    }
  }

  /**
   * éinitialise le fichier de logs
   */
  public static function clear()
  {
    if (self::$enabled) {
      $f = new File(self::$logFilePath, true);
      $f->write('', false);
    }
  }

  /**
   * Modifie la destination des logs
   *
   * @param  string $writePath
   * @return boolean
   * @throws \Exception
   */
  protected static function setPath($writePath)
  {
    if (is_file($writePath)) {
      self::$logFilePath = $writePath;
      return true;
    }
    throw new \Exception('Impossible de modifier la destination des logs : le fichier '.$writePath.' n\'existe pas.');
    return false;
  }

}


<?php
namespace Clusterpoint\Query;

use Clusterpoint\Client;
use Clusterpoint\Helper\Key;
use Clusterpoint\Helper\Raw;
use Clusterpoint\Query\Scope;
use Clusterpoint\Transport\Rest as DataLayer;
use Clusterpoint\Exceptions\ClusterpointException;
use Clusterpoint\Contracts\ConnectionInterface;
/**
 *
 * Parses Query Builder Requests.
 *
 * @category   Clusterpoint 4.0 PHP Client API
 * @package    clusterpoint/php-client-api-v4
 * @copyright  Copyright (c) 2016 Clusterpoint (http://www.clusterpoint.com)
 * @author     Marks Gerasimovs <marks.gerasimovs@clusterpoint.com>
 * @license    http://opensource.org/licenses/MIT    MIT
 */
class Parser
{
    /**
     * Pass back SELECT clause string to set in scope.
     *
     * @param  mixed  $select
     * @return string
     */
    public static function select($select)
    {
        if (gettype($select)=="array") {
            foreach ($select as $key => $field) {
                if ($field instanceof Key) {
                    $alias =  '"'.$field.'"';
                    $field =  self::field($field);
                    $select[$key] = "{$field} as {$alias}";
                }
            }
            $select = implode(", ", $select);
        } elseif (gettype($select)!="string") {
            throw new ClusterpointException("\"->select()\" function: passed parametr is not in valid format.", 9002);
        }
        return $select;
    }

    /**
     * Pass back WHERE clause string to append the scope.
     *
     * @param  string  $field
     * @param  string  $operator
     * @param  mixed   $value
     * @param  string  $logical
     * @return string
     */
    public static function where($field, $operator, $value, $logical)
    {
        if (gettype($field)=="array") {
            throw new ClusterpointException("\"->where()\" function: passed field selector is not in valid format.", 9002);
        }
        if ($operator===null) {
            return "{$logical} {$field} ";
        } elseif ($value===null) {
            $value = $operator;
            $operator = '==';
        }
        if ($field instanceof Key) {
            $field =  self::field("{$field}");
        }
        if (!($value instanceof Raw)) {
        	if (is_string($value)){
				$value = '"'.Client::escape($value).'"';
			}
			else {
				$value =  json_encode($value);
			}
        }
        return "{$logical} {$field}{$operator}{$value} ";
    }

    /**
     * Pass back LIMIT parametr to set to scope.
     *
     * @param  mixed  $limit
     * @return int
     */
    public static function limit($limit)
    {
        if (!is_numeric($limit)) {
            throw new ClusterpointException("\"->limit()\" function: passed parametr is not in valid format.", 9002);
        }
        return intval($limit);
    }

    /**
     * Pass back OFFSET parametr to set to scope.
     *
     * @param  mixed  $offset
     * @return int
     */
    public static function offset($offset)
    {
        if (!is_numeric($offset)) {
            throw new ClusterpointException("\"->offset()\" function: passed parametr is not in valid format.", 9002);
        }
        return intval($offset);
    }

    /**
     * Pass back ORDER BY Clause to append the scope.
     *
     * @param  mixed  $field
     * @param  string $order
     * @return string
     */
    public static function orderBy($field, $order)
    {
        if (!$order) {
            $order = 'DESC';
        }
        $order = strtoupper($order);
        if (!($order=='ASC' || $order=='DESC')) {
            throw new ClusterpointException("\"->order()\" function: ordering should be DESC or ASC.", 9002);
        }
        if (!(gettype($field)=="string" || $field instanceof Key || $field instanceof Raw)) {
            throw new ClusterpointException("\"->order()\" function: passed field selector is not in valid format.", 9002);
        }
        if ($field instanceof Key) {
            $field =  self::field("{$field}");
        }
        return "{$field} {$order}";
    }

    /**
     * Pass back GROUP BY Clause to append the scope.
     *
     * @param  mixed  $field
     * @return string
     */
    public static function groupBy($field)
    {
        if (!(gettype($field)=="string" || $field instanceof Key || $field instanceof Raw)) {
            throw new ClusterpointException("\"->group()\" function: passed field selector is not in valid format.", 9002);
        }
        if ($field instanceof Key) {
            $field =  self::field("{$field}");
        }
        return "{$field}";
    }

    /**
     * Set query parametrs to execute - retrieve by "_id".
     *
     * @param  string  $id
     * @param  \stdClass  $connection
     * @return \Clusterpoint\Response\Single
     */
    public static function find($id = null, $connection)
    {
        if (gettype($id)!="string" && !is_numeric($id)) {
            throw new ClusterpointException("\"->find()\" function: \"_id\" is not in valid format.", 9002);
        }
        $connection->method = 'GET';
        $connection->action = '['.urlencode($id).']';
        $connection->multiple = false;
        return self::sendQuery($connection);
    }

    /**
     * Build query from scope. Passes to execute it.
     *
     * @param  \stdClass  $scope
     * @param  \stdClass $connection
     * @param  bool $multiple
     * @return \Clusterpoint\Response\Batch
     */
    public static function get(Scope $scope, $connection, $multiple, $return = false)
    {
        $from = $connection->db;
        if (strpos($from, '.') !== false) {
            $tmp = explode('.', $connection->db);
            $from = end($tmp);
        }

		if (!is_null($scope->listWordsField)) {
			if ($scope->listWordsField === '') {
				$from = 'LIST_WORDS(' . $from . ')';
			} else {
				$from = 'LIST_WORDS(' . $from . '.' . $scope->listWordsField . ')';
			}
		}

		if (!is_null($scope->alternativesField)) {
			if ($scope->alternativesField === '') {
				$from = 'ALTERNATIVES(' . $from . ')';
			} else {
				$from = 'ALTERNATIVES(' . $from . '.' . $scope->alternativesField . ')';
			}
		}

        $connection->query = $scope->prepend.'SELECT '.$scope->select.' FROM '.$from.' ';

		if (!is_null($scope->join)){
			$connection->query .= $scope->join.' ';
		}

        if ($scope->where!='') {
            $connection->query .= 'WHERE'.$scope->where;
        }
        if (count($scope->groupBy)) {
            $connection->query .= 'GROUP BY '.implode(", ", $scope->groupBy).' ';
        }
        if (count($scope->orderBy)) {
            $connection->query .= 'ORDER BY '.implode(", ", $scope->orderBy).' ';
        }
        $connection->query .= 'LIMIT '.$scope->offset.', '.$scope->limit;
        if ($return) {
            return $connection->query;
        }
        $connection->method = 'POST';
        $connection->action = '/_query';
        $connection->multiple = $multiple;
        $scope->resetSelf();
        return self::sendQuery($connection);
    }

    /**
     * Passes raw query string for exectuion.
     *
     * @param  string  $raw
     * @param  \stdClass $connection
     * @return \Clusterpoint\Response\Batch
     */
    public static function raw($raw, $connection)
    {
        $connection->query = $raw;
        $connection->method = 'POST';
        $connection->action = '/_query';
        $connection->multiple = true;
        return self::sendQuery($connection);
    }

    /**
     * Set query parametrs to execute - delete by "_id".
     *
     * @param  string  $id
     * @param  \stdClass $connection
     * @return \Clusterpoint\Response\Single
     */
    public static function delete($id = null, $connection)
    {
        if (gettype($id)!="string" && !is_numeric($id)) {
            throw new ClusterpointException("\"->delete()\" function: \"_id\" is not in valid format.", 9002);
        }
        $connection->method = 'DELETE';
        $connection->action = '['.urlencode($id).']';
        return self::sendQuery($connection);
    }

    /**
     * Set query parametrs to execute - delete many by "_id".
     *
     * @param  array  $id
     * @param  \stdClass $connection
     * @return \Clusterpoint\Response\Single
     */
    public static function deleteMany(array $ids = array(), $connection)
    {
        if (!is_array($ids)) {
            throw new ClusterpointException("\"->deleteMany()\" function: \"_id\" is not in valid format.", 9002);
        }
        $connection->method = 'DELETE';
        $connection->action = '';

        // force strings! REST hates DELETE with integers for now...
        foreach ($ids as &$id) {
            $id = (string)$id;
        }
        $connection->query = json_encode($ids);
        return self::sendQuery($connection);
    }

    /**
     * Set query document to execute - Insert One.
     *
     * @param  array|object  $document
     * @param  \stdClass $connection
     * @return \Clusterpoint\Response\Single
     */
    public static function insertOne($document, $connection)
    {
        $connection->query = self::singleDocument($document);
        return self::insert($connection);
    }

    /**
     * Set query documents to execute - Insert Many.
     *
     * @param  array|object  $document
     * @param  \stdClass $connection
     * @return \Clusterpoint\Response\Single
     */
    public static function insertMany($document, $connection)
    {
        if (gettype($document)!="array" && gettype($document)!="object") {
            throw new ClusterpointException("\"->insert()\" function: parametr passed ".json_encode(self::escape_string($document))." is not in valid document format.", 9002);
        }
        if (gettype($document)=="object") {
            $document_array = array();
            foreach ($document as $value) {
                $document_array[] = $value;
            }
            $document = $document_array;
        }
        $connection->query = json_encode(array_values($document));
        $connection->multiple = true;
        return self::insert($connection);
    }

    /**
     * Set query parametrs to execute - Insert.
     *
     * @param  array|object  $document
     * @param  \stdClass $connection
     * @return \Clusterpoint\Response\Single
     */
    public static function insert($connection)
    {
        $connection->method = 'POST';
        $connection->action = '';
        return self::sendQuery($connection);
    }

    /**
     * Set query parametrs to execute - Update by "_id".
     *
     * @param  string  $id
     * @param  array|object  $document
     * @param  \stdClass $connection
     * @return \Clusterpoint\Response\Single
     */
    public static function update($id, $document, $connection)
    {
        $from = $connection->db;
        if (strpos($from, '.') !== false) {
            $tmp = explode('.', $connection->db);
            $from = end($tmp);
        }

        $connection->method = 'PATCH';
        $connection->action = '['.urlencode($id).']';
        switch (gettype($document)) {
            case "string":
                $connection->query = $document;
                break;
            case "array":
            case "object":
                $connection->method = 'POST';
                $connection->action = '/_query';
                $connection->query = 'UPDATE '.$from.'["'.$id.'"] SET '.self::updateRecursion($document);
                break;
            default:
                throw new ClusterpointException("\"->update()\" function: parametr passed ".json_encode(self::escape_string($document))." is not in valid format.", 9002);
                break;

        }
        return self::sendQuery($connection);
    }

    /**
     * Parse document for valid update command.
     *
     * @param  mixed  $document
     * @return string
     */
	private static function updateRecursion($document)
	{
		$result = array();
		foreach (self::toDotted($document, '', 1) as $path => $value) {
			$result[] = $path . $value;
		}

		return implode(' ', $result);
	}

	private static function toDotted($array, $prepend = '', $counter = 1)
	{
		$results = [];

		if ($prepend !== '') {
			$results['if (typeof ' . $prepend . ' === \'undefined\' || ' . $prepend . '.constructor !== Object ) {' . $prepend . ' = {}}'] = ';';
		}

		foreach ($array as $key => $value) {
			if ($counter > 1) {
				$key = '["' . $key . '"]';
			} else {
				$results['if (typeof ' . $key . ' === \'undefined\' || ' . $key . '.constructor !== Object) {' . $key . ' = {}}'] = ';';
			}
			if (is_array($value) && !empty($value)) {
				// check if this is meant to be value-only array without assoc keys (P.S. assoc key = field name)
				if (is_array($value) && (count($value) === 0 || array_keys($value) === range(0, count($value) - 1))) {
					$results[$prepend . $key] = ' = ' . json_encode($value) . ';';
				} else {
					$results = array_merge($results, self::toDotted($value, $prepend . $key, $counter + 1));
				}
			} else {
				if (is_array($value) && count($value) === 0) {
					$results[$prepend . $key] = ' = ' . json_encode($value) . ';';
				} else {
					if (is_string($value)){
						$results[$prepend . $key] = ' = "' . Client::escape($value) . '";';
					}
					else {
						$results[$prepend . $key] = ' = ' . Client::escape($value) . ';';
					}

				}
			}
		}

		return $results;
	}

    /**
     * Set query parametrs to execute - Replace by "_id".
     *
     * @param  string  $id
     * @param  array|object  $document
     * @param  \stdClass $connection
     * @return \Clusterpoint\Response\Single
     */
    public static function replace($id, $document, $connection)
    {
        $connection->query = self::singleDocument($document);
        $connection->method = 'PUT';
        $connection->action = '['.urlencode($id).']';
        return self::sendQuery($connection);
    }

    /**
     * Set query parametrs to execute - Begin Transaction.
     *
     * @param  \stdClass $connection
     * @return \Clusterpoint\Response\Single
     */
    public static function beginTransaction($connection)
    {
        $connection->query = 'BEGIN_TRANSACTION';
        $connection->method = 'POST';
        $connection->action = '/_query';
        return self::sendQuery($connection);
    }

    /**
     * Set query parametrs to execute - Rollback Transaction.
     *
     * @param  \stdClass $connection
     * @return \Clusterpoint\Response\Single
     */
    public static function rollbackTransaction($connection)
    {
        $connection->query = 'ROLLBACK';
        $connection->method = 'POST';
        $connection->action = '/_query';
        return self::sendQuery($connection);
    }

    /**
     * Set query parametrs to execute - Commit Transaction.
     *
     * @param  \stdClass $connection
     * @return \Clusterpoint\Response\Single
     */
    public static function commitTransaction($connection)
    {
        $connection->query = 'COMMIT';
        $connection->method = 'POST';
        $connection->action = '/_query';
        return self::sendQuery($connection);
    }

    /**
     * Escapes invalid for regular usage key values.
     *
     * @param  string $field
     * @return field
     */
    public static function field($field)
    {
        return 'this["'.$field.'"]' ;
    }

    /**
     * Pass query Params to Transport Layer for execution.
     *
     * @param  \stdClass $connection
     * @return mixed
     */
    public static function sendQuery(ConnectionInterface $connection)
    {
        $response = DataLayer::execute($connection);
        $connection->resetSelf();
        return $response;
    }

	public static function getStatus($connection)
	{
		$connection->query = '';
		$connection->method = 'GET';
		$connection->action = '/_status';
		$connection->multiple = true;
		return self::sendQuery($connection);
	}

    /**
     * Encode single document in valid format.
     *
     * @param  mixed $document
     * @return string
     */
    public static function singleDocument($document)
    {
        if (gettype($document)!="array" && gettype($document)!="object") {
            throw new ClusterpointException("\"->insert()\" function: parametr passed ".json_encode(self::escape_string($document))." is not in valid document format.", 9002);
        }
        $query = "{";
        $first = true;
        foreach ($document as $key => $value) {
            if (!$first) {
                $query .= ",";
            }
            $query .= '"'.self::escape_string($key).'" : '.json_encode($value);
            $first = false;
        }
        $query .= '}';
        return $query;
    }

    /**
     * Escapes string for special characters.
     *
     * @param  string $string
     * @return string
     */
    public static function escape_string($string)
    {
        $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a");
        $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");
        return str_replace($search, $replace, $string);
    }
}


<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * MessageBuilder.php.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Broadcast;

use EasyWeChat\Core\Exceptions\InvalidArgumentException;
use EasyWeChat\Core\Exceptions\RuntimeException;

/**
 * Class MessageBuilder.
 */
class MessageBuilder
{
    /**
     * Message target user or group.
     *
     * @var mixed
     */
    protected $to;

    /**
     * Message type.
     *
     * @var string
     */
    protected $msgType;

    /**
     * Message.
     *
     * @var mixed
     */
    protected $message;

    /**
     * Message types.
     *
     * @var array
     */
    private $msgTypes = [
        Broadcast::MSG_TYPE_TEXT,
        Broadcast::MSG_TYPE_NEWS,
        Broadcast::MSG_TYPE_IMAGE,
        Broadcast::MSG_TYPE_VIDEO,
        Broadcast::MSG_TYPE_VOICE,
        Broadcast::MSG_TYPE_CARD,
    ];

    /**
     * Preview bys.
     *
     * @var array
     */
    private $previewBys = [
        Broadcast::PREVIEW_BY_OPENID,
        Broadcast::PREVIEW_BY_NAME,
    ];

    /**
     * Set message type.
     *
     * @param string $msgType
     *
     * @return MessageBuilder
     *
     * @throws InvalidArgumentException
     */
    public function msgType($msgType)
    {
        if (!in_array($msgType, $this->msgTypes, true)) {
            throw new InvalidArgumentException('This message type not exist.');
        }

        $this->msgType = $msgType;

        return $this;
    }

    /**
     * Set message.
     *
     * @param string|array $message
     *
     * @return MessageBuilder
     */
    public function message($message)
    {
        $this->message = $message;

        return $this;
    }

    /**
     * Set target user or group.
     *
     * @param mixed $to
     *
     * @return MessageBuilder
     */
    public function to($to)
    {
        $this->to = $to;

        return $this;
    }

    /**
     * Build message.
     *
     * @return bool
     *
     * @throws RuntimeException
     */
    public function build()
    {
        if (empty($this->msgType)) {
            throw new RuntimeException('message type not exist.');
        }

        if (empty($this->message)) {
            throw new RuntimeException('No message content to send.');
        }

        // 群发视频消息给用户列表时，视频消息格式需要另外处理，具体见文档
        if ($this->msgType === Broadcast::MSG_TYPE_VIDEO) {
            if (is_array($this->message)) {
                $this->message = array_shift($this->message);
            }
            $this->msgType = 'mpvideo';
        }

        $content = (new Transformer($this->msgType, $this->message))->transform();

        $group = isset($this->to) ? $this->to : null;

        $message = array_merge($this->buildGroup($group), $content);

        return $message;
    }

    /**
     * Build preview message.
     *
     * @param string $by
     *
     * @return array
     *
     * @throws RuntimeException
     * @throws InvalidArgumentException
     */
    public function buildPreview($by)
    {
        if (!in_array($by, $this->previewBys, true)) {
            throw new InvalidArgumentException('This preview by not exist.');
        }

        if (empty($this->msgType)) {
            throw new RuntimeException('Message type not exist.');
        } elseif ($this->msgType === Broadcast::MSG_TYPE_VIDEO) {
            if (is_array($this->message)) {
                $this->message = array_shift($this->message);
            }
            $this->msgType = 'mpvideo';
        }

        if (empty($this->message)) {
            throw new RuntimeException('No message content to send.');
        }

        if (empty($this->to)) {
            throw new RuntimeException('No to.');
        }

        $content = (new Transformer($this->msgType, $this->message))->transform();

        $message = array_merge($this->buildTo($this->to, $by), $content);

        return $message;
    }

    /**
     * Build group.
     *
     * @param mixed $group
     *
     * @return array
     */
    private function buildGroup($group)
    {
        if (is_null($group)) {
            $group = [
                'filter' => [
                    'is_to_all' => true,
                ],
            ];
        } elseif (is_array($group)) {
            $group = [
                'touser' => $group,
            ];
        } else {
            $group = [
                'filter' => [
                    'is_to_all' => false,
                    'group_id' => $group,
                ],
            ];
        }

        return $group;
    }

    /**
     * Build to.
     *
     * @param string $to
     * @param string $by
     *
     * @return array
     */
    private function buildTo($to, $by)
    {
        return [
            $by => $to,
        ];
    }

    /**
     * Return property.
     *
     * @param string $property
     *
     * @return mixed
     */
    public function __get($property)
    {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }
}


<?php
namespace eMacros;

class Scope implements \ArrayAccess, \IteratorAggregate {
	/**
	 * Symboil table
	 * @var array
	 */
	public $symbols = [];

	/**
	 * Macros list
	 * @var array
	 */
	public $macros = [];

	protected static function symbol($symbol) {
		if ($symbol instanceof Symbol)
			return $symbol->symbol;
		elseif (is_string($symbol))
			return $symbol;

		throw new \UnexpectedValueException(sprintf("Unexpected value of type '%s'.", is_object($symbol) ? get_class($symbol) : gettype($symbol)));
	}

	/**
	 * Obtains a symbol from table
	 * (non-PHPdoc)
	 * @see ArrayAccess::offsetGet()
	 */
	public function offsetGet($symbol) {
		$sym = self::symbol($symbol);

		//is symbol defined on this scope?
		if (array_key_exists($sym, $this->symbols))
			return $this->symbols[$sym];
		else {
			foreach ($this->macros as $regex => $callback) {
				if (preg_match($regex, $sym, $matches))
					return $this->symbols[$sym] = $callback->__invoke($matches);
			}
		}

		return;
	}

	public function offsetExists($symbol) {
		return true;
	}

	/**
	 * Stores a symbol
	 * Used when setting up a Scope/Package
	 * Ex: $this['.'] = new Concatenation();
	 * (non-PHPdoc)
	 * @see ArrayAccess::offsetSet()
	 */
	public function offsetSet($symbol, $value) {
		$this->symbols[Symbol::validateSymbol($symbol)] = $value;
	}

	/**
	 * Removes a symbol from table
	 * (non-PHPdoc)
	 * @see ArrayAccess::offsetUnset()
	 */
	public function offsetUnset($symbol) {
		unset($this->symbols[$symbol]);
	}

	/**
	 * Obtains a symbol iterator
	 * (non-PHPdoc)
	 * @see IteratorAggregate::getIterator()
	 */
	public function getIterator() {
		$symbols = [];

		foreach ($this->listSymbols() as $name)
			$symbols[$name] = $this[$name];

		return new \ArrayIterator($symbols);
	}

	/**
	 * Obtains all defined symbols
	 * @return array
	 */
	public function listSymbols() {
		return array_keys($this->symbols);
	}

	/**
	 * Adds a new macro
	 * @param string $regex
	 * @param \Closure $handler
	 */
	public function macro($regex, \Closure $handler) {
		$this->macros[$regex] = $handler;
	}
}
?>


<?php

namespace Wambo\Catalog;

use Psr\Cache\CacheItemPoolInterface;
use Wambo\Catalog\Exception\RepositoryException;
use Wambo\Catalog\Model\Product;

/**
 * Class CachedProductRepository fetches Product models from the Storage and writes Products back to the Storage
 * while using a cache layer.
 *
 * @package Wambo\Catalog
 */
class CachedProductRepository implements ProductRepositoryInterface
{
    /**
     * @var CacheItemPoolInterface
     */
    private $cache;
    /**
     * @var ProductRepository
     */
    private $productRepository;

    /**
     * Creates a new CachedProductRepository instance.
     *
     * @param CacheItemPoolInterface $cache             A cache backend for storing the results
     * @param ProductRepository      $productRepository A product repository for reading and writing product data
     *
     */
    public function __construct(CacheItemPoolInterface $cache, ProductRepository $productRepository)
    {
        $this->cache = $cache;
        $this->productRepository = $productRepository;
    }

    /**
     * Get all products
     *
     * @return Product[]
     *
     * @throws RepositoryException If fetching the products failed
     */
    public function getProducts()
    {
        $cacheKey = "products";
        if ($this->cache->hasItem($cacheKey)) {

            // return from cache
            $cacheItem = $this->cache->getItem($cacheKey);
            $cachedProducts = $cacheItem->get();
            return $cachedProducts;
        }

        $products = $this->productRepository->getProducts();

        // save to cache
        $cacheItem = $this->cache->getItem($cacheKey);
        $cacheItem->set($products);

        return $products;
    }

    public function getById(string $id)
    {
        throw new RepositoryException("Not implemented yet");
    }

    public function add(Product $product)
    {
        throw new RepositoryException("Not implemented yet");
    }

    public function remove(Product $product)
    {
        throw new RepositoryException("Not implemented yet");
    }
}


<?php

/*
 * This file is part of the Dektrium project.
 *
 * (c) Dektrium project <http://github.com/dektrium/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace dektrium\user\models;

use dektrium\user\Finder;
use yii\base\Model;
use dektrium\user\helpers\Password;

/**
 * LoginForm get user's login and password, validates them and logs the user in. If user has been blocked, it adds
 * an error to login form.
 *
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
class LoginForm extends Model
{
    /** @var string User's email or username */
    public $login;

    /** @var string User's plain password */
    public $password;

    /** @var string Whether to remember the user */
    public $rememberMe = false;

    /** @var \dektrium\user\models\User */
    protected $user;

    /** @var \dektrium\user\Module */
    protected $module;

    /** @var Finder */
    protected $finder;

    /**
     * @param Finder $finder
     * @param array $config
     */
    public function __construct(Finder $finder, $config = [])
    {
        $this->finder = $finder;
        $this->module = \Yii::$app->getModule('user');
        parent::__construct($config);
    }

    /** @inheritdoc */
    public function attributeLabels()
    {
        return [
            'login'      => \Yii::t('user', 'Login'),
            'password'   => \Yii::t('user', 'Password'),
            'rememberMe' => \Yii::t('user', 'Remember me next time'),
        ];
    }

    /** @inheritdoc */
    public function rules()
    {
        return [
            [['login', 'password'], 'required'],
            ['login', 'trim'],
            ['password', function ($attribute) {
                if ($this->user === null || !Password::validate($this->password, $this->user->password_hash)) {
                    $this->addError($attribute, \Yii::t('user', 'Invalid login or password'));
                }
            }],
            ['login', function ($attribute) {
                if ($this->user !== null) {
                    $confirmationRequired = $this->module->enableConfirmation && !$this->module->enableUnconfirmedLogin;
                    if ($confirmationRequired && !$this->user->getIsConfirmed()) {
                        $this->addError($attribute, \Yii::t('user', 'You need to confirm your email address'));
                    }
                    if ($this->user->getIsBlocked()) {
                        $this->addError($attribute, \Yii::t('user', 'Your account has been blocked'));
                    }
                }
            }],
            ['rememberMe', 'boolean'],
        ];
    }

    /**
     * Validates form and logs the user in.
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return \Yii::$app->getUser()->login($this->user, $this->rememberMe ? $this->module->rememberFor : 0);
        } else {
            return false;
        }
    }

    /** @inheritdoc */
    public function formName()
    {
        return 'login-form';
    }

    /** @inheritdoc */
    public function beforeValidate()
    {
        if (parent::beforeValidate()) {
            $this->user = $this->finder->findUserByUsernameOrEmail($this->login);
            return true;
        } else {
            return false;
        }
    }
}


<?php
/**
 * (c) Joffrey Demetz <joffrey.demetz@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace JDZ\Filesystem;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Exception;

/**
 * Folder Helper
 *
 * @author Joffrey Demetz <joffrey.demetz@gmail.com>
 */
abstract class Folder
{
  /**
   * Mirrors a directory to another.
   *
   * @param   string    $src    The path to the source folder
   * @param   string    $dest   The path to the destination folder
   * @param   bool      $force  Force copy
   * @throws   Exception
   */
  public static function copy($src, $dest, $force=false, $delete=false)
  {
    $src  = Path::clean($src);
    $dest = Path::clean($dest);

    $fs = new Filesystem();

    try {
      $fs->mirror($src, $dest, null, [ 'override' => $force, 'delete' => $delete, 'copy_on_windows' => true ]);
    } catch(IOExceptionInterface $e){
      throw new Exception(Helper::getTranslation('CANNOT_FIND_SOURCE').' '.$e->getPath());
    }

    return true;
  }

  /**
   * Creates a directory recursively.
   *
   * @param string|array|\Traversable $dirs The directory path
   * @param int                       $mode The directory mode
   * @throws Exception On any directory creation failure
   */
  public static function create($path='', $mode=0777)
  {
    $path = Path::clean($path);

    $fs = new Filesystem();

    try {
      $fs->mkdir($path);
    } catch(IOExceptionInterface $e){
      throw new Exception(Helper::getTranslation('FAILED_CREATING').' '.$e->getPath());
    }

    return true;
  }

  /**
   * Checks the existence of files or directories.
   *
   * @param   string    $path     Folder name relative to installation dir
   * @return  bool      true if the file exists, false otherwise
   */
  public static function exists($path)
  {
    $path = Path::clean($path);

    $fs = new Filesystem();
    return $fs->exists($path);
  }

  /**
   * Delete a folder.
   *
   * @param   string    $path     The path to the folder to delete.
   * @return   boolean   True on success
   * @throws   Exception
   */
  public static function delete($path)
  {
    if ( !Folder::exists($path) ){
      return true;
    }

    $path = Path::clean($path);

    if ( trim($path) === '' ){
      throw new Exception(Helper::getTranslation('FAILED_DELETING').' : Cannot delete root path');
    }

    $fs = new Filesystem();

    try {
      $fs->remove($path);
    }
    catch(IOExceptionInterface $e){
      throw new Exception(Helper::getTranslation('FAILED_DELETING').' - ('.$e->getMessage().')');
    }

    return true;
  }

  /**
   * Moves a folder.
   *
   * @param   string    $src          The path to the source folder
   * @param   string    $dest         The path to the destination folder
   * @param   bool      $overwrite    Overwrite destination file
   * @return   boolean   True on success
   * @throws   Exception
   */
  public static function move($src, $dest, $overwrite=false)
  {
    $src  = Path::clean($src);
    $dest = Path::clean($dest);

    if ( !Folder::exists($src) ){
      throw new Exception(Helper::getTranslation('CANNOT_FIND_SOURCE').' : '.$src);
    }

    if ( Folder::exists($dest) ){
      throw new Exception(Helper::getTranslation('ALREADY_EXISTS').' : '.$dest);
    }

    $fs = new Filesystem();

    try {
      $fs->rename($src, $dest, $overwrite);
    }
    catch(IOExceptionInterface $e){
      throw new Exception(Helper::getTranslation('FAILED_RENAMING').' - ('.$e->getMessage().')');
    }

    return true;
  }

  /**
   * Utility function to read the files in a folder.
   *
   * @param   string    $path           The path of the folder to read.
   * @param   string    $filter         A filter for file names.
   * @param   mixed     $recurse        True to recursively search into sub-folders, or an integer to specify the maximum depth.
   * @param   boolean   $full           True to return the full path to the file.
   * @param   array     $exclude        Array with names of files which should not be shown in the result.
   * @param   array     $excludefilter  Array of filter to exclude
   * @param   boolean   $naturalSort    False for asort, true for natsort
   * @return   array     Array of files
   * @throws   Exception
   */
  public static function files($path, $filter = '.', $recurse = false, $full = false, $exclude = array('.svn', 'CVS', '.DS_Store', '__MACOSX', 'Thumbs.db'), $excludefilter = array('^\..*', '.*~'), $naturalSort = true)
  {
    $path = Path::clean($path);

    if ( !is_dir($path) ){
      throw new Exception(Helper::getTranslation('NOT_A_FOLDER'));
    }

    if ( count($excludefilter) ){
      $excludefilter_string = '/(' . implode('|', $excludefilter) . ')/';
    }
    else {
      $excludefilter_string = '';
    }

    $arr = Folder::_items($path, $filter, $recurse, $full, $exclude, $excludefilter_string, true);

    if ( $naturalSort ){
      natsort($arr);
    }
    else {
      asort($arr);
    }
    return array_values($arr);
  }

  /**
   * Utility function to read the folders in a folder.
   *
   * @param   string    $path           The path of the folder to read.
   * @param   string    $filter         A filter for folder names.
   * @param   mixed     $recurse        True to recursively search into sub-folders, or an integer to specify the maximum depth.
   * @param   boolean   $full           True to return the full path to the folders.
   * @param   array     $exclude        Array with names of folders which should not be shown in the result.
   * @param   array     $excludefilter  Array with regular expressions matching folders which should not be shown in the result.
   * @return   array     Array of folders
   * @throws   Exception
   */
  public static function folders($path, $filter = '.', $recurse = false, $full = false, $exclude = array('.svn', 'CVS', '.DS_Store', '__MACOSX', 'Thumbs.db'), $excludefilter = array('^\..*'))
  {
    $path = Path::clean($path);

    if ( !is_dir($path) ){
      throw new Exception(Helper::getTranslation('NOT_A_FOLDER'));
    }

    if ( count($excludefilter) ){
      $excludefilter_string = '/(' . implode('|', $excludefilter) . ')/';
    }
    else {
      $excludefilter_string = '';
    }

    $arr = Folder::_items($path, $filter, $recurse, $full, $exclude, $excludefilter_string, false);

    asort($arr);
    return array_values($arr);
  }

  /**
   * Function to read the files/folders in a folder.
   *
   * @param   string    $path                  The path of the folder to read.
   * @param   string    $filter                A filter for file names.
   * @param   mixed     $recurse               True to recursively search into sub-folders, or an integer to specify the maximum depth.
   * @param   boolean   $full                  True to return the full path to the file.
   * @param   array     $exclude               Array with names of files which should not be shown in the result.
   * @param   string    $excludefilter_string  Regexp of files to exclude
   * @param   boolean   $findfiles             True to read the files, false to read the folders
   * @return   array     Files
   */
  protected static function _items($path, $filter, $recurse, $full, $exclude, $excludefilter_string, $findfiles)
  {
    @set_time_limit(ini_get('max_execution_time'));

    $arr = [];

    if ( false === ($handle=@opendir($path)) ){
      return $arr;
    }

    while( false !== ($file=readdir($handle)) ){
      if ( $file != '.' && $file != '..' && !in_array($file, $exclude) && (empty($excludefilter_string) || !preg_match($excludefilter_string, $file)) ){
        $fullpath = $path . DIRECTORY_SEPARATOR . $file;

        $isDir = is_dir($fullpath);

        if ( ($isDir xor $findfiles) && preg_match("/$filter/", $file) ){
          if ( $full ){
            $arr[] = $fullpath;
          }
          else {
            $arr[] = $file;
          }
        }

        if ( $isDir && $recurse === true ){
          $arr = array_merge($arr, Folder::_items($fullpath, $filter, true, $full, $exclude, $excludefilter_string, $findfiles));
        }
      }
    }

    closedir($handle);
    return $arr;
  }
}


<?php
namespace Lab123\Odin\Requests;

use Illuminate\Foundation\Http\FormRequest as BaseFormRequest;

abstract class FormRequest extends BaseFormRequest
{

    /**
     * General rules to validate this request.
     */
    protected $rules = [];

    /**
     * Rules to validate in this request.
     */
    protected $validateFields = [];

    /**
     * Custom rules to validate in this request.
     */
    protected $customRules = [];

    /**
     * Override rules to validate in this request.
     */
    protected $overrideRules = [];

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $this->customValidates();
        $this->overrideValidates();

        return array_only($this->rules, $this->validateFields);
    }

    /**
     * Set the validation rules that apply to the request.
     *
     * @return array
     */
    private function customValidates()
    {
        if (count($this->customRules) > 0) {
            foreach ($this->customRules as $field => $value) {
                if (empty($value) || is_int($field)) {
                    continue;
                }

                $this->rules[$field] .= $value;
            }
        }
    }

    /**
     * Set the validation rules that apply to the request.
     *
     * @return array
     */
    private function overrideValidates()
    {
        if (count($this->overrideRules) > 0) {
            foreach ($this->overrideRules as $field => $value) {
                if (empty($value) || is_int($field)) {
                    continue;
                }

                $this->rules[$field] = $value;
            }
        }
    }
}


<?php

/*
 * This file is part of the Сáша framework.
 *
 * (c) tchiotludo <http://github.com/tchiotludo>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types = 1);

namespace Cawa\Renderer;

use Cawa\Core\DI;
use Cawa\Net\Uri;

trait AssetTrait
{
    /**
     * @param string $path
     *
     * @return array<Uri, bool>
     */
    protected function getAssetData(string $path) : array
    {
        $return = [null, DI::config()->exists('assets/hashes')];

        // file hash
        $hashes = DI::config()->getIfExists('assets/hashes');
        if ($hashes) {
            if (isset($hashes[$path])) {
                $path = $hashes[$path];
            }
        }

        // relative path like "vendor.js", add assets/url
        if (substr($path, 0, 4) != 'http' && // remove "http//host/vendor.js"
            substr($path, 0, 1) != '/' && // remove "/vendor.js" & "//host/vendor.js"
            $assetsPath = DI::config()->get('assets/url')) {
            $path = rtrim($assetsPath, '/') . '/' . $path;
        }

        $host = '';
        if (substr($path, 0, 1) == '/') {
            if (DI::config()->getIfExists('assets/absolute')) {
                $host = self::request()->getUri()->getHostFull();
            } else {
                $host = DI::config()->getIfExists('assets/host');
            }
        }

        $return[0] = (new Uri(null, [Uri::OPTIONS_RELATIVE => empty($host)]))
            ->setPath($path)
            ->setQueries([])
            ->setFragment();

        if ($host) {
            $return[0]->setHostFull($host);
        }

        return $return;
    }

    /**
     * @param string $path
     *
     * @return Uri
     */
    public function asset(string $path) : Uri
    {
        list($path) = $this->getAssetData($path);

        return $path;
    }
}


<?php

namespace Esockets\Protocol;

use Esockets\Base\AbstractProtocol;
use Esockets\Base\CallbackEventListener;
use Esockets\Base\Exception\ReadException;
use Esockets\Base\Exception\SendException;
use Esockets\Base\IoAwareInterface;
use Esockets\Base\PingPacket;
use Esockets\Base\PingSupportInterface;

/**
 * Протокол потоковой передачи данных любого типа.
 * В задачи данного протокола входит:
 *  - сериализация (json-изация) отправляемых структур данных
 *  - десериализация полученных на другой стороне данных.
 * Структура пакета данных протокола EasyStream:
 * FSdata* - короткий пакет, у него 1 байт на флаги, 1 байт на длину данных,
 * FSSSSdata* - обычный пакет, 1 байт на флаги, по 4 байта на длину данных и номер пакета
 */
final class EasyStream extends AbstractProtocol implements PingSupportInterface
{
    const SHORT_PACKET = 0x01; // короткий пакет
    const DATA_INT = 0x02; // целочисленный тип
    const DATA_FLOAT = 0x04; // вещественное число
    const DATA_STRING = 0x08; // строка
    const DATA_ARRAY = 0x10; // массив (кодируется в json)
    const DATA_OBJECT = 0x20; // объект (сериализуется)
//    const DATA_PING_PONG = 0x40; // reserved
//    const DATA_CONTROL = 0x80; // reserved

    const SHORT_HEADER_SIZE = 2; // размер короткого заголовка EasyStream протокола
    const SHORT_PACKET_SIZE = 256; // размер полезных данных короткого пакета
    const SHORT_PACKET_SIZE_WITH_HEADER
        = self::SHORT_PACKET_SIZE + self::SHORT_HEADER_SIZE; // полный размер короткого пакета
    const HEADER_SIZE = 5; // размер обычного заголовка EasyStream протокола
    const PACKET_MAX_SIZE = 4294967296; // максимальный размер полезных данных пакета, теоретический (4GB)
    const PACKET_MAX_SIZE_WITH_HEADER
        = self::PACKET_MAX_SIZE + self::HEADER_SIZE; // полный размер обычного пакета

    /**
     * Буфер чтения.
     *
     * @var string
     */
    private $readBuffer = '';
    private $pingCallback;
    private $pongCallback;

    /**
     * @inheritDoc
     */
    public function __construct(IoAwareInterface $provider)
    {
        parent::__construct($provider);
        if (
            $provider->getMaxPacketSizeForWriting() > 0
            && $provider->getMaxPacketSizeForWriting() < self::SHORT_PACKET_SIZE_WITH_HEADER
        ) {
            throw new \LogicException(
                'This "' . get_class($provider)
                . '" I/O provider does not allow the transfer of packets of the required size of '
                . self::SHORT_PACKET_SIZE_WITH_HEADER . ' bytes.'
            );
        }
    }

    /**
     * @inheritDoc
     */
    public function returnRead()
    {
        $result = null;

        do {
            // пытаемся прочитать данные

            $readData = $this->provider->read($this->provider->getReadBufferSize(), false);
            if (null !== $readData) {
                // буферизация прочитанных пакетов
                $this->readBuffer .= $readData;
            }
            $bufferSize = strlen($this->readBuffer);
            if ($bufferSize > self::SHORT_HEADER_SIZE) {
                // если что-то можно прочитать в буфере
                // сначала прочитаем флаги нового поступившего пакета
                $flag = unpack('Cflag', substr($this->readBuffer, 0, 1))['flag'];
                if ($flag & self::SHORT_PACKET) {
                    // если пакет является коротким
                    $sizeHead = substr($this->readBuffer, 1, self::SHORT_HEADER_SIZE - 1);
                    $size = unpack('Csize', $sizeHead)['size'];
                    $headerSize = self::SHORT_HEADER_SIZE;
                } else {
                    // если пакет обычный
                    $sizeHead = substr($this->readBuffer, 1, self::HEADER_SIZE - 1);
                    $size = unpack('Nsize', $sizeHead)['size'];
                    $headerSize = self::HEADER_SIZE;
                }
                $size += 1; // добавляем 1, т.к. счёт размера данных начинается с 0.
                $fullPacketSize = $headerSize + $size;
                if ($bufferSize < $fullPacketSize) {
                    // если размер буфера меньше чем кол-во данных, которые необходимо прочитать
                    $needRead = $fullPacketSize - $bufferSize; // сколько данных нужно прочитать
                    // попробуем дочитать необходимое кол-во данных
                    $appendBuffer = $this->provider->read($needRead, true);
                    $this->readBuffer .= $appendBuffer;
                    if (strlen($appendBuffer) !== $needRead) {
                        throw new ReadException(
                            sprintf('Not enough length: %d bytes', $needRead - strlen($appendBuffer)),
                            ReadException::ERROR_FAIL
                        );
                    }
                }
                // прочитаем данные пакета из буфера чтения с отступом в $headerSize байт
                $data = substr($this->readBuffer, $headerSize, $size);

                // сбросим буфер чтения
                $this->flushReadBuffer($fullPacketSize);

                // распакуем данные
                $result = $this->unpack($data, $flag);
                if (null === $result) {
                    // если не удалось распаковать - исключение
                    throw new SendException('Data packet is corrupted.');
                } elseif ($result instanceof PingPacket) {
                    if (!$result->isResponse()) {
                        if (!$this->send(PingPacket::response($result->getValue()))) {
                            throw new SendException('Cannot send pong packet.');
                        }
                        $this->pingReceived($result);
                    } else {
                        $this->pongReceived($result);
                    }
                    $result = null;
                }
            }
        } while (false); // цикл только для использования continue;

        return $result;
    }

    /**
     * Сброс буфера чтения.
     *
     * @param int $flushSize Размер данных для сброса
     *
     * @return void
     */
    private function flushReadBuffer(int $flushSize)
    {
        $bufferSize = strlen($this->readBuffer);
        if ($flushSize === $bufferSize) {
            $this->readBuffer = '';
        } else {
            $this->readBuffer = substr(
                $this->readBuffer,
                $flushSize,
                $bufferSize - $flushSize
            );
        }
    }

    /**
     * Распаковывает принятые из сокета данные.
     * Возвращает null если данные не были распакованы по неизвестным причинам.
     *
     * @param string $raw
     * @param int $flag
     *
     * @return mixed
     * @throws \InvalidArgumentException
     */
    private function unpack(string $raw, int $flag)
    {
        $data = null;
        if ($flag & self::DATA_STRING) {
            $data = $raw;
        } elseif ($flag & self::DATA_INT) {
            $data = (int)$raw;
        } elseif ($flag & self::DATA_FLOAT) {
            $data = (float)$raw;
        } elseif ($flag & self::DATA_ARRAY) {
            $data = json_decode($raw, JSON_OBJECT_AS_ARRAY);
        } elseif ($flag & self::DATA_OBJECT) {
            $data = unserialize($raw);
        } else {
            throw new \InvalidArgumentException('Invalid data type.');
        }
        return $data;
    }

    /**
     * @inheritdoc
     */
    public function send($data): bool
    {
        if (!$this->provider->send($this->pack($data))) {
            return false;
        }
        return true;
    }

    /**
     * Пакует данные в пакеты, и возвращает массив пакетов,
     * которые можно отправлять в любом порядке.
     *
     * @param $data
     *
     * @return string
     * @throws SendException
     */
    private function pack($data): string
    {
        $flag = $this->flagChoice(gettype($data));
        if ($flag & self::DATA_OBJECT) {
            $data = serialize($data);
        } elseif ($flag & self::DATA_ARRAY) {
            $data = json_encode($data);
        }
        $size = strlen($data);
        if ($size > self::PACKET_MAX_SIZE_WITH_HEADER) {
            throw new SendException('Large size of data to send! Please break it into your code.');
        }
        $format = 'CNa*';
        if ($size <= self::SHORT_PACKET_SIZE) {
            $format = 'CCa*';
            $flag |= self::SHORT_PACKET;
        }
        return pack($format, $flag, $size - 1, $data);
    }

    /**
     * Выбирает флаг соотетствующий типу данных.
     *
     * @param string $dataType
     *
     * @return int
     * @throws SendException
     */
    private function flagChoice(string $dataType): int
    {
        switch ($dataType) {
            case 'boolean':
                throw new SendException('Boolean data type cannot be transmitted.');
            case 'integer':
                $flag = self::DATA_INT;
                break;
            case 'double':
                $flag = self::DATA_FLOAT;
                break;
            case 'array':
                $flag = self::DATA_ARRAY;
                break;
            case 'object':
                $flag = self::DATA_OBJECT;
                break;
            case 'resource':
                throw new SendException('Values of type Resource cannot be transmitted on current Net version.');
            case 'NULL':
                throw new SendException('Null data type cannot be transmitted.');
            case 'unknown type':
                throw new SendException('Values of Unknown type cannot be transmitted on current Net version.');
            default:
                $flag = self::DATA_STRING;
        }
        return $flag;
    }

    private function pingReceived(PingPacket $ping): void
    {
        if (null !== $this->pingCallback) {
            call_user_func($this->pingCallback, $ping);
        }
    }

    private function pongReceived(PingPacket $pong): void
    {
        if (null !== $this->pongCallback) {
            call_user_func($this->pongCallback, $pong);
            $this->pongCallback = null;
        }
    }

    /**
     * @inheritDoc
     */
    public function onReceive(callable $callback): CallbackEventListener
    {
        return $this->eventReceive->attachCallbackListener($callback);
    }

    /**
     * @inheritdoc
     */
    public function ping(PingPacket $pingPacket): void
    {
        $this->send($pingPacket);
    }

    /**
     * @inheritdoc
     */
    public function onPingReceived(callable $pingReceived): void
    {
        $this->pingCallback = $pingReceived;
    }

    /**
     * @inheritdoc
     */
    public function pong(callable $pongReceived): void
    {
        $this->pongCallback = $pongReceived;
    }
}


<?php
namespace app\manage\controller;

use think\Config;
use think\Url;
use cms\Captcha;
use think\Request;
use app\manage\logic\LoginLogic;

class Start extends Base
{

    /**
     * 后台登录
     *
     * @var unknown
     */
    const LOGIN_KEY = 'manage_login';

    /**
     * 登录页面
     */
    public function login()
    {
        $this->site_title = '欢迎使用';

        $login_url = Url::build('start/doLogin');
        $this->assign('login_url', $login_url);

        $code_url = Captcha::getCodeSrc(self::LOGIN_KEY);
        $this->assign('code_url', $code_url);

        return $this->fetch();
    }

    /**
     * 登录验证
     *
     * @param Request $request
     */
    public function doLogin(Request $request)
    {
        $verify_code = $request->param('verify_code');
        if (! Config::get('app_debug') && ! Captcha::checkCode($verify_code, self::LOGIN_KEY)) {
            return $this->error('验证码错误');
        }

        $user_name = $request->param('user_name');
        $user_pass = $request->param('user_passwd');
        $res = LoginLogic::doLogin($user_name, $user_pass);
        return $this->jump($res['code'], $res['msg'], $res['data']);
    }

    /**
     * 退出登录
     *
     * @return mixed
     */
    public function logout()
    {
        LoginLogic::loginOut();

        return $this->success('退出登录成功', Url::build('start/login'));
    }
}


<?php
namespace cascade\components\db;

/**
 * ActiveQuery [[@doctodo class_description:cascade\components\db\ActiveQuery]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class ActiveQuery extends \canis\db\ActiveQuery
{
    /**
     * [[@doctodo method_description:andWhereFromQuery]].
     *
     * @param [[@doctodo param_type:instructions]] $instructions [[@doctodo param_description:instructions]]
     *
     * @return [[@doctodo return_type:andWhereFromQuery]] [[@doctodo return_description:andWhereFromQuery]]
     */
    public function andWhereFromQuery($instructions)
    {
        $where = $this->buildWhereFromQuery($instructions);
        if (!$where) {
            return false;
        }
        $this->andWhere($where);

        return true;
    }

    /**
     * [[@doctodo method_description:buildWhereFromQuery]].
     *
     * @param [[@doctodo param_type:instructions]] $instructions [[@doctodo param_description:instructions]]
     *
     * @return [[@doctodo return_type:buildWhereFromQuery]] [[@doctodo return_description:buildWhereFromQuery]]
     */
    public function buildWhereFromQuery($instructions)
    {
        $where = [];
        if (!isset($instructions['condition'])
            || !in_array($instructions['condition'], ['AND', 'OR'])) {
            return false;
        }
        $where[] = $instructions['condition'];
        foreach ($instructions['rules'] as $rule) {
            $parsedRule = $this->parseRule($rule);
            if ($parsedRule) {
                $where[] = $parsedRule;
            }
        }

        return $where;
    }

    /**
     * [[@doctodo method_description:parseRule]].
     *
     * @param [[@doctodo param_type:rule]] $rule [[@doctodo param_description:rule]]
     *
     * @return [[@doctodo return_type:parseRule]] [[@doctodo return_description:parseRule]]
     */
    protected function parseRule($rule)
    {
        if (isset($rule['condition'])) {
            return $this->buildWhereFromQuery($rule);
        }
        if (!isset($rule['field']) || !isset($rule['operator'])) {
            return false;
        }
        if (!isset($rule['value'])) {
            $rule['value'] = null;
        }
        $modelClass = $this->modelClass;
        $dummyModel = new $modelClass();
        if ($dummyModel->hasAttribute($rule['field'])) {
            return $this->buildLogic($rule['field'], $rule['operator'], $rule['value']);
        } else {
            \d($rule);
            exit;
        }
    }

    /**
     * [[@doctodo method_description:buildLogic]].
     *
     * @param [[@doctodo param_type:field]]    $field    [[@doctodo param_description:field]]
     * @param [[@doctodo param_type:operator]] $operator [[@doctodo param_description:operator]]
     * @param [[@doctodo param_type:value]]    $value    [[@doctodo param_description:value]] [optional]
     *
     * @return [[@doctodo return_type:buildLogic]] [[@doctodo return_description:buildLogic]]
     */
    protected function buildLogic($field, $operator, $value = null)
    {
        $operatorMap = [
            'equal' => '=',
            'not_equal' => '!=',
            'less' => '<',
            'less_or_equal' => '<=',
            'greater' => '>',
            'greater_or_equal' => '>=',

        ];
        switch ($operator) {
            case 'equal':
                return ['or like', $field, $value, false];
            break;
            case 'not_equal':
                return ['or not like', $field, $value, false];
            break;
            case 'begins_with':
                return ['like', $field, $value . '%', false];
            break;
            case 'not_begins_with':
                return ['not like', $field, $value . '%', false];
            break;
            case 'contains':
                return ['like', $field, '%' . $value . '%', false];
            case 'not_contains':
                return ['not like', $field, '%' . $value . '%', false];
            break;
            case 'ends_with':
                return ['like', $field, '%' . $value, false];
            break;
            case 'not_ends_with':
                return ['not like', $field, '%' . $value, false];
            break;
            case 'less':
            case 'less_or_equal':
            case 'greater':
            case 'greater_or_equal':
                $paramName = ':' . md5(serialize([microtime(true), mt_rand(), $value]));
                $this->addParams([$paramName => $value]);

                return $field . $operatorMap[$operator] . $paramName;
            break;
            case 'in':
                $value = strtr($value, ', ', ',');

                return $this->buildLogic($field, 'equal', explode(",", $value));
            break;
            case 'not_in':
                $value = strtr($value, ', ', ',');

                return $this->buildLogic($field, 'not_equal', explode(",", $value));
            break;
            case 'is_empty':
                return $field . '=""';
            break;
            case 'is_not_empty':
                return $field . '!=""';
            break;
            case 'is_null':
                return $field . ' IS NULL';
            break;
            case 'is_not_null':
                return $field . ' IS NOT NULL';
            break;
        }

        return false;
    }

    /**
     * [[@doctodo method_description:buildContainsQuery]].
     *
     * @param [[@doctodo param_type:queryString]] $queryString [[@doctodo param_description:queryString]]
     *
     * @return [[@doctodo return_type:buildContainsQuery]] [[@doctodo return_description:buildContainsQuery]]
     */
    public function buildContainsQuery($queryString)
    {
        $queryString = trim($queryString);
        if (empty($queryString)) {
            return [];
        }
        $modelClass = $this->modelClass;
        $queryTerms = $modelClass::prepareSearchTerms($queryString);
        $searchFields = $modelClass::parseSearchFields($modelClass::searchFields());
        $localSearchFieldsRaw = $searchFields['local'];
        $localSearchFields = [];
        foreach ($localSearchFieldsRaw as $fieldGroup) {
            $localSearchFields = array_merge($localSearchFields, $fieldGroup);
        }
        $method = 'single';
        if ($method === 'group') {
            $query = ['condition' => 'AND', 'rules' => []];
            foreach ($queryTerms as $queryTerm) {
                $subquery = ['condition' => 'OR', 'rules' => []];
                foreach ($localSearchFields as $searchField) {
                    $subquery['rules'][] = [
                        'field' => $searchField,
                        'operator' => 'contains',
                        'value' => $queryTerm,
                    ];
                }
                $query['rules'][] = $subquery;
            }
        } else {
            $query = ['condition' => 'OR', 'rules' => []];
            foreach ($queryTerms as $queryTerm) {
                foreach ($localSearchFields as $searchField) {
                    $query['rules'][] = [
                        'field' => $searchField,
                        'operator' => 'contains',
                        'value' => $queryTerm,
                    ];
                }
            }
        }

        return $query;
    }
}


<?php

/**
 * Jin Framework
 * Diatem
 */

namespace Jin2\Log;

/**
 * Boite d'analyse des performances
 */
class PerfAnalyser
{

  /**
   * @var array ableau des points de contrôle enregistrés
   */
  protected $points = array();

  /**
   * Constructeur (instancie un premier point de contrôle, débute l'analyse)
   */
  public function __construct()
  {
    $this->_addPoint('[START]');
  }

  /**
   * Ajoute un point de contrôle sur lequel analyser le temps écoulé depuis l'instanciation de la classe
   */
  public function addPoint()
  {
    $this->_addPoint();
  }

  /**
   * Ajoute techniquement le point de contrôle
   *
   * @param  string  $entete (optional) En-tête affiché ('[POINT]' par défaut)
   */
  protected function _addPoint($entete = '[POINT]')
  {
    $trace = debug_backtrace();
    $time = round(microtime(true) * 1000);
    if (count($this->points) == 0) {
      $elapsed = 0;
    } else {
      $elapsed = $time - $this->points[0]['time'];
    }
    $point = array(
      'time' => $time,
      'entete' => $entete,
      'contexte' => $trace[1]['file'] . ' ligne ' . $trace[1]['line'],
      'elapsed' => $elapsed
    );
    $this->points[] = $point;
  }

  /**
   * Génère et affiche un rapport de performances. (Ajoute un dernier point de contrôle qui clôt l'analyse)
   *
   * @param string $titre  (optional) Titre du rapport ('Rapport de performance' par défaut)
   */
  public function renderTimeReport($titre = 'Rapport de performance')
  {
    if (Debug::getEnabled() || Config::get('reportTimeEnabled')) {
      $this->_addPoint('[STOP]');
      $diff = $this->points[count($this->points) - 1]['time'] - $this->points[0]['time'];

      $dump = '';

      $c = count($this->points);
      for ($i = 0; $i < $c; $i++) {
        $dump .= sprintf(
          '
%s %s :: %s ms
',
          $this->points[$i]['entete'],
          $this->points[$i]['contexte'],
          $this->points[$i]['elapsed']
        );
      }

      $dump .= sprintf(
        '
TOTAL : %s ms
',
        $diff
      );

      print Debug::getCustomTrace($titre, array(array('name' => 'Points d\'analyse', 'content' => $dump)));
    }
  }

  /**
   * Retourne le temps total d'execution en milisecondes
   *
   * @return integer
   */
  public function getTotalTimeInMS()
  {
    return $this->points[count($this->points) - 1]['time'] - $this->points[0]['time'];
  }

}


<?php

abstract class SDIS62_Model_Proxy_Abstract implements SDIS62_Model_Interface_Abstract
{
    /**
     * @var SDIS62_Model_Abstract|null
     */
    protected $entity;

    /**
     * Récupération de l'entité
     * Si l'entité n'est pas déjà explicité, on la charge d'après le nom du proxy
     *
     * @return SDIS62_Model_Abstract
     */
	public function getEntity()
	{
        // Si l'entité n'est pas explicitement determinée, on la devine d'après le nom du proxy
		if($this->entity === null)
		{
            $name_of_entity_class = str_replace("Proxy_", "", get_class($this));
			$this->setEntity(new $name_of_entity_class);
		}

		return $this->entity;
	}

    /**
     * Définition de l'entité utilisée par le proxy en la préparant au 'lazy load'
     *
     * @param SDIS62_Model_Abstract
     * @return SDIS62_Model_Proxy_Abstract Interface fluide
     */
	protected function setEntity(&$entity)
	{
		$this->entity = $entity;

        // On récupère les valeurs de l'entité
        $data = $this->getEntity()->extract();

        // On enlève les id
        unset($data["id"]);

        // On filtre les valeurs nulles avec un alias :undefined:
        array_walk($data, function(&$var) {
            if($var === null)
            {
                $var = ":undefined:";
            }
        });

        // On transforme les entités liées en proxy
        array_walk_recursive($data, function(&$item, $key) {
            if($key === "classname")
            {
                $item = str_replace("", "Proxy_", $item);
            }
        });

        // On hydrate l'entité avec ces nouvelles valeurs
        $this->getEntity()->hydrate($data);

		return $this;
	}

    /**
     * Constructeur (et hydratation de l'entité si le $data est fourni)
     *
     * @param array $data Optionnel
     */
    public function __construct($data = array())
    {
        $this->getEntity()->hydrate($data);
    }

    /**
     * Récupération de l'id de l'entité
     *
     * @return int|string|null
     */
    public function getId()
    {
        return $this->getEntity()->getId();
    }

    /**
     * Définition de l'id de l'entité
     *
     * @param int|string|null
     * @return SDIS62_Model_Proxy_Abstract Interface fluide
     * @throws Zend_Exception Si l'id de l'entité est déjà spécifié (prévention d'une modification de l'identifiant)
     */
    public function setId($id)
    {
        $this->getEntity()->setId($id);
        return $this;
    }

    /**
     * Chargement complet forcé de l'entité
     *
     * @return SDIS62_Model_Proxy_Abstract Interface fluide
     */
    public function forceFullLoad()
    {
        $methods = get_class_methods($this);

        foreach($methods as $method)
        {
            if(substr($method, 0, 3) === "get")
            {
                $this->$method();
            }
        }

        return $this;
    }

    /**
     * Extraction de l'entité en un tableau de données
     *
     * @return array
     */
    public function extract()
    {
        // On charge complètement l'objet
        $this->forceFullLoad();

        // On lance l'extract de l'entité
        $data = $this->getEntity()->extract();

        // On annule l'alias de la valeur null
        array_walk($data, function(&$var) {
            if($var === ":undefined:")
            {
                $var = null;
            }
        });

        // On retourne les datas
        return $data;
    }

    /**
     * Extraction de l'entité dans l'état actuel (l'entité étant lié par le proxy, et donc le lazy load, elle n'est peut être pas entièrement chargée)
     *
     * @return array
     */
    public function extractWithoutForceFullLoad()
    {
        // On lance l'extract de l'entité
        $data = $this->getEntity()->extract();

        // On annule l'alias de la valeur null
        array_walk($data, function(&$var) {
            if($var === ":undefined:")
            {
                $var = null;
            }
        });

        // On retourne les datas
        return $data;
    }

    /**
     * Hydratation (remplissage) de l'entité à partir d'un tableau de données
     *
     * @return SDIS62_Model_Proxy_Abstract Interface fluide
     */
    public function hydrate(array $data)
    {
        array_walk_recursive($data, function(&$item, $key) {
            if($key === "classname")
            {
                $item = str_replace("", "Proxy_", $item);
            }
        });

        return $this->getEntity()->hydrate($data);
    }

    /**
     * Contrôle si une valeur devant être retournée a été préalablement chargée ou pas
     *
     * @param string $method
     * @param array $args Optionnel
     * @return boolean
     */
    public function isNotLoaded($method, array $args = array())
    {
        $value = call_user_func_array(array($this->getEntity(), $method), $args);
        return $value === ':undefined:' && $this->getId() !== null;
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\web\widgets\decorator;

use canis\helpers\Html;

/**
 * Decorator [[@doctodo class_description:cascade\components\web\widgets\decorator\Decorator]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class Decorator extends \yii\base\Behavior implements DecoratorInterface
{
    /**
     * [[@doctodo method_description:generateStart]].
     *
     * @return [[@doctodo return_type:generateStart]] [[@doctodo return_description:generateStart]]
     */
    public function generateStart()
    {
        $parts = [];
        foreach ($this->owner->widgetClasses as $class) {
            Html::addCssClass($this->owner->htmlOptions, $class);
        }
        $parts[] = Html::beginTag('div', $this->owner->htmlOptions);

        return implode("", $parts);
    }

    /**
     * [[@doctodo method_description:generateEnd]].
     *
     * @return [[@doctodo return_type:generateEnd]] [[@doctodo return_description:generateEnd]]
     */
    public function generateEnd()
    {
        $parts = [];
        $parts[] = Html::endTag('div'); // panel

        return implode("", $parts);
    }

    /**
     * Get widget classes.
     *
     * @return [[@doctodo return_type:getWidgetClasses]] [[@doctodo return_description:getWidgetClasses]]
     */
    public function getWidgetClasses()
    {
        return [];
    }
}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\BonusHybrid\Repo\Dao;

use Praxigento\BonusHybrid\Repo\Data\Downline as Entity;

class Downline
    extends \Praxigento\Core\App\Repo\Dao
{
    public function __construct(
        \Magento\Framework\App\ResourceConnection $resource,
        \Praxigento\Core\Api\App\Repo\Generic $daoGeneric
    )
    {
        parent::__construct(
            $resource,
            $daoGeneric,
            Entity::class
        );
    }

    /**
     * Get downline tree by calculation ID.
     *
     * @param int $calcId
     * @return \Praxigento\BonusHybrid\Repo\Data\Downline[]
     */
    public function getByCalcId($calcId)
    {
        $where = Entity::A_CALC_REF . '=' . (int)$calcId;
        $result = $this->get($where);
        return $result;
    }

    /**
     * Get entry by unique key (calcId & custId).
     *
     * @param int $calcId
     * @param int $custId
     * @return \Praxigento\BonusHybrid\Repo\Data\Downline|null
     */
    public function getByKeyCalcCust($calcId, $custId)
    {
        $byCalc = Entity::A_CALC_REF . '=' . (int)$calcId;
        $byCust = Entity::A_CUST_REF . '=' . (int)$custId;
        $where = "($byCalc) AND ($byCust)";
        $rs = $this->get($where);
        $result = (is_array($rs)) ? reset($rs) : null;
        return $result;
    }
}


<?php
namespace HtSettingsModule\Mapper;

use ZfcBase\Mapper\AbstractDbMapper;
use HtSettingsModule\Entity\ParameterInterface;
use HtSettingsModule\Entity\IdAwareParameterInterface;
use HtSettingsModule\Exception;

class DbSettingsMapper extends AbstractDbMapper implements SettingsMapperInterface
{
    /**
     * {@inheritDoc}
     */
    public function findByNamespace($namespace)
    {
        $select = $this->getSelect();
        $select->where(['namespace' => $namespace]);
        $resultSet = $this->select($select);

        return iterator_to_array($resultSet);
    }

    /**
     * {@inheritDoc}
     */
    public function insertParameter(ParameterInterface $parameter)
    {
        $result = $this->insert($parameter);
        if ($parameter instanceof IdAwareParameterInterface) {
            $parameter->setId($result->getGeneratedValue());
        }
    }

    /**
     * {@inheritDoc}
     */
    public function updateParameter(ParameterInterface $parameter)
    {
        $where = $this->getWhereFromParameter($parameter);
        $this->update($parameter, $where);
    }

    /**
     * {@inheritDoc}
     */
    public function deleteParameter(ParameterInterface $parameter)
    {
        $where = $this->getWhereFromParameter($parameter);
        $this->delete($where);
    }

    /**
     * {@inheritDoc}
     */
    public function findParameter($parameter, $name = null)
    {
        if ($parameter instanceof ParameterInterface) {
            $where = $this->getWhereFromParameter($parameter);
        } elseif (is_string($parameter)) {
            $namespace = $parameter;
            $where = ['namespace' => $namespace, 'name' => $name];
        } else {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    '%s expects parameter 1 to be string or an instance of HtSettingsModule\Entity\ParameterInterface, %s provided instead',
                    __METHOD__,
                    is_object($parameter) ? get_class($parameter) : gettype($parameter)
                )
            );
        }
        $select = $this->getSelect();
        $select->where($where);

        return $this->select($select);
    }

    /**
     * Gets where condition of select, update or delete a parameter
     *
     * @param  ParameterInterface $parameter
     * @return array
     */
    protected function getWhereFromParameter(ParameterInterface $parameter)
    {
        if ($parameter instanceof IdAwareParameterInterface && $parameter->getId()) {
            return ['id' => $parameter->getId()];
        } else {
            return ['namespace' => $parameter->getNamespace(), 'name' => $parameter->getName()];
        }
    }

    /**
     * Sets table name of settings
     *
     * @param  string|\Zend\Db\Sql\TableIdentifier $tableName
     * @return self
     */
    public function setTableName($tableName)
    {
        $this->tableName = $tableName;

        return $this;
    }
}