<?php

namespace Dothiv\Bundle\ContentfulBundle\Service;

use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class WebhookUserService implements UserProviderInterface
{
    /**
     * @var array
     */
    private $config;

    /**
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->config = $config;
    }

    /**
     * {@inheritdoc}
     */
    public function loadUserByUsername($username)
    {
        if ($username != $this->config['httpBasicUsername']) {
            throw new UsernameNotFoundException();
        }
        return new WebhookUser($this->config['httpBasicUsername'], $this->config['httpBasicPassword']);
    }

    /**
     * {@inheritdoc}
     */
    public function refreshUser(UserInterface $user)
    {
        return $user;
    }

    /**
     * {@inheritdoc}
     */
    public function supportsClass($class)
    {
        return $class === 'Dothiv\Bundle\ContentfulBundle\Service\WebhookUser';
    }
}


<?php
/**
 * CoolMS2 User Module (http://www.coolms.com/)
 *
 * @link      http://github.com/coolms/user for the canonical source repository
 * @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
 * @license   http://www.coolms.com/license/new-bsd New BSD License
 * @author    Dmitry Popov <d.popov@altgraphic.com>
 */

namespace CmsUser\Mvc\Controller;

use Zend\Form\ElementInterface,
    Zend\Mvc\Controller\AbstractActionController,
    Zend\Stdlib\Parameters,
    Zend\Stdlib\ResponseInterface,
    Zend\View\Model\ViewModel,
    CmsCommon\Stdlib\OptionsProviderTrait,
    CmsUser\Options\ControllerOptionsInterface,
    CmsUser\Service\UserServiceAwareTrait,
    CmsUser\Service\UserServiceInterface;

/**
 * Registration controller
 *
 * @method IndexController setOptions(\CmsUser\Options\ControllerOptionsInterface $options)
 * @method \CmsUser\Options\ControllerOptionsInterface getOptions()
 * @method \CmsAuthentication\Mvc\Controller\Plugin\Authentication cmsAuthentication()
 */
class RegistrationController extends AbstractActionController
{
    use UserServiceAwareTrait,
        OptionsProviderTrait;

    /**
     * @var string
     */
    protected $registrationNamespace = 'cms-user-registration';

    /**
     * @var ElementInterface
     */
    protected $identityElement;

    /**
     * @var ElementInterface
     */
    protected $credentialElement;

    /**
     * __construct
     *
     * @param UserServiceInterface $userService
     * @param ControllerOptionsInterface $options
     * @param ElementInterface $identityElement
     * @param ElementInterface $credentialElement
     */
    public function __construct(
        UserServiceInterface $userService,
        ControllerOptionsInterface $options,
        ElementInterface $identityElement = null,
        ElementInterface $credentialElement = null
    ) {
        $this->setUserService($userService);
        $this->setOptions($options);
        $this->identityElement = $identityElement;
        $this->credentialElement = $credentialElement;
    }

    /**
     * Register index action
     *
     * Displays user registration form
     *
     * @return ResponseInterface|ViewModel
     */
    public function indexAction()
    {
        $authPlugin = $this->cmsAuthentication();

        // if the user is logged in, we don't need to register
        if ($authPlugin->hasIdentity()) {
            // redirect to the default user route
            $route = $this->getOptions()->getDefaultUserRoute();
            if (is_callable($route)) {
                $route = $route($authPlugin->getIdentity());
            }

            return $this->redirect()->toRoute($route);
        }

        // if registration is disabled
        if (!($enableRegistration = $this->getOptions()->getEnableRegistration())) {
            return new ViewModel(compact('enableRegistration'));
        }

        if ($this->getOptions()->getUseRegistrationRedirectParameter()) {
            $redirect = $this->params()->fromQuery('redirect', false);
        } else {
            $redirect = false;
        }

        $url = $this->url()->fromRoute(null, [],
            $redirect ? ['query' => ['redirect' => rawurldecode($redirect)]] : []
        );

        $prg = $this->prg($url, true);
        // Return early if prg plugin returned a response
        if ($prg instanceof ResponseInterface) {
            return $prg;
        }

        $post = $prg;

        $this->flashMessenger()->setNamespace($this->registrationNamespace)->clearCurrentMessages();

        $form = $this->getUserService()->getRegisterForm();
        $form->setAttribute('action', $this->url()->fromRoute());
        if ($redirect && $form->has('redirect')) {
            $form->get('redirect')->setValue($redirect);
        }

        if ($post && $form->setData($post)->isValid()) {

            $redirect = empty($post['redirect']) ? $redirect : $post['redirect'];

            $identity = $this->getUserService()->register($post);

            // Return early if an user service returned a response
            if ($identity instanceof ResponseInterface) {
                return $identity;
            } elseif ($identity) { // We are registered

                if ($this->identityElement && $this->credentialElement
                    && $this->getOptions()->getLoginAfterRegistration()
                ) {
                    // Create authentication data
                    $identityFields = $this->getOptions()->getIdentityFields();
                    if ($this->getOptions()->getEnableUsername()) {
                        $post[$this->identityElement->getName()] = $identity->getEmail();
                    } elseif (in_array('username', $identityFields)) {
                        $post[$this->identityElement->getName()] = $identity->getUsername();
                    }
                    $post[$this->credentialElement->getName()] = $post['password'];
                    if ($redirect) {
                        $post['redirect'] = $redirect;
                    }

                    $this->flashMessenger()->addSuccessMessage($this->translate(
                        'Congratulations! You have successfully registered. ' .
                        'Please, check your inbox to confirm your email address ' .
                        'and to complete registration.'
                    , 'CmsUser'));

                    $this->getRequest()->setPost(new Parameters($post));
                    return $this->forward()->dispatch(
                        $this->getOptions()->getAuthenticationController(),
                        ['action' => 'authenticate']
                    );
                }

                if ($redirect) {
                    return $this->redirect()->toUrl($redirect);
                }

                // redirect to the default user route
                $route = $this->getOptions()->getDefaultUserRoute();
                if (is_callable($route)) {
                    $route = $route($authPlugin->getIdentity());
                }

                return $this->redirect()->toRoute($route);
            }
        }

        return new ViewModel(compact('enableRegistration', 'form'));
    }
}


<?php
namespace Devedge\XmlRpc\Client;

class XmlRpcParser extends \Devedge\XmlRpc\Common\XmlRpcParser
{
    /**
     * Convert an XMLRPC Fault in an Exception
     * @param \SimpleXMLElement $fault
     * @return \Exception
     */
    public static function parseFault(\SimpleXMLElement $fault)
    {
        $faultData = static::parseStruct($fault->value->struct);
        return new \Devedge\XmlRpc\Client\RemoteException($faultData['faultString'], $faultData['faultCode']);
    }
}


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

namespace RedKiteCms\Content\BlockManager;

use RedKiteCms\Bridge\Dispatcher\Dispatcher;
use RedKiteCms\Bridge\Monolog\DataLogger;
use RedKiteCms\EventSystem\BlockEvents;
use RedKiteCms\EventSystem\Event\Block\BlockRemovedEvent;
use RedKiteCms\EventSystem\Event\Block\BlockRemovingEvent;
use RedKiteCms\Tools\FilesystemTools;
use RedKiteCms\Tools\JsonTools;

/**
 * Class BlockManagerRemove is the object assigned to remove a block froma slot
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\BlockManager
 */
class BlockManagerRemove extends BlockManager
{
    /**
     * Removes the block from the given slot
     *
     * @param $sourceDir
     * @param array $options
     * @param $username
     */
    public function remove($sourceDir, array $options, $username)
    {
        $dir = $this
            ->init($sourceDir, $options, $username)
            ->getDirInUse();

        $blockName = $options["blockname"];
        $blocksDir = $dir . '/blocks';
        $filename = sprintf('%s/%s.json', $blocksDir, $blockName);
        $options["block"] = JsonTools::jsonDecode(FilesystemTools::readFile($filename));
        Dispatcher::dispatch(BlockEvents::BLOCK_REMOVING, new BlockRemovingEvent($this->serializer, $filename));

        $this->filesystem->remove($filename);
        $this->removeBlockFromSlotFile($options, $dir);

        Dispatcher::dispatch(BlockEvents::BLOCK_REMOVED, new BlockRemovedEvent($this->serializer, $filename));
        DataLogger::log(
            sprintf(
                'Block "%s" has been removed from the "%s" slot on page "%s" for the "%s_%s" language',
                $options["blockname"],
                $options["slot"],
                $options["page"],
                $options["language"],
                $options["country"]
            )
        );
    }
}


<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Predis\Command;

/**
 * Base class used to implement an higher level abstraction for commands based
 * on Lua scripting with EVAL and EVALSHA.
 *
 * @link http://redis.io/commands/eval
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
abstract class ScriptCommand extends Command
{
    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return 'EVALSHA';
    }

    /**
     * Gets the body of a Lua script.
     *
     * @return string
     */
    abstract public function getScript();

    /**
     * Calculates the SHA1 hash of the body of the script.
     *
     * @return string SHA1 hash.
     */
    public function getScriptHash()
    {
        return sha1($this->getScript());
    }

    /**
     * Specifies the number of arguments that should be considered as keys.
     *
     * The default behaviour for the base class is to return 0 to indicate that
     * all the elements of the arguments array should be considered as keys, but
     * subclasses can enforce a static number of keys.
     *
     * @return int
     */
    protected function getKeysCount()
    {
        return 0;
    }

    /**
     * Returns the elements from the arguments that are identified as keys.
     *
     * @return array
     */
    public function getKeys()
    {
        return array_slice($this->getArguments(), 2, $this->getKeysCount());
    }

    /**
     * {@inheritdoc}
     */
    public function setArguments(array $arguments)
    {
        if (($numkeys = $this->getKeysCount()) && $numkeys < 0) {
            $numkeys = count($arguments) + $numkeys;
        }

        $arguments = array_merge(array($this->getScriptHash(), (int) $numkeys), $arguments);

        parent::setArguments($arguments);
    }

    /**
     * Returns arguments for EVAL command.
     *
     * @return array
     */
    public function getEvalArguments()
    {
        $arguments = $this->getArguments();
        $arguments[0] = $this->getScript();

        return $arguments;
    }

    /**
     * Returns the equivalent EVAL command as a raw command instance.
     *
     * @return RawCommand
     */
    public function getEvalCommand()
    {
        return new RawCommand('EVAL', $this->getEvalArguments());
    }
}


<?php

/*
 * Chill is a software for social workers
 *
 * Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
 * <http://www.champs-libres.coop>, <info@champs-libres.coop>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace Chill\CustomFieldsBundle\Service;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Receive all the services tagged with 'chill.custom_field'.
 *
 * The services tagged with 'chill.custom_field' are services used to declare
 * a new custom field type. The tag must contain a 'type' variable (that must
 * be unique), this type is used to identify this custom field in the form
 * declration
 *
 * For example (in services.yml) :
 *  services:
 *      chill.icp2.type:
 *          tags:
 *              - { name: 'chill.custom_field', type: 'ICPC2' }
 *
 * @author Julien Fastré <julien.fastre@champs-libres.coop>
 */
class CustomFieldProvider implements ContainerAwareInterface
{
    /** @var array $servicesByType The services indexes by the type */
    private $servicesByType = array();

    /** @var Container $container The container */
    private $container;

    /**
     * Add a new custom field to the provider
     *
     * @param type $serviceName The name of the service (declared in service.yml)
     * @param type $type The type of the service (that is used in the form to
     * add this type)
     */
    public function addCustomField($serviceName, $type)
    {
        $this->servicesByType[$type] = $serviceName;
    }

    /**
     * Get a custom field stored in the provider. The custom field is identified
     * by its type.
     *
     * @param string $type The type of the wanted service
     * @return CustomFieldInterface
     */
    public function getCustomFieldByType($type)
    {
        if (isset($this->servicesByType[$type])) {
            return $this->servicesByType[$type];
        } else {
            throw new \LogicException('the custom field with type '.$type.' '
                . 'is not found');
        }
    }

    /*
     * (non-PHPdoc)
     * @see \Symfony\Component\DependencyInjection\ContainerAwareInterface::setContainer()
     */
    public function setContainer(ContainerInterface $container = null)
    {
        if ($container === null) {
            throw new \LogicException('container should not be null');
        }

        $this->container = $container;
    }

    /**
     * Get all the custom fields known by the provider
     *
     * @return array Array of the known custom fields indexed by the type.
     */
    public function getAllFields()
    {
        return $this->servicesByType;
    }
}


<?php

/*
 * This file is part of the P13/DateTime package.
 *
 * (c) Wagner Sicca <wssicca@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace p13\datetime;

use \DateTime as OriginalDateTime;

/**
 * Extensão da classe nativa \DateTime
 *
 * @author Wagner Sicca <wssicca@gmail.com>
 * @namespace p13\datetime
 * @package p13\datetime
 */
class DateTime extends OriginalDateTime implements ExtensionInterface
{

    /**
     * Define o formato de data aceito pelo PostgreSQL
     * @const string
     */
    const PGSQL_DATE = 'Y-m-d';

    /**
     * Define o formato de timestamp aceito pelo PostgreSQL
     * @const string
     */
    const PGSQL_DATETIME = 'Y-m-d H:i:s';

    /**
     * Define o formato de hora aceito pelo PostgreSQL
     * @const string
     */
    const PGSQL_TIME = 'H:i:s';

    /**
     * Retorna o objeto Month relativo a esta data
     * @return \p13\datetime\Month
     */
    public function getMonth()
    {
        return new Month($this->format('m'), $this->format('Y'));
    }

    /**
     * Fim de Semana (Rick & Renner)
     *
     * Do jeito que você me olha
     * Você me fascina
     * Eu fico louco pôr você
     * E esse amor me domina
     * Podemos sair pôr aí
     * Fazer um programa legal
     * E o fim de semana curtir
     * Que tal? Que tal?
     * Chega mais perto de mim
     * Mais perto do meu coração
     * Se tudo der certo assim
     * Que bom, que bom
     *
     * Do jeito que você me olha
     * Você não me engana
     * Quem sabe a gente se encontra
     * E a gente se ama
     * Podemos sair pôr aí
     * Fazer um programa legal
     * E o fim de semana curtir
     * Que tal? Que tal?
     * Chega mais perto de mim
     * Mais perto do meu coração
     * Se tudo der certo assim
     * Que bom, que bom
     *
     * @return boolean
     */
    public function isFinalDeSemana()
    {
        return $this->format('N') > 5;
    }

    /**
     * Faz o "cast" de \DateTime para p13\util\datetime\DateTime
     * @param OriginalDateTime $datetime
     * @return DateTime
     */
    public static function cast($datetime)
    {
        return $datetime instanceof self ?
                $datetime :
                new self($datetime->format(self::ISO8601), $datetime->getTimezone());
    }

}


<?php
/**
 * Copyright (c) vdeApps 2018
 */

namespace vdeApps\Import;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\SchemaConfig;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Types\Type;
use Exception;

/**
 * Class AbstractImport
 * @package vdeApps\Import
 *
 *          Import de données dans une table
 *
 *          db: Connection
 *          tablename: nom de la table d'import
 *
 *          headerLikeFirstLine : création des colonnes comme la première ligne du tableau, sinon colonnes par lettres
 *
 */
/*
$imp = (new ImportCsv($this->db))
                            ->fromFile($localFilename)
                            ->setLimit(10)
                            // Destination table
                            ->setTable('import_csv')
                            //Ignore la premiere ligne
                            ->setIgnoreFirstLine(false)
                            // Prend la première ligne comme entête de colonnes
                            ->setHeaderLikeFirstLine(true)
                            // Colonnes personnalisées
//                            ->setFields($customFields)
                            // Ajout de champs supplémentaires
                            ->addFields(['calc_iduser', 'calc_ident'])
                            // Ajout de n colonnes
//                            ->addFields(12)
                            // Ajout d'un plugins
                            ->addPlugins([ImportCsv::class, 'pluginsNullValue'])
                            // Ajout d'un plugins
                            ->addPlugins(function ($rowData) {
                                $rowData['calcIduser'] = 'hack';
                                return $rowData;
                            })
                            // required: Lecture/vérification
                            ->read()
                            // Exec import
                            ->import();
 */

class ImportAbstract implements ImportInterface
{
    /** @var null|Connection $db */
    private $db = null;

    /** @var null|Table */
    private $table = null;
    private $headerLikeFirstLine = false;
    private $limit = 0;
    private $startAt = 0;
    /** @var null|resource */
    private $resource = null;
    private $fromfile = null;
    private $fromdata = null;

    private $ignoreFirstLine = false;
    /** @var null|array $fields */
    private $fields = null;
    private $nbFields = null;

    private $addFields = null;
    /** @var null|array $values */
    private $rows = null;
    private $currentRow = 1;
    private $defaultType = Type::TEXT;

    /** @var null|array $plugins */
    private $plugins = null;

    private $charset = 'utf8_general_ci';

    /**
     * Object Base de données
     * InterfaceImport constructor.
     *
     * @param \Doctrine\DBAL\Connection $db
     */
    public function __construct($db)
    {
        $this->setDb($db);
    }

    /**
     * @param null $db
     *
     * @return $this
     */
    public function setDb($db)
    {
        $this->db = $db;

        return $this;
    }

    /**
     * plugins: Set null values to empty value
     *
     * @param $rowData
     *
     * @return array
     */
    public static function pluginsNullValue($rowData)
    {
        return array_map(function ($v)
        {
            return ($v == '') ? null : $v;
        }, $rowData);
    }

    /**
     * Ajout n champs
     *
     * @param array|integer $mixed : Tableau ou nb de colonnes à ajouter
     *
     * @return $this
     * @throws Exception
     */
    public function addFields($mixed)
    {
        if (!is_numeric($mixed) && !is_array($mixed)) {
            throw new Exception(__FUNCTION__ . " doit être un entier ou un tableau", self::IMPORT_BAD_FORMAT);
            return $this;
        }

        $this->addFields = $mixed;
        return $this;
    }

    public function __destruct()
    {
        $ressource = $this->getResource();
        if (is_resource($ressource)) {
            fclose($ressource);
            $this->setResource(null);
        }
    }

    /**
     * @return null|resource
     */
    public function getResource()
    {
        return $this->resource;
    }

    /*
     * Données lues
     */

    /**
     * Resource contenant les données
     *
     * @param null|resource $resource
     *
     * @return $this
     */
    public function setResource($resource)
    {
        $this->resource = $resource;

        return $this;
    }

    /**
     * Return the number of line to add
     * @return int
     */
    public function getLimit()
    {
        return $this->limit;
    }

    /**
     * number of line to add
     *
     * @param int $limit (optional) default=0 pas de limite
     *
     * @return $this
     */
    public function setLimit($limit = 0)
    {
        $this->limit = $limit;

        return $this;
    }

    /**
     * Lecture d'un fichier
     *
     * @param $localFilename
     *
     * @return $this
     * @throws Exception
     */
    public function fromFile($fromfile)
    {
        if (!file_exists($fromfile)) {
            throw new Exception("Fichier d'import non trouvé: $fromfile", self::IMPORT_FILENOTFOUND);
        }

        $this->fromfile = $fromfile;

        $resource = fopen($fromfile, "r");
        if ($resource === false) {
            throw new Exception("Erreur de lecture de $fromfile", self::IMPORT_READ_ERROR);
        }

        $this->setResource($resource);

        return $this;
    }

    /**
     * Return filename
     * @return null
     */
    public function getFilename()
    {
        return $this->fromfile;
    }

    /**
     * Lecture depuis une chaine
     *
     * @param $string
     *
     * @return $this
     */
    public function fromData($data)
    {
        $this->fromdata = $data;
        $resource = fopen('php://memory', 'r+');
        fwrite($resource, $data);
        rewind($resource);

        //        $resource = fopen('data://text/plain,' . $data, 'r+');
        $this->setResource($resource);

        return $this;
    }

    public function getData()
    {
        return $this->fromdata;
    }

    /**
     * Les valeurs
     *
     * @param array $values
     *
     * @param bool  $ignoreStartAt ignore the startAt, force add values
     *
     * @return bool
     * @throws Exception
     */
    public function addRow($values = [], $forced=false)
    {
        /*
         * Test si fields est déjà rempli
         * et si oui on regarde si le nombre de values correspond au nombre de fields
         */
        if (!is_null($this->getFields())) {
            if ($this->nbFields < count($values)) {
                throw new Exception("Ligne " . $this->currentRow . ": Mauvais nombre de colonnes, attendu: " . $this->nbFields, self::IMPORT_BAD_FORMAT);
                return false;
            }
        }

        // Add the values
        $this->rows[] = $values;

        if ($forced){
            return true;
        }

        $this->currentRow++;

        /*
         * check the limit
         */
        if ($this->getLimit()!=0 and $this->currentRow  + (($this->isheaderLikeFirstLine()===false) ? 1:0)>  $this->getLimit() ){
            return false;
        }

        return true;
    }

    /**
     * @return array|null
     */
    public function getFields()
    {
        return $this->fields;
    }

    /**
     * Désignation des noms de colonnes
     *
     * @param array $fields [colname=>'', type=>'LONGTEXT')
     *
     * @return $this
     */
    public function setFields($fields = [])
    {
        $this->fields = $fields;
        $this->nbFields = count($this->fields);

        /*
         * make array with backquote from create columns
         */
        $this->dbColumns = array_map(function($val){
            return "`$val`";
        }, $fields);

        return $this;
    }

    /**
     * Effectue l'import des données
     * @return $this
     * @throws Exception
     */
    public function import()
    {

        /*
         * Dispatch des données et vérification
         */
        $this->build();

        $this->createTable();

        $this->insertData();

        return $this;
    }

    /**
     * Lecture/Vérification des données values
     * Lire des données et les traiter par setFields et setValues
     * @return mixed
     * @throws Exception
     */
    public function build()
    {
        $tbError = [];

        $this->currentRow = 1;

        /*
         * Supprime la premiere ligne
         */
        if ($this->isIgnoreFirstLine()) {
            $this->currentRow++;
            array_shift($this->rows);
        }

        /*
         * Si aucun champs n'a été défini
         */
        if (is_null($this->getFields())) {
            $this->currentRow++;

            // On prend la première ligne comme nom de colonnes ?
            if ($this->isheaderLikeFirstLine()) {
                if (is_null($this->rows) || count($this->rows) == 0) {
                    throw new Exception("Pas de données à traiter", self::IMPORT_NODATA);
                }
                $firstLine = array_shift($this->rows);
                $this->setFields($firstLine);
            } else {
                /*
                 * Sinon on génère automatiquement les noms de colonnes
                 */
                $firstLine = $this->getRows(0);
                $nbFields = count($firstLine);
                $tbFields = [];
                for ($i = 1; $i <= $nbFields; $i++) {
                    $tbFields[] = self::number2lettre($i);
                }
                $this->setFields($tbFields);
            }
        }

        /**
         * Ajout des colonnes supplémentaires
         */
        if (($addFields = $this->getAddFields())) {
            $tbNewFields = [];
            if (is_array($addFields)) {
                $tbNewFields = array_merge($this->getFields(), $addFields);
            } elseif (is_numeric($addFields)) {
                // Ajout automatique de colonnes
                for ($i = $this->nbFields + 1; $i <= $this->nbFields + $addFields; $i++) {
                    $tbNewFields[] = self::number2lettre($i);
                }

                $tbNewFields = array_merge($this->getFields(), $tbNewFields);
            }
            $this->setFields($tbNewFields);
        }

        /*
         * Sinon on garde ceux qui sont définis et on test
         */
        $nbRows = count($this->getRows());
        for ($i = 0; $i < $nbRows; $i++, ++$this->currentRow) {
            if ($this->nbFields < count($this->getRows($i))) {
                $tbError[] = "Ligne " . $this->currentRow . ": Mauvais nombre de colonnes, attendu: " . $this->nbFields;
            }
        }

        if (count($tbError)) {
            throw new Exception(implode("\n", $tbError), self::IMPORT_BAD_FORMAT);
        }

        /*
         * Create columns
         */
        for ($i=0; $i < count($this->dbColumns); $i++){
            $this->table->addColumn($this->dbColumns[$i], $this->defaultType, ["notnull" => false, "collation" => $this->getCharset()]);
        }

        return $this;
    }

    /**
     * @return bool
     */
    public function isIgnoreFirstLine()
    {
        return $this->ignoreFirstLine;
    }

    /**
     * Test si on doit ignorer la première ligne
     *
     * @param bool $ignoreFirstLine (optional) default=false
     *
     * @return $this
     */
    public function setIgnoreFirstLine($ignoreFirstLine = false)
    {
        $this->ignoreFirstLine = $ignoreFirstLine;

        return $this;
    }

    /**
     * @return bool
     */
    public function isheaderLikeFirstLine()
    {
        return $this->headerLikeFirstLine;
    }

    /**
     * @param bool $headerLikeFirstLine (optional) default=false
     *
     * @return $this
     */
    public function setHeaderLikeFirstLine($headerLikeFirstLine = false)
    {
        $this->headerLikeFirstLine = $headerLikeFirstLine;

        return $this;
    }

    /**
     * Retourne toutes les lignes sous forme de tableau
     *
     * @param null|interger $indice (optional) Retourne la ligne d'indice $indice
     *
     * @return array|null
     * @throws Exception
     */
    public function getRows($indice = null)
    {
        $result = false;
        if (is_null($indice)) {
            $result = $this->rows;
        } elseif (is_numeric($indice) and $indice >= 0) {
            if ($indice <= count($this->rows) - 1) {
                $result = $this->rows[$indice];
            }
        } else {
            throw new Exception("Impossible de lire la première ligne", self::IMPORT_NODATA);
        }

        return $result;
    }

    /**
     * Retourne le code lettre d'après un indice
     * ex: 1->A 2->B 26->Z 27->AA ...
     *
     * @param int $icol
     *
     * @return $string lettres
     */
    public static function number2lettre($icol = 0)
    {
        $letter = '';

        $aCode = 96; //A - 1
        if ($icol <= 0 || $icol > 16384) {    //Trop petit ou trop grand
            $letter = '';
        } elseif ($icol > 702) {
            $letter = chr(((($icol - 1 - 26 - 676) / 676) % 676) + $aCode + 1);
            $letter .= chr(((($icol - 1 - 26) / 26) % 26) + $aCode + 1);
            $letter .= chr((($icol - 1) % 26) + $aCode);
        } elseif ($icol > 26) {
            $letter = chr(((($icol - 1 - 26) / 26) % 26) + $aCode + 1);
            $letter .= chr((($icol - 1) % 26) + $aCode + 1);
        } else {
            $letter = chr($icol + $aCode);
        }

        return strtolower($letter);
    } // No limit

    /**
     * Start at the line for Add
     *
     * @param int $startAt
     *
     * @return $this
     * @throws Exception
     */
    public function startAt($startAt=0){
        if (!is_numeric($startAt) || $startAt < 0){
            throw new Exception("startAt: bad value", 10);
        }
        $this->startAt = $startAt;
        return $this;
    }

    /**
     * @return null
     */
    public function getAddFields()
    {
        return $this->addFields;
    }

    /**
     * @return string
     */
    public function getCharset()
    {
        return $this->charset;
    }

    /**
     * @param string $charset
     *
     * @return $this
     */
    public function setCharset($charset)
    {
        $this->charset = $charset;

        return $this;
    }

    /**
     * Creation de la table
     * @return $this
     * @throws Exception
     */
    private function createTable()
    {
        $tableExists = $this->getDb()->getSchemaManager()->tablesExist([$this->table->getName()]);

        /*
         * Drop and Create
         */
        try {
            if ($tableExists) {
                $this->getDb()->getSchemaManager()->dropAndCreateTable($this->table);
            } else {
                $this->getDb()->getSchemaManager()->createTable($this->table);
            }
        } catch (Exception $ex) {
            throw new Exception("Erreur de création de table: " . $ex->getMessage(), self::IMPORT_BAD_FORMAT);
        }

        return $this;
    }

    /**
     * @return Connection|null
     */
    private function getDb()
    {
        return $this->db;
    }

    /**
     * Insert des données
     * @return $this
     * @throws Exception
     */
    private function insertData()
    {
        /*
         * Parcours de données à insérer
         */
        $nbRows = count($this->rows);
        $nbColumnsToInsert = count($this->getRows(0));

        $blankFields = ($this->nbFields - $nbColumnsToInsert) ? array_fill(0, $this->nbFields - $nbColumnsToInsert, null) : [];

        // On coupe le tableau pour ne garder que les champs nécessaires
        $fieldsToInsert = $this->getFields(); //array_slice($this->getFields(), 0, $nbColumnsToInsert);

        $nbPlugins = count($this->getPlugins());

        for ($i = 0; $i < $nbRows; $i++) {
            /*
             * Valeurs lues
             */
            $row = $this->getRows($i);

            /*
             * Ajout des champs supplémentaires
             */
            $row = array_merge_recursive($row, $blankFields);

            /*
             * Creation du tableau associatif pour les plugins
             */
            $values = array_combine($fieldsToInsert, $row);

            /*
             * Application des plugins
             */
            for ($ip = 0; $ip < $nbPlugins; $ip++) {
                $callable = $this->getPlugins($ip);
                if (is_callable($callable)) {
                    $values = call_user_func($callable, $values);
                }
            }

            /*
             * Rewrite array with blackquote
             */
            $valuesToInsert = [];
            foreach ($values as $key => $value) {
                $valuesToInsert["`$key`"] = $value;
            }

            try {
                $this->db->insert($this->getTable()->getName(), $valuesToInsert);
            } catch (Exception $ex) {
                throw new Exception("Erreur d'insertion dans la base, merci de vérifier l'affectation des valeurs dans les colonnes", self::IMPORT_BAD_FORMAT);
            }
        }

        return $this;
    }

    /**
     * Retourne la liste des plugins à appliquer
     *
     * @param null $indice
     *
     * @return null|array
     * @throws Exception
     */
    public function getPlugins($indice = null)
    {
        if (is_numeric($indice)) {
            if ($indice > count($this->plugins) - 1) {
                throw new Exception("Plugins d'indice $indice introuvable", self::IMPORT_NODATA);
            }

            return $this->plugins[$indice];
        }

        return $this->plugins;
    }

    /**
     * @return Table
     */
    public function getTable()
    {
        return $this->table;
    }

    /**
     * @param string $strTable
     *
     * @return $this
     * @throws Exception
     */
    public function setTable($strTable)
    {

        if (!is_string($strTable)) {
            throw new Exception("Table de destination non définie", self::IMPORT_UNKNOWN_TABLE);
        }

        $infoTable = explode('.', $strTable);

        $schema = null;
        if (count($infoTable) == 2) {
            $schema = (new SchemaConfig())->setName($infoTable[0]);
            array_shift($infoTable);
        }

        $this->table = new Table($infoTable[0]);
        $this->table->addOption("collate", $this->getCharset());
        if ($schema) {
            $this->table->setSchemaConfig($schema);
        }

        return $this;
    }

    /**
     * Ajoute un plugins: callable
     *
     * @param callable $fct fct($row)
     *
     * @return $this
     * @throws Exception
     */
    public function addPlugins(callable $fct)
    {

        if (!is_callable($fct)) {
            throw new Exception("$fct: Le plugins n'est pas conforme");
        }
        $this->plugins[] = $fct;

        return $this;
    }

    /**
     * Lire des données et les traiter par setFields et setValues
     * @return mixed
     * @throws Exception
     */
    public function read()
    {
        throw new Exception("You must implement the read function", 10);
    }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Core;

use ItePHP\Mapper\MapperAbstract;
use ItePHP\Mapper\MapperNotFoundException;

/**
 * Service to cast variables
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class MapperService{

	/**
	 * @var Container
	 */
	private $container;

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

	/**
	 * Cast value
	 *
	 * @param string $mapperName - class with implements mapped code eg: "ItePHP\Mapper\Text"
	 * @param mixed $value - value to cast
	 * @return mixed
	 * @throws MapperNotFoundException
	 */
	public function cast($mapperName,$value){
		if(!class_exists($mapperName)){
			throw new MapperNotFoundException($mapperName);
		}

        /**
         * @var MapperAbstract $mapper
         */
		$mapper=new $mapperName($this->container);
		return $mapper->cast($value);
	}

}


<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Predis\Command\Redis;

use Predis\Command\Command as RedisCommand;

/**
 * @link http://redis.io/commands/blpop
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class BLPOP extends RedisCommand
{
    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return 'BLPOP';
    }

    /**
     * {@inheritdoc}
     */
    public function setArguments(array $arguments)
    {
        if (count($arguments) === 2 && is_array($arguments[0])) {
            list($arguments, $timeout) = $arguments;
            array_push($arguments, $timeout);
        }

        parent::setArguments($arguments);
    }
}


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

namespace RedKiteCms\Core\RedKiteCms\Core\Form\PageCollection;

use RedKiteCms\Bridge\Form\BaseType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Class PageType is the object deputed to define the page editor form
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Core\RedKiteCms\Core\Form\Page
 */
class PageType extends BaseType
{
    /**
     * @type array
     */
    private $templates;

    /**
     * Constructor
     *
     * @param array $templates
     */
    public function __construct(array $templates)
    {
        $this->templates = $templates;
    }

    /**
     * Builds the form
     *
     * @see FormTypeExtensionInterface::buildForm()
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder->add(
            'pagename',
            null,
            array(
                'attr' => array(
                    'data-bind' => 'value: name, uniqueName: true, valueUpdate: \'afterkeydown\', event: {change: $root.editPage}',
                    'class' => 'form-control input-sm',
                ),
            )
        );

        $builder->add(
            'templatename',
            'choice',
            array(
                'choices' => $this->templates,
                'attr' => array(
                    'data-bind' => 'value: template, uniqueName: true, valueUpdate: \'afterkeydown\', event: {change: $root.editPage}',
                    'class' => 'form-control input-sm',
                ),
            )
        );
    }
}


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use OpenOrchestra\ModelBundle\Document\Content;
use OpenOrchestra\ModelBundle\Document\ContentAttribute;
use OpenOrchestra\ModelInterface\Model\ContentInterface;

/**
 * Class LoadContentThousandData
 */
class LoadContentThousandData extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * @param ObjectManager $objectManager
     */
    public function load(ObjectManager $objectManager)
    {
        for ($i = 0; $i < 250 ; $i++) {
            $objectManager->persist($this->generateNews($i, 1, 'fr'));
            // Versions
            for ($j = 2; $j < 5; $j++) {
                // Languages
                for ($k = 0; $k < 2; $k++) {
                    $language = 'fr';
                    if ($k === 1) {
                        $language = 'en';
                    }
                    $objectManager->persist($this->generateNews($i, $j, $language));
                }
            }
        }

        $objectManager->flush();
    }

    /**
     * Get the order of this fixture
     *
     * @return integer
     */
    function getOrder()
    {
        return 530;
    }

    /**
     * @param string $name
     * @param string $value
     * @param string $type
     *
     * @return ContentAttribute
     */
    public function generateContentAttribute($name, $value, $type = 'text')
    {
        $attribute = new ContentAttribute();
        $attribute->setName($name);
        $attribute->setValue($value);
        $attribute->setStringValue($value);
        $attribute->setType($type);

        return $attribute;
    }

    /**
     * Generate a content
     *
     * @param string  $type
     * @param int     $id
     * @param string  $name
     * @param string  $language
     * @param int     $version
     * @param boolean $deleted
     *
     * @return Content
     */
    protected function generateContent($type, $id, $name, $language, $version, $deleted)
    {
        $content = new Content();

        $content->setContentId($id);
        $content->setContentType($type);
        $content->setDeleted($deleted);
        $content->setName($name);
        $content->setLanguage($language);
        $content->setVersion($version);
        $content->setSiteId('2');
        $date = new \DateTime("now");
        $content->setVersionName($content->getName().'_'. $date->format("Y-m-d_H:i:s"));

        switch ($version) {
            case 2: $content->setStatus($this->getReference('status-pending'));
                break;
            case 4: $content->setStatus($this->getReference('status-draft'));
                break;
            default: $content->setStatus($this->getReference('status-published'));
                break;
        }

        return $content;
    }

    /**
     * Fill news attributes
     *
     * @param Content          $news
     * @param ContentAttribute $title
     * @param ContentAttribute $intro
     * @param ContentAttribute $text
     *
     * @return Content
     */
    protected function addNewsAttributes($news, $title, $intro, $text)
    {
        $news->addAttribute($title);
        $news->addAttribute($this->generateContentAttribute('publish_start', '2014-08-26', 'date'));
        $news->addAttribute($this->generateContentAttribute('publish_end', '2014-12-19', 'date'));
        $news->addAttribute($intro);
        $news->addAttribute($text);

        return $news;
    }

    /**
     * @param string  $index
     * @param int     $version
     * @param string  $language
     * @param boolean $deleted
     *
     * @return ContentInterface
     */
    public function generateNews($index, $version, $language, $deleted = false)
    {
        $title = $this->generateContentAttribute('title', 'New number' . $index . 'in language ' . $language);
        $intro = $this->generateContentAttribute('intro', 'This is the introduction for the news number ' . $index .'.');
        $text = $this->generateContentAttribute('text', 'Donec bibendum at nibh eget imperdiet. Mauris eget justo augue. Fusce fermentum iaculis erat, sollicitudin elementum enim sodales eu. Donec a ante tortor. Suspendisse a.', 'wysiwyg');
        $news = $this->generateContent('news', 'news-' . $index, 'News ' . $index, $language, $version, $deleted);

        return $this->addNewsAttributes($news, $title, $intro, $text);
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\Basket\Basket\Filter;

use RunetId\Client\Result\Pay\ItemResult;
use RunetId\Client\Result\Pay\OrderResult;

final class ManagerFilter extends AbstractBinaryFilter
{
    private $manager;

    public function __construct(string $manager, int $priority = 1)
    {
        $this->manager = $manager;
        parent::__construct($priority);
    }

    /**
     * {@inheritdoc}
     */
    protected function vote(ItemResult $item, ?OrderResult $order): bool
    {
        return $this->manager === $item->Product->Manager;
    }
}


<?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.
 */

/**
 * QRCode.php.
 *
 * Part of Overtrue\WeChat.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author    mingyoung <mingyoungcheung@gmail.com>
 * @copyright 2016
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\MiniProgram\QRCode;

use EasyWeChat\MiniProgram\Core\AbstractMiniProgram;

class QRCode extends AbstractMiniProgram
{
    const API_GET_WXACODE = 'https://api.weixin.qq.com/wxa/getwxacode';
    const API_GET_WXACODE_UNLIMIT = 'http://api.weixin.qq.com/wxa/getwxacodeunlimit';
    const API_CREATE_QRCODE = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode';

    /**
     * Get WXACode.
     *
     * @param string $path
     * @param int    $width
     * @param bool   $autoColor
     * @param array  $lineColor
     *
     * @return \Psr\Http\Message\StreamInterface
     */
    public function getAppCode($path, $width = 430, $autoColor = false, $lineColor = ['r' => 0, 'g' => 0, 'b' => 0])
    {
        $params = [
            'path' => $path,
            'width' => $width,
            'auto_color' => $autoColor,
            'line_color' => $lineColor,
        ];

        return $this->getStream(self::API_GET_WXACODE, $params);
    }

    /**
     * Get WXACode unlimit.
     *
     * @param string $scene
     * @param int    $width
     * @param bool   $autoColor
     * @param array  $lineColor
     *
     * @return \Psr\Http\Message\StreamInterface
     */
    public function getAppCodeUnlimit($scene, $width = 430, $autoColor = false, $lineColor = ['r' => 0, 'g' => 0, 'b' => 0])
    {
        $params = [
            'scene' => $scene,
            'width' => $width,
            'auto_color' => $autoColor,
            'line_color' => $lineColor,
        ];

        return $this->getStream(self::API_GET_WXACODE_UNLIMIT, $params);
    }

    /**
     * Create QRCode.
     *
     * @param string $path
     * @param int    $width
     *
     * @return \Psr\Http\Message\StreamInterface
     */
    public function createQRCode($path, $width = 430)
    {
        return $this->getStream(self::API_CREATE_QRCODE, compact('path', 'width'));
    }

    /**
     * Get stream.
     *
     * @param string $endpoint
     * @param array  $params
     *
     * @return \Psr\Http\Message\StreamInterface
     */
    protected function getStream($endpoint, $params)
    {
        return $this->getHttp()->json($endpoint, $params)->getBody();
    }
}


<?php
/**
 * This file is part of VinceTAdminBundle for Symfony2
 *
 * @category VinceT
 * @package  VinceTAdminBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/AdminBundle
 */

namespace VinceT\AdminBundle\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Theme controller
 *
 * @category VinceT
 * @package  VinceTAdminBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/AdminBundle
 */
class ThemeController extends AdminController
{
    /**
     * Change the current theme used
     *
     * @return RedirectResponse
     */
    public function changeAction()
    {
        $theme = $this->container->get('request')->request->get('admin_theme');
        $this->container->get('vince_t.admin.theme.handler')->setCurrentTheme($theme);
        $headers = $this->container->get('request')->server->getHeaders();
        $referer = $headers['REFERER'];
        return new RedirectResponse($referer);
    }

}


<?php
namespace HtSettingsModule\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use HtSettingsModule\Service\CacheManager;

class CacheManagerFactory implements FactoryInterface
{
    /**
     * Gets cache manager
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return CacheManager
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $cacheManager = new CacheManager($serviceLocator->get('HtSettingsModule\Options\ModuleOptions')->getCacheOptions());
        $cacheManager->setServiceLocator($serviceLocator);

        return $cacheManager;
    }
}


<?php
/**
 * This file is part of Formular.
 *
 * (c) Philippe Gerber
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace bigwhoop\Formular\Validation;

/**
 * @author Philippe Gerber <philippe@bigwhoop.ch>
 */
class CallbackValidator implements ValidatorInterface
{
    /** @var callable */
    private $callable;

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

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

    /**
     * @param callable $callable
     * @param string $errorMessageTemplate
     */
    public function __construct(callable $callable, $errorMessageTemplate)
    {
        $this->callable = $callable;
        $this->errorMessageTemplate = $errorMessageTemplate;
    }

    /**
     * {@inheritdoc}
     */
    public function isValid($value)
    {
        if (call_user_func($this->callable, $value)) {
            $this->errorMessage = '';
            return true;
        }
        $this->errorMessage = str_replace('%VALUE%', print_r($value, true), $this->errorMessageTemplate);
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }
}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Item;

class DeletedContentfulEntry
{
    use Traits\ContentfulSys;

    /**
     * @param ContentfulEntry $entry
     *
     * @return DeletedContentfulEntry
     */
    public static function fromEntry(ContentfulEntry $entry)
    {
        $deletedEntry = new DeletedContentfulEntry();
        $deletedEntry->setCreatedAt($entry->getCreatedAt());
        $deletedEntry->setId($entry->getId());
        $deletedEntry->setRevision($entry->getRevision());
        $deletedEntry->setSpaceId($entry->getSpaceId());
        $deletedEntry->setUpdatedAt($entry->getUpdatedAt());
        return $deletedEntry;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return sprintf('ContentfulEntry: %s@%s, v%d', $this->getId(), $this->getSpaceId(), $this->getRevision());
    }
}


<?php

/**
 * Manage Cache by Redis
 *
 * @category  	lib
 * @package		lib\Cache
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
namespace Venus\lib\Cache;

use \Redis as RealRedis;
use \Venus\lib\Cache\CacheInterface;

/**
 * This class manage the Cache by Redis
 *
 * @category  	lib
 * @package		lib\Cache
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Redis extends RealRedis implements CacheInterface
{
    /**
     * constructor with the connection to Redis
     *
     * @access public
     * @param $oConf
     * @throws \Exception
     * @internal param string $sName name of the session
     * @internal param int $iFlags flags
     * @internal param int $iTimeout expiration of cache
     */
    public function __construct($oConf)
    {
        if (!$this->connect($oConf->host, $oConf->port)) {

            throw new \Exception('Redis server unavailable');
        }

        // Select the REDIS db index
        $this->select($oConf->index);
    }

    /**
     * get a value
     *
     * @access public
     * @param  string $sName name of the session
     * @param  int $iFlags flags
     * @param  int $iTimeout expiration of cache
     * @return mixed
     */
    public function get(string $sName, int &$iFlags = null, int $iTimeout = 0)
    {
        return parent::get($sName);
    }

    /**
     * set a value
     *
     * @access public
     * @param  string $sName name of the session
     * @param  mixed $mValue value of this sesion var
     * @param  int $iFlag unused
     * @param  int $iExpire expiration of cache
     * @return \Venus\lib\Cache\Apc
     */
    public function set(string $sName, $mValue, int $iFlag = 0, int $iExpire = false)
    {
        if ($iExpire === false) {

            return parent::set($sName, $mValue);
        }
        else {

            return parent::setex($sName, $iExpire, $mValue);
        }
    }

    /**
     * flush the cache
     *
     * @access public
     * @return mixed
     */
    public function flush()
    {
        return false;
    }

    /**
     * delete a value
     *
     * @access public
     * @param  string $sName name of the session
     * @return mixed
     */
    public function delete(string $sName)
    {
        return $this->del($sName);
    }

    /**
     * close the redis connecction
     *
     * @access public
     * @return mixed
     */
    public function __sleep()
    {
        $this->close();
    }

    /**
     * add
     *
     * @access public
     * @param  string $sName name of the session
     * @param  mixed $mValue value of this sesion var
     * @param  int $iFlag unused
     * @param  int $iExpire expiration of cache
     * @return mixed
     */
    public function add(string $sName, $mValue, int $iExpire = false)
    {
        return $this->set($sName, $mValue, 0, $iExpire);
    }
}


<?php

namespace bariew\eventModule\controllers;

use Yii;
use bariew\eventModule\models\Item;
use bariew\eventModule\models\ItemSearch;
use yii\helpers\Json;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * ItemController implements the CRUD actions for Item model.
 */
class ItemController extends Controller
{

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Item models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ItemSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Item model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Item model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Item();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Item model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Activates/deactivates model.
     * @param integer $id model id.
     * @param integer 1/0 $active whether to activate model.
     */
    public function actionActivate($id, $active)
    {
        $model = Item::findOne($id);
        $model->attributes = compact('active');
        $model->save();
    }
    /**
     * Deletes an existing Item model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    public function actionTree($type, $id, $model_id = false)
    {
        ob_start();
        $model = $model_id ? Item::findOne($model_id) : new Item();
        $tree = $model->$type();
        if ($id == '#') {
            $id = false;
            $items = $tree;
        } else {
            $path = explode('\\', $id);
            $items = $tree;
            foreach ($path as $name) {
                $items = &$items[$name];
            }
        }
        ob_clean();
        Yii::$app->response->format = Response::FORMAT_JSON;
        return $model->createJsonTreeItems($type, $items, $id);
    }

    /**
     * Returns json event list for form DepDrop widget.
     */
    public function actionTriggerEvents()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $result = ($post = Yii::$app->request->post('depdrop_parents'))
            ? Item::eventList($post[0])
            : [];
        $output = [];
        foreach ($result as $id => $name) {
            $output[] = compact('id', 'name');
        }
        echo Json::encode(['output' => $output, 'selected' => '']);
    }

    /**
     * Returns json handler method list for form DepDrop widget.
     */
    public function actionHandlerMethods()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $result = ($post = Yii::$app->request->post('depdrop_parents'))
            ? Item::methodList($post[0])
            : [];
        $output = [];
        foreach ($result as $id => $name) {
            $output[] = compact('id', 'name');
        }
        echo Json::encode(['output' => $output, 'selected' => '']);
    }

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

    public function actionTest()
    {
        return CommonTree::widget();
    }
}


<?php
/**
 * CoolMS2 User Module (http://www.coolms.com/)
 *
 * @link      http://github.com/coolms/user for the canonical source repository
 * @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
 * @license   http://www.coolms.com/license/new-bsd New BSD License
 * @author    Dmitry Popov <d.popov@altgraphic.com>
 */

namespace CmsUser\Listener;

use Zend\EventManager\AbstractListenerAggregate,
    Zend\EventManager\EventManagerInterface,
    Zend\Http\Request as HttpRequest,
    Zend\Mvc\MvcEvent,
    CmsAuthorization\Mapping\RoleableInterface,
    CmsAuthorization\Options\ModuleOptions as AuthorizationModuleOptions,
    CmsPermissions\Options\ModuleOptions as PermissionsModuleOptions,
    CmsUser\Service\UserService;

/**
 * User register event listener
 *
 * @author Dmitry Popov <d.popov@altgraphic.com>
 */
class RegistrationListener extends AbstractListenerAggregate
{
    /**
     * {@inheritDoc}
     */
    public function attach(EventManagerInterface $events)
    {
    	$this->listeners[] = $events->attach(MvcEvent::EVENT_BOOTSTRAP, [$this, 'onBootstrap'], -100);
    }

    /**
     * Event callback to be triggered on bootstrap
     *
     * @param MvcEvent $e
     * @return void
     */
    public function onBootstrap(MvcEvent $e)
    {
        if (!$e->getRequest() instanceof HttpRequest) {
            return;
        }

        $app = $e->getApplication();
        $services = $app->getServiceManager();

        $eventManager       = $app->getEventManager();
        $sharedEventManager = $eventManager->getSharedManager();

        $sharedEventManager->attach(UserService::class, 'register', function($e) use ($services)
        {
            $user = $e->getParam('user');
            if ($user instanceof RoleableInterface &&
                $services->has(AuthorizationModuleOptions::class)
            ) {
                /* @var $config PermissionsModuleOptions */
                $config = $services->get(PermissionsModuleOptions::class);
                $roleClass = $config->getRoleEntityClass();
                $mapper = $services->get('MapperManager')->get($roleClass);
                if ($defaultRole = $mapper->find($config->getAuthenticatedRole())) {
                    $user->addRole($defaultRole);
                }
            }
        }, 100);
    }
}


<?php

namespace Dhii\Output;

use Dhii\Util\String\StringableInterface as Stringable;
use Exception as RootException;
use Dhii\Output\Exception\CouldNotRenderException;

trait CreateCouldNotRenderExceptionCapableTrait
{
    /**
     * Creates a new render failure exception.
     *
     * @since [*next-version*]
     *
     * @param string|Stringable|null $message  The error message, if any.
     * @param int|null               $code     The error code, if any.
     * @param RootException|null     $previous The inner exception for chaining, if any.
     * @param RendererInterface      $renderer The associated renderer, if any.
     *
     * @return CouldNotRenderException The new exception.
     */
    protected function _createCouldNotRenderException(
        $message = null,
        $code = null,
        RootException $previous = null,
        RendererInterface $renderer = null
    ) {
        return new CouldNotRenderException($message, $code, $previous, $renderer);
    }
}


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

namespace Controller\Theme;

use RedKiteCms\Rendering\Controller\Theme\ShowThemeController as BaseShowThemeController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * This object implements the Silex controller to show the themes panel
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Theme
 */
class ShowThemeController extends BaseShowThemeController
{
    /**
     * Show themes panel action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function showAction(Request $request, Application $app)
    {
        $options = array(
            'twig' => $app["twig"],
            'template_assets' => $app["red_kite_cms.template_assets"],
            "configuration_handler" => $app["red_kite_cms.configuration_handler"],
            "plugin_manager" => $app["red_kite_cms.plugin_manager"],
        );

        return parent::show($options);
    }
}


<?php

namespace Acacha\Contact\Providers;

use Illuminate\Support\ServiceProvider;

/**
 * Class ContactServiceProvider.
 */
class ContactServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Register the application services.
     */
    public function register()
    {
        if (!defined('ACACHA_CONTACT_PATH')) {
            define('ACACHA_CONTACT_PATH', realpath(__DIR__.'/../../'));
        }

        $this->app->bind('Contact', function () {
            return new \Acacha\Contact\Contact();
        });

    }

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->migrations();
    }

    /**
     * Configure package migrations.
     */
    protected function migrations()
    {
        $this->loadMigrationsFrom(ACACHA_CONTACT_PATH.'/database/migrations');
    }

}


<?php

namespace Webforge\Types;

use Psc\Code\Code;
use Psc\Code\Generate\GClass;
use Webforge\Common\ClassInterface;
use InvalidArgumentException;

class CollectionType extends \Webforge\Types\InterfacedObjectType implements MappedComponentType, TraversableType {

  const PSC_ARRAY_COLLECTION = 'Psc\Data\ArrayCollection';
  const WEBFORGE_COLLECTION = 'Webforge\Collections\ArrayCollection';
  const DOCTRINE_ARRAY_COLLECTION = 'Doctrine\Common\Collections\ArrayCollection';

  /**
   * @var bool|NULL
   */
  protected $isList = NULL;

  protected $implementation;

  /**
   * @param const $implementation
   */
  public function __construct($implementation = NULL, Type $innerType = NULL) {
    if (!($implementation instanceof ClassInterface) && $implementation !== NULL) {

      if (!in_array($implementation, array(self::PSC_ARRAY_COLLECTION, self::DOCTRINE_ARRAY_COLLECTION, self::WEBFORGE_COLLECTION))) {
         throw new InvalidArgumentException("implementation needs to be of _COLLECTION constant");
      }

      $implementation = GClassAdapter::newGClass($implementation);
    }

    $this->implementation = $implementation;
    $this->interfaceClass = GClassAdapter::newGClass($this->getInterface());

    parent::__construct($implementation);

    if (isset($innerType)) {
      $this->setType($innerType);
    }
  }

  public function getImplementationConstantCode() {
    if (!isset($this->implementation)) return 'NULL';

    $impl = $this->implementation->getFQN();

    if (self::PSC_ARRAY_COLLECTION === $impl) {
      return '\\'.__CLASS__.'::PSC_ARRAY_COLLECTION';
    } elseif (self::DOCTRINE_ARRAY_COLLECTION === $impl) {
      return  '\\'.__CLASS__.'::DOCTRINE_ARRAY_COLLECTION';
    } elseif (self::WEBFORGE_COLLECTION === $impl) {
      return  '\\'.__CLASS__.'::WEBFORGE_COLLECTION';
    } else {
      return '\\'.$this->implementation;
    }
  }

  /**
   * Collection zu Component-Mapping
   *
   */
  public function getMappedComponent(\Webforge\Types\Adapters\ComponentMapper $componentMapper) {
    return $componentMapper->createComponent('ComboDropBox');
  }

  /**
   * @return bool
   */
  public function isTyped() {
    return isset($this->type);
  }

  /**
   * @return Webforge\Types\Type
   */
  public function getType() {
    if (!isset($this->type)) throw new NotTypedException('Cannot return Type of Collection. Because its not set.');
    return $this->type;
  }

  /**
   *
   * wird der Parameter NULL Übergeben ist der Array nicht mehr getyped
   * @param Webforge\Types\Type|NULL
   */
  public function setType(Type $type = NULL) {
    $this->type = $type;
    return $this;
  }

  /**
   * Gibt den PHP-DokumentationsTyp der Collection zurück
   *
   * Doctrine\Common\Collections\Collection<Psc\Doctrine\Entity> z. B.
   */
  public function getPHPType() {
    return $this->getInterface().($this->isTyped() ? sprintf('<%s>',$this->getType()->getPHPType()) : NULL);
  }

  public function getInterface() {
    return 'Doctrine\Common\Collections\Collection';

    // das geht leider nicht, weil wir dann die doctrine arraycollection nicht als implementierung benutzen können
    // yagni?
    //return $this->getInterfaceDefinition('Collection');
  }

  /**
   * @inheritdoc
   */
  public function getParameterHint($useFQN = TRUE) {
    if ($useFQN) {
      return '\\'.$this->interfaceClass->getFQN();
    } else {
      return $this->interfaceClass->getName();
    }
  }

  /**
   * @inheritdoc
   */
  public function getParameterHintImport() {
    return $this->interfaceClass;
  }

  public function getSerializationType() {
    return 'ArrayCollection';
  }

  public function getDefaultValue() {
    // beide collectio interfaces lassen sich mit new und einem leeren array erstellen
    $c = $this->getClassFQN();
    return new $c(array());
  }

  public function hasScalarDefaultValue() {
    return FALSE;
  }

  /**
   * @return bool|NULL wenn es === NULL ist, gibt es keine Aussage explizite Aussage darüber ob das Array eine Liste ist
   */
  public function isList() {
    return $this->isList;
  }

  /**
   * @param bool $list
   */
  public function setIsList($list) {
    $this->isList = $list == TRUE;
    return $this;
  }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Core;

use ItePHP\Error\ErrorHandler;
use ItePHP\Presenter\HTML as HTMLPresenter;
use Onus\ClassLoader;
use Pactum\ConfigContainer;

/**
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class HTTPErrorHandler implements ErrorHandler{

	/**
	 *
	 * @var ClassLoader
	 */
	private $classLoader;

	/**
	 *
	 * @var Request
	 */
	private $request;

	/**
	 *
	 * @param ClassLoader $classLoader
	 * @param Request $request
	 */
	public function __construct(ClassLoader $classLoader, Request $request){
		$this->classLoader=$classLoader;
		$this->request=$request;
	}

    /**
     * {@inheritdoc}
     */
	public function execute(\Exception $exception){
		if(!$this->classLoader->get('environment')->isSilent()){
			error_log($exception->getMessage()." ".$exception->getFile()."(".$exception->getLine().")");
		}

		$presenter=$this->getPresenter($this->request->getUrl());

		$response=new Response();
		$response->setStatusCode(500);
		$response->setContent($exception);
		if($exception instanceof HTTPException){
			$response->setStatusCode($exception->getStatusCode());
		}

		$event=new ExecutePresenterEvent($this->request,$response);
		$this->classLoader->get('eventManager')->fire('executePresenter',$event);

		$presenter->render($this->request,$response);

	}

	/**
	 *
	 * @param string $url
	 * @return Presenter
	 */
	private function getPresenter($url){
        /**
         * @var ConfigContainer $config
         */
        $config=$this->classLoader->get('config');
		foreach($config->getArray('error') as $error){
            /**
             * @var ConfigContainer $error
             */
			if(!preg_match('/^'.$error->getValue('pattern').'$/',$url)){
				continue;
			}
			$presenterName=$error->getValue('presenter');
            /**
             * @var Presenter $presenterObject
             */
            $presenterObject=$this->classLoader->get('presenter.'.$presenterName);
			return $presenterObject;
		}

		return new HTMLPresenter($this->classLoader->get('environment'));

	}

}


<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Predis\Connection\Cluster;

use Predis\Cluster\PredisStrategy;
use Predis\Cluster\StrategyInterface;
use Predis\Command\CommandInterface;
use Predis\Connection\NodeConnectionInterface;
use Predis\NotSupportedException;

/**
 * Abstraction for a cluster of aggregate connections to various Redis servers
 * implementing client-side sharding based on pluggable distribution strategies.
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 *
 * @todo Add the ability to remove connections from pool.
 */
class PredisCluster implements ClusterInterface, \IteratorAggregate, \Countable
{
    /**
     * @var NodeConnectionInterface[]
     */
    private $pool = array();

    /**
     * @var NodeConnectionInterface[]
     */
    private $aliases = array();

    /**
     * @var StrategyInterface
     */
    private $strategy;

    /**
     * @var Predis\Cluster\Distributor\DistributorInterface
     */
    private $distributor;

    /**
     * @param StrategyInterface $strategy Optional cluster strategy.
     */
    public function __construct(StrategyInterface $strategy = null)
    {
        $this->strategy = $strategy ?: new PredisStrategy();
        $this->distributor = $this->strategy->getDistributor();
    }

    /**
     * {@inheritdoc}
     */
    public function isConnected()
    {
        foreach ($this->pool as $connection) {
            if ($connection->isConnected()) {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function connect()
    {
        foreach ($this->pool as $connection) {
            $connection->connect();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function disconnect()
    {
        foreach ($this->pool as $connection) {
            $connection->disconnect();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function add(NodeConnectionInterface $connection)
    {
        $parameters = $connection->getParameters();

        $this->pool[(string) $connection] = $connection;

        if (isset($parameters->alias)) {
            $this->aliases[$parameters->alias] = $connection;
        }

        $this->distributor->add($connection, $parameters->weight);
    }

    /**
     * {@inheritdoc}
     */
    public function remove(NodeConnectionInterface $connection)
    {
        if (false !== $id = array_search($connection, $this->pool, true)) {
            unset($this->pool[$id]);
            $this->distributor->remove($connection);

            if ($this->aliases && $alias = $connection->getParameters()->alias) {
                unset($this->aliases[$alias]);
            }

            return true;
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getConnectionByCommand(CommandInterface $command)
    {
        $slot = $this->strategy->getSlot($command);

        if (!isset($slot)) {
            throw new NotSupportedException(
                "Cannot use '{$command->getId()}' over clusters of connections."
            );
        }

        $node = $this->distributor->getBySlot($slot);

        return $node;
    }

    /**
     * {@inheritdoc}
     */
    public function getConnectionById($id)
    {
        if (isset($this->pool[$id])) {
            return $this->pool[$id];
        }
    }

    /**
     * Returns a connection instance by its alias.
     *
     * @param string $alias Connection alias.
     *
     * @return NodeConnectionInterface|null
     */
    public function getConnectionByAlias($alias)
    {
        if (isset($this->aliases[$alias])) {
            return $this->aliases[$alias];
        }
    }

    /**
     * Retrieves a connection instance by slot.
     *
     * @param string $key Key string.
     *
     * @return NodeConnectionInterface|null
     */
    public function getConnectionBySlot($slot)
    {
        return $this->distributor->getBySlot($slot);
    }

    /**
     * Retrieves a connection instance from the cluster using a key.
     *
     * @param string $key Key string.
     *
     * @return NodeConnectionInterface
     */
    public function getConnectionByKey($key)
    {
        $hash = $this->strategy->getSlotByKey($key);
        $node = $this->distributor->getBySlot($hash);

        return $node;
    }

    /**
     * Returns the underlying command hash strategy used to hash commands by
     * using keys found in their arguments.
     *
     * @return StrategyInterface
     */
    public function getClusterStrategy()
    {
        return $this->strategy;
    }

    /**
     * {@inheritdoc}
     */
    public function count()
    {
        return count($this->pool);
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->pool);
    }

    /**
     * {@inheritdoc}
     */
    public function writeRequest(CommandInterface $command)
    {
        $this->getConnectionByCommand($command)->writeRequest($command);
    }

    /**
     * {@inheritdoc}
     */
    public function readResponse(CommandInterface $command)
    {
        return $this->getConnectionByCommand($command)->readResponse($command);
    }

    /**
     * {@inheritdoc}
     */
    public function executeCommand(CommandInterface $command)
    {
        return $this->getConnectionByCommand($command)->executeCommand($command);
    }
}


<?php
namespace BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
use CoreBundle\Entity\Timestampable;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity(repositoryClass="BlogBundle\Entity\Repository\CategoryRepository")
 * @ORM\Table(name="post_category")
 */
class Category
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $name;

    /**
     * @ORM\Column(type="string", nullable=true)
     */
    protected $image;

    /**
     * @Gedmo\Slug(fields={"name"}, updatable=true, separator="-")
     * @ORM\Column(name="slug", type="string", length=64)
     */
    protected $slug;

    /**
     * @ORM\Column(type="string", nullable=true)
     */
    protected $description;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    protected $active = true;

    /**
    * @ORM\ManyToMany(targetEntity="Post", mappedBy="categories")
    */
    protected $posts;

    /**
     * @var string
     *
     * @ORM\Column(name="meta_title", type="string", length=255)
     * @Assert\NotBlank
     */
    private $metaTitle;

    /**
     * @var string
     *
     * @ORM\Column(name="meta_description", type="text")
     * @Assert\NotBlank
     */
    private $metaDescription;

    /**
     * @var string
     *
     * @ORM\Column(name="meta_tags", type="string", length=255, nullable=true)
     */
    private $metaTags;

    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Category", mappedBy="parentCategory", cascade={"remove"})
     */
    private $subcategories;

    /**
     * @var Category
     *
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="subcategories")
     * @ORM\JoinColumn(name="parent_category_id", referencedColumnName="id", nullable=true , onDelete="cascade")
     */
    private $parentCategory;

    /**
     * @var integer
     *
     * @ORM\Column(name="_order", type="integer", nullable=true)
     */
    private $order;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->posts = new ArrayCollection();
        $this->subcategories = new ArrayCollection();
    }

    /**
     * Returns the name
     * @return string
     */
    public function __toString()
    {
        return $this->getName();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *                     @return $this
     */
    public function setName($name)
    {
        $this->name = $name;
        if($this->metaTitle=='')$this->metaTitle = $name;
        if($this->metaDescription=='')$this->metaDescription = $name;
        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set image
     *
     * @param string $image
     *                      @return $this
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set slug
     *
     * @param  string $slug
     * @return Post
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

    /**
     * Get slug
     *
     * @return string
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * Set description
     *
     * @param string $description
     *                            @return $this
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

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

    /**
     * Set active
     *
     * @param boolean $active
     */
    public function setActive($active)
    {
        $this->active = $active;

        return $this;
    }

    /**
     * Get active
     *
     * @return boolean
     */
    public function active()
    {
        return $this->active;
    }

    /**
     * Add post
     *
     * @param Post $post
     *
     * @return Category
     */
    public function addPosts(Post $post)
    {
        $this->posts->add($post);

        return $this;
    }

    /**
     * Remove $post
     *
     * @param Post $post
     */
    public function removePost(Post $post)
    {
        $this->posts->removeElement($post);
    }

    /**
     * Get posts
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPosts()
    {
        return $this->posts;
    }

    /**
     * Set metaTitle
     *
     * @param string $metaTitle
     *
     * @return Category
     */
    public function setMetaTitle($metaTitle)
    {
        $this->metaTitle = $metaTitle;

        return $this;
    }

    /**
     * Get metaTitle
     *
     * @return string
     */
    public function getMetaTitle()
    {
        return $this->metaTitle;
    }

    /**
     * Set metaDescription
     *
     * @param string $metaDescription
     *
     * @return Category
     */
    public function setMetaDescription($metaDescription)
    {
        $this->metaDescription = $metaDescription;

        return $this;
    }

    /**
     * Get metaDescription
     *
     * @return string
     */
    public function getMetaDescription()
    {
        return $this->metaDescription;
    }

    /**
     * Set metaTags
     *
     * @param string $metaTags
     *
     * @return Category
     */
    public function setMetaTags($metaTags)
    {
        $this->metaTags = $metaTags;

        return $this;
    }

    /**
     * Get metaTags
     *
     * @return string
     */
    public function getMetaTags()
    {
        return $this->metaTags;
    }

    /**
     * Add subcategory
     *
     * @param Category $subcategory
     *
     * @return Category
     */
    public function addSubcategory(Category $subcategory)
    {
        $this->subcategories->add($subcategory);

        return $this;
    }

    /**
     * Remove subcategory
     *
     * @param Category $subcategory
     */
    public function removeSubcategory(Category $subcategory)
    {
        $this->subcategories->removeElement($subcategory);
    }

    /**
     * Get subcategories
     *
     * @return ArrayCollection
     */
    public function getSubcategories()
    {
        return $this->subcategories;
    }

    /**
     * Set parent Category
     *
     * @param Category $parentCategory
     *
     * @return Category
     */
    public function setParentCategory(Category $parentCategory = null)
    {
        $this->parentCategory = $parentCategory;

        return $this;
    }

    /**
     * Get parent Category
     *
     * @return Category
     */
    public function getParentCategory()
    {
        return $this->parentCategory;
    }

     /**
     * Set order
     *
     * @param integer $order
     *
     * @return Slider
     */
    public function setOrder($order)
    {
        $this->order = $order;

        return $this;
    }

    /**
     * Get order
     *
     * @return integer
     */
    public function getOrder()
    {
        return $this->order;
    }

}


<?php

namespace cascade\controllers\admin;

use cascade\components\dataInterface\DeferredAction;
use cascade\models\DataInterface;
use cascade\models\DataInterfaceLog;
use canis\base\exceptions\HttpException;
use canis\web\Controller;
use Yii;
use yii\filters\AccessControl;

/**
 * InterfaceController [[@doctodo class_description:cascade\controllers\admin\InterfaceController]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class InterfaceController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function ($rule, $action) {
                            return Yii::$app->gk->is('administrators');
                        },
                    ],
                    [
                        'allow' => false,
                    ],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * [[@doctodo method_description:actionIndex]].
     */
    public function actionIndex()
    {
        Yii::$app->response->view = 'index';
    }

    /**
     * [[@doctodo method_description:actionRun]].
     *
     * @throws HttpException         [[@doctodo exception_description:HttpException]]
     * @throws NotFoundHttpException [[@doctodo exception_description:NotFoundHttpException]]
     * @return [[@doctodo return_type:actionRun]] [[@doctodo return_description:actionRun]]
     *
     */
    public function actionRun()
    {
        if (empty($_GET['id']) || !($dataInterface = DataInterface::get($_GET['id']))) {
            throw new HttpException(404, 'Data interface could not be found');
        }
        $lastLog = $dataInterface->lastDataInterfaceLog;
        if (!empty($lastLog) && $lastLog->isActive) {
            Yii::$app->response->error = 'There is already an active interface action.';
            Yii::$app->response->refresh = true;

            return;
        }

        $log = new DataInterfaceLog();
        $log->data_interface_id = $dataInterface->primaryKey;
        if (!$log->save()) {
            Yii::$app->response->error = 'An error occurred while starting the data interface log.';
            Yii::$app->response->refresh = true;

            return;
        }

        $deferredAction = DeferredAction::setup(['logModel' => $log->primaryKey]);
        if (!$deferredAction) {
            throw new NotFoundHttpException("Deferred action could not be started!");
        }
        Yii::$app->response->task = 'client';
        Yii::$app->response->clientTask = 'deferredAction';
        Yii::$app->response->taskOptions = $deferredAction->package();
    }

    /**
     * [[@doctodo method_description:actionViewLogs]].
     *
     * @throws HttpException [[@doctodo exception_description:HttpException]]
     */
    public function actionViewLogs()
    {
        if (empty($_GET['id']) || !($dataInterface = DataInterface::get($_GET['id']))) {
            throw new HttpException(404, 'Data interface could not be found');
        }
        $this->params['dataInterface'] = $dataInterface;
        Yii::$app->response->view = 'view_logs';
    }

    /**
     * [[@doctodo method_description:actionViewLog]].
     *
     * @throws HttpException [[@doctodo exception_description:HttpException]]
     * @return [[@doctodo return_type:actionViewLog]] [[@doctodo return_description:actionViewLog]]
     *
     */
    public function actionViewLog()
    {
        if (empty($_GET['id']) || !($dataInterfaceLog = DataInterfaceLog::get($_GET['id']))) {
            throw new HttpException(404, 'Data interface log could not be found');
        }
        $this->params['dataInterfaceLog'] = $dataInterfaceLog;
        if (Yii::$app->request->isAjax && !empty($_GET['package'])) {
            Yii::$app->response->data = $dataInterfaceLog->dataPackage;

            return;
        } elseif (Yii::$app->request->isAjax) {
            Yii::$app->response->taskOptions = ['title' => 'View Log', 'modalClass' => 'modal-xl'];
            Yii::$app->response->task = 'dialog';
        }
        if ($dataInterfaceLog->status === 'queued') {
            Yii::$app->response->view = 'view_log_queued';
        } else {
            Yii::$app->response->view = 'view_log';
        }
    }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Component\Form;

/**
 * Formatter for FormBuilder
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class BasicFormFormatter implements FormFormatter{

    /**
     * {@inheritdoc}
     */
	public function renderField(FormField $field){
		$html=$field->render();
		return $html;
	}

    /**
     * {@inheritdoc}
     */
	public function renderFormBegin($tags){
		$template='<FORM ';
		foreach($tags as $kTag=>$tag){
			if($tag!='')
				$template.=$kTag.'="'.$tag.'" ';
		}

		$template.=' >';

		return $template;
	}

    /**
     * {@inheritdoc}
     */
	public function renderFormEnd(){
		return '</FORM>';
	}

    /**
     * {@inheritdoc}
     */
	public function renderSubmit($tags){
		$template='<BUTTON ';
		$value=$tags['value'];
		unset($tags['value']);

		foreach($tags as $kTag=>$tag){
			if($tag!='')
				$template.=$kTag.'="'.$tag.'" ';
		}

		$template.=' >'.$value.'</BUTTON>';

		return $template;

	}
}


<?php
namespace app\manage\block;

class KeywordBlock extends Block
{

    /**
     * search
     *
     * @param array $data
     * @return string
     */
    public static function search($data = [])
    {
        $data = array_merge(self::$default_search, $data);

        $html = '
';
        $html .= '
';
        $html .= '<input type="text" class="am-form-field nd-search-field" name="' . $data['name'] . '" placeholder="' . $data['holder'] . '" value="' . $data['value'] . '" style="' . $data['style'] . '" ' . $data['attr'] . ' />';
        $html .= '';
        $html .= '<button class="am-btn am-btn-default nd-search" target-form="' . $data['target'] . '" type="button">' . $data['text'] . '</button>';
        $html .= '';
        $html .= '
';
        $html .= '
';

        return $html;
    }
}


<?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.
 */

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

namespace EasyWeChat\User;

use EasyWeChat\Core\AbstractAPI;

/**
 * Class Tag.
 */
class Tag extends AbstractAPI
{
    const API_GET = 'https://api.weixin.qq.com/cgi-bin/tags/get';
    const API_CREATE = 'https://api.weixin.qq.com/cgi-bin/tags/create';
    const API_UPDATE = 'https://api.weixin.qq.com/cgi-bin/tags/update';
    const API_DELETE = 'https://api.weixin.qq.com/cgi-bin/tags/delete';
    const API_USER_TAGS = 'https://api.weixin.qq.com/cgi-bin/tags/getidlist';
    const API_MEMBER_BATCH_TAG = 'https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging';
    const API_MEMBER_BATCH_UNTAG = 'https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging';
    const API_USERS_OF_TAG = 'https://api.weixin.qq.com/cgi-bin/user/tag/get';

    /**
     * Create tag.
     *
     * @param string $name
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function create($name)
    {
        $params = [
                   'tag' => ['name' => $name],
                  ];

        return $this->parseJSON('json', [self::API_CREATE, $params]);
    }

    /**
     * List all tags.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function lists()
    {
        return $this->parseJSON('get', [self::API_GET]);
    }

    /**
     * Update a tag name.
     *
     * @param int    $tagId
     * @param string $name
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function update($tagId, $name)
    {
        $params = [
                   'tag' => [
                               'id' => $tagId,
                               'name' => $name,
                              ],
                  ];

        return $this->parseJSON('json', [self::API_UPDATE, $params]);
    }

    /**
     * Delete tag.
     *
     * @param int $tagId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function delete($tagId)
    {
        $params = [
                   'tag' => ['id' => $tagId],
                  ];

        return $this->parseJSON('json', [self::API_DELETE, $params]);
    }

    /**
     * Get user tags.
     *
     * @param string $openId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function userTags($openId)
    {
        $params = ['openid' => $openId];

        return $this->parseJSON('json', [self::API_USER_TAGS, $params]);
    }

    /**
     * Get users from a tag.
     *
     * @param string $tagId
     * @param string $nextOpenId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function usersOfTag($tagId, $nextOpenId = '')
    {
        $params = ['tagid' => $tagId, 'next_openid' => $nextOpenId];

        return $this->parseJSON('json', [self::API_USERS_OF_TAG, $params]);
    }

    /**
     * Batch tag users.
     *
     * @param array $openIds
     * @param int   $tagId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function batchTagUsers(array $openIds, $tagId)
    {
        $params = [
                   'openid_list' => $openIds,
                   'tagid' => $tagId,
                  ];

        return $this->parseJSON('json', [self::API_MEMBER_BATCH_TAG, $params]);
    }

    /**
     * Untag users from a tag.
     *
     * @param array $openIds
     * @param int   $tagId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function batchUntagUsers(array $openIds, $tagId)
    {
        $params = [
                   'openid_list' => $openIds,
                   'tagid' => $tagId,
                  ];

        return $this->parseJSON('json', [self::API_MEMBER_BATCH_UNTAG, $params]);
    }
}