<?php

namespace Hmaus\Spas\Parser;

use Hmaus\Reynaldo\Elements\ApiHttpTransaction;
use Hmaus\Reynaldo\Elements\ApiParseResult;
use Hmaus\Reynaldo\Elements\ApiResource;
use Hmaus\Reynaldo\Elements\ApiResourceGroup;
use Hmaus\Reynaldo\Elements\ApiStateTransition;
use Hmaus\Reynaldo\Parser\RefractParser;

class Apib implements Parser
{
    /**
     * @var RefractParser
     */
    private $parser;

    public function __construct()
    {
        $this->parser = new RefractParser();
    }

    public function parse(array $description) : array
    {
        return $this->buildParsedRequests(
            $this->parser->parse($description)
        );
    }

    /**
     * Traverse the document and build parsed requests for spas
     *
     * @param ApiParseResult $parseResult
     * @return ParsedRequest[]
     */
    private function buildParsedRequests(ApiParseResult $parseResult) : array
    {
        $requests = [];

        foreach ($parseResult->getApi()->getResourceGroups() as $apiResourceGroup) {
            foreach ($apiResourceGroup->getResources() as $apiResource) {
                foreach ($apiResource->getTransitions() as $apiStateTransition) {
                    foreach ($apiStateTransition->getHttpTransactions() as $apiHttpTransaction) {
                        $this->processApiHttpTransactions(
                            $apiHttpTransaction,
                            $apiResourceGroup,
                            $apiResource,
                            $apiStateTransition,
                            $requests
                        );
                    }
                }
            }
        }

        return $requests;
    }

    /**
     * @param $apiHttpTransaction
     * @param $apiResourceGroup
     * @param $apiResource
     * @param $apiStateTransition
     * @param $requests
     * @return array
     */
    private function processApiHttpTransactions(
        ApiHttpTransaction $apiHttpTransaction,
        ApiResourceGroup $apiResourceGroup,
        ApiResource $apiResource,
        ApiStateTransition $apiStateTransition,
        array &$requests
    ) : array
    {
        $apiRequest = $apiHttpTransaction->getHttpRequest();
        $apiResponse = $apiHttpTransaction->getHttpResponse();
        $req = new SpasRequest();

        $req->setResourceGroup($apiResourceGroup);

        if ($apiResourceGroup->getTitle()) {
            $req->appendToName($apiResourceGroup->getTitle());
        }

        if ($apiResource->getTitle()) {
            $req->appendToName($apiResource->getTitle());
        }

        if ($apiStateTransition->getTitle()) {
            $req->appendToName($apiStateTransition->getTitle());
        }

        if ($apiHttpTransaction->getTitle()) {
            $req->appendToName($apiHttpTransaction->getTitle());
        }

        if ($apiRequest->getTitle()) {
            $req->appendToName($apiRequest->getTitle());
        }

        $hrefVarsFromStateTransition = $apiStateTransition->getHrefVariablesElement()->getAllVariables();
        $hrefVarsFromApiResource = $apiResource->getHrefVariablesElement()->getAllVariables();
        $hrefVars = array_merge($hrefVarsFromStateTransition, $hrefVarsFromApiResource);

        if ($hrefVars) {
            $hrefVarsForParamBag = [];

            foreach ($hrefVars as $hrefVarValueObject) {
                // Skip optional params that do not provide a default value
                // Using an example value can lead to undesired results
                if ($hrefVarValueObject->required === 'optional' && $hrefVarValueObject->default === null) {
                    continue;
                }

                $hrefVarsForParamBag[$hrefVarValueObject->name] =
                    $hrefVarValueObject->default
                        ? $hrefVarValueObject->default
                        : $hrefVarValueObject->example;
            }

            $req->params->add($hrefVarsForParamBag);
        }

        $req->setUriTemplate($apiResource->getHref());

        $req->headers->add($apiRequest->getHeaders());
        $req->setMethod($apiRequest->getMethod());
        $req->setEnabled(true);

        if ($apiRequest->hasMessageBody()) {
            $req->setContent($apiRequest->getMessageBodyAsset()->getBody());
        }

        $response = new SpasResponse();
        $response->setStatusCode($apiResponse->getStatusCode());
        $response->headers->add($apiResponse->getHeaders());

        if ($apiResponse->hasMessageBody()) {
            $response->setBody($apiResponse->getMessageBodyAsset()->getBody());
        }

        if ($apiResponse->hasMessageBodySchema()) {
            $response->setSchema($apiResponse->getMessageBodySchemaAsset()->getBody());
        }

        $req->setExpectedResponse($response);
        $requests[] = $req;

        return $requests;
    }
}


<?php declare(strict_types=1);
////////////////////////////////////////////////////////////////////////////////
// __________ __             ________                   __________
// \______   \  |__ ______  /  _____/  ____ _____ ______\______   \ _______  ___
//  |     ___/  |  \\____ \/   \  ____/ __ \\__  \\_  __ \    |  _//  _ \  \/  /
//  |    |   |   Y  \  |_> >    \_\  \  ___/ / __ \|  | \/    |   (  <_> >    <
//  |____|   |___|  /   __/ \______  /\___  >____  /__|  |______  /\____/__/\_ \
//                \/|__|           \/     \/     \/             \/            \/
// -----------------------------------------------------------------------------
//          Designed and Developed by Brad Jones <brad @="bjc.id.au" />
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////

namespace Gears\Asset\Tasks;

use Robo;
use SplFileInfo;
use RuntimeException;
use Gears\Asset\Contracts\Compiler;
use Symfony\Component\Finder\Finder;

class BuildAsset extends Robo\Task\BaseTask implements Robo\Contract\BuilderAwareInterface
{
    use Robo\Common\BuilderAwareTrait;

    /**
     * This should be set the final location of the asset.
     * Eg: ```./assets/script.min.js```
     *
     * @var SplFileInfo
     */
    protected $destination;

    /**
     * An array of source file / folder paths, that will be
     * concatenated together to build the final asset.
     *
     * @var string[]
     */
    protected $source;

    /**
     * If this is set to true, we will not minify the asset.
     * Thus allowing for easier debugging during in development.
     *
     * **Defaults to:** ```false```
     *
     * @var bool
     */
    protected $debug = false;

    /**
     * If set to true and debug is also set to false we will rename the final
     * asset to include an md5 hash of it's contents. You may also use this in
     * conjuction with the template option.
     *
     * @var bool
     */
    protected $cachebust = false;

    /**
     * If cachebust is set to true, the assets will be renamed.
     * Files in this array will be opened and searched for the old filenames,
     * replacing with the new cache busted filenames.
     *
     * @var string[]
     */
    protected $template = [];

    /**
     * If set to true we will also output a gzipped version of the asset so that
     * you can setup your webserver to serve the pre gzipped version of the
     * asset instead of doing it on the fly.
     *
     * **Defaults to:** ```false```
     *
     * @var bool
     */
    protected $gz = false;

    /**
     * Only applies when building css assets. If set to true the default we will
     * automatically prefix the built css using ```vladkens/autoprefixer-php```.
     *
     * If set to false we will not do any prefixing.
     *
     * If set to a string or an array, we will perform prefixing and pass the
     * value through to the setBrowsers method of the Autoprefixer class,
     * allowing you to easily configure the prefixer.
     *
     * **Defaults to:** ```false```
     *
     * @var bool
     */
    protected $autoprefix = false;

    /**
     * BuildAssetTask Constructor.
     *
     * @param string $destination  The path to where we will save the built asset.
     */
    public function __construct(string $destination)
    {
        $this->destination = new SplFileInfo($destination);
    }

    /**
     * Set the source(s) of the asset.
     *
     * @param  string|string[]|Finder $value Can be a single path to a folder or
     *                                       file, an array of files of folders,
     *                                       or a Finder instance.
     *
     * @return BuildAsset                    Returns our self for method chaining.
     */
    public function source($value): self
    {
        $this->source = $this->normaliseSrcInput($value); return $this;
    }

    /**
     * Debug setter.
     *
     * @param  bool $value
     * @return self
     */
    public function debug(bool $value): self
    {
        $this->debug = $value; return $this;
    }

    /**
     * Template setter.
     *
     * @param  string|string[]|Finder $value Can be a single path to a folder or
     *                                       file, an array of files of folders,
     *                                       or a Finder instance.
     *
     * @return self
     */
    public function template($value): self
    {
        $this->template = $this->normaliseSrcInput($value); return $this;
    }

    /**
     * Gz Setter.
     *
     * @param  bool $value
     * @return self
     */
    public function gz(bool $value): self
    {
        $this->gz = $value; return $this;
    }

    /**
     * Autoprefix Setter.
     *
     * @param  bool $value
     * @return self
     */
    public function autoprefix(bool $value): self
    {
        $this->autoprefix = $value; return $this;
    }

    /**
     * Cachebust Setter.
     *
     * @param  bool $value
     * @return self
     */
    public function cachebust(bool $value): self
    {
        $this->cachebust = $value; return $this;
    }

    /**
     * The main run method.
     *
     * ```php
     * $this->taskBuildAsset('/path/to/asset.js')
     * 		->source
     * 		([
     * 			'/path/to/asset1.js',
     * 			'/path/to/asset2.js',
     * 			'/path/to/asset3.js',
     * 			'/path/to/assetetc.js'
     * 		])
     * ->run();
     * ```
     * @return Robo\Result
     */
    public function run(): Robo\Result
    {
        // Touch the destination so that "realpath" works.
        $result = $this->collectionBuilder()->taskFilesystemStack()
            ->mkdir($this->destination->getPath())
            ->touch($this->destination->getPathname())
        ->run()->wasSuccessful();

        // Plus this should error out early if we can't write to the file
        if (!$result)
        {
            throw new RuntimeException
            (
                'We can not write to the destination file: '.
                $this->destination->getPathname()
            );
        }

        // Initialise the asset, this is what we will eventually
        // write to the file-system at the end of this method.
        $asset_contents = '';

        // Loop through the source files
        foreach ($this->source as $file)
        {
            // Tell the world what we are doing
            $this->printTaskInfo('Compiling - <info>'.$file.'</info>');

            // Run the compiler for each file
            $asset_contents .= $this->getCompiler(new SplFileInfo($file))->compile();
        }

        // Bust some cache balls
        if ($this->cachebust === true)
        {
            $this->bustCacheBalls($asset_contents);
        }

        // Now write the asset
        $this->writeAsset($asset_contents);

        // If we get to here assume everything worked
        return \Robo\Result::success($this);
    }

    /**
     * Creates a new compiler based on the file extension type.
     *
     * @param  SplFileInfo $file
     * @return Compiler
     */
    protected function getCompiler(SplFileInfo $file): Compiler
    {
        // Grab the source type
        $source_type = $this->getSourceType($file);

        // Which compiler will we use?
        $compiler_type = '\Gears\Asset\Compilers\\';
        $compiler_type .= ucfirst($source_type);

        // Does the compiler exist
        if (!class_exists($compiler_type))
        {
            throw new RuntimeException
            (
                'The source file type is not supported! - ('.$file.')'
            );
        }

        // Return the compiler
        return new $compiler_type
        (
            $file,
            $this->destination,
            $this->debug,
            $this->autoprefix
        );
    }

    /**
     * Determins the type of source we are dealing file.
     *
     * Normally this is as simple as looking at the file extension,
     * however a folder doesn't have one of those so we mimic it here.
     *
     * @param  SplFileInfo $file
     * @return string
     */
    protected function getSourceType(SplFileInfo $file): string
    {
        if ($file->isDir()) return 'folder';
        return $file->getExtension();
    }

    /**
     * So that we can bust the client cache in browser, we will rename the
     * asset filename, using a timestamp. But we also need to update the
     * HTML that includes the asset into the web page.
     * This method does all that for us.
     *
     * @param string $asset_contents
     *
     * @return void
     */
    protected function bustCacheBalls(string $asset_contents)
    {
        // Get some details about the asset
        $asset_ext = $this->destination->getExtension();
        $asset_name = $this->destination->getBasename('.'.$asset_ext);
        $asset_name_quoted = preg_quote($asset_name, '/');

        // Create our regular expression
        $search_for =
        '/'.
            $asset_name_quoted.'\..*?\.'.$asset_ext.'|'.
            $asset_name_quoted.'\..*?\.min\.'.$asset_ext.'|'.
            $asset_name_quoted.'\.min\.'.$asset_ext.'|'.
            $asset_name_quoted.'\.'.$asset_ext.
        '/';

        // This is the new asset name
        $replace_with = $asset_name.'.'.md5($asset_contents).'.'.$asset_ext;

        foreach ($this->template as $templateFile)
        {
            // Tell the world what we are doing
            $this->printTaskInfo('Updating template file - <info>'.$templateFile.'</info>');

            // Run the search and replace
            $this->collectionBuilder()
                ->taskReplaceInFile($templateFile)
                ->regex($search_for)
                ->to($replace_with)
            ->run();
        }

        // Grab the asset base dir
        $asset_base_dir = $this->destination->getPath();

        // Update the final asset filename to match
        $this->destination = new SplFileInfo($asset_base_dir.'/'.$replace_with);

        // Delete any old assets
        $files_to_delete = new Finder();
        $files_to_delete->files();
        $files_to_delete->name($asset_name.'.'.$asset_ext);
        $files_to_delete->name($asset_name.'.*.'.$asset_ext);
        $files_to_delete->name($asset_name.'.*.'.$asset_ext.'.gz');
        $files_to_delete->in($asset_base_dir);
        $files_to_delete->depth('== 0');
        foreach ($files_to_delete as $file_to_delete)
        {
            unlink($file_to_delete->getPathname());
        }
    }

    /**
     * The business end, finally lets actually save the
     * compiled / minified asset.
     *
     * @param string $asset_contents
     */
    protected function writeAsset(string $asset_contents)
    {
        // Tell the world what we are doing
        $this->printTaskInfo('Writing to final asset - <info>'.$this->destination->getPathname().'</info>');

        // Write the normal asset
        if (file_put_contents($this->destination->getPathname(), $asset_contents) === false)
        {
            throw new RuntimeException
            (
                'Failed to write asset: '.$this->destination->getPathname()
            );
        }

        // Create a gzipped version of the asset
        if ($this->debug === false && $this->gz === true)
        {
            $gz_file_name = $this->destination->getPathname().'.gz';

            $gz_contents = gzencode($asset_contents);

            // Tell the world what we are doing
            $this->printTaskInfo('Writing gzipped version of final asset - <info>'.$gz_file_name.'</info>');

            if (file_put_contents($gz_file_name, $gz_contents) === false)
            {
                throw new RuntimeException
                (
                    'Failed to write gzipped version of asset: '.
                    $gz_file_name
                );
            }
        }
    }

    /**
     * Helper method to convert several possible inputs
     * to a simple array of file paths.
     *
     * @param  string|string[]|Finder $input Can be a single path to a folder or
     *                                       file, an array of files of folders,
     *                                       or a Finder instance.
     *
     * @return string[]
     */
    protected function normaliseSrcInput($input): array
    {
        $output = [];

        if ($input instanceof Finder)
        {
            foreach ($input as $fileInfo)
            {
                $output[] = $fileInfo->getRealpath();
            }
        }
        else
        {
            if (!is_array($input)) $input = [$input];

            if (count($input) === 0) throw new \UnexpectedValueException;

            if (!is_string($input[0])) throw new \UnexpectedValueException;

            $output = $input;
        }

        return $output;
    }
}


<?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\Rendering\Controller\ElFinder;

use RedKiteCms\Rendering\Controller\BaseController;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class ElFinderController is the object assigned to implement the action to create the connector for the ElFinder media
 * library
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Rendering\Controller\ElFinder
 */
abstract class ElFinderController extends BaseController
{
    /**
     * Implements the action to create the connector for the ElFinder media library
     * @param array $options
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function show(array $options)
    {
        $resolver = new OptionsResolver();
        $this->configureOptions($resolver);
        $this->options = $resolver->resolve($options);

        $options["connector"]->connect();
    }

    /**
     * Configures the options for the resolver
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver
     */
    protected function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setRequired(
            array(
                'connector',
            )
        );

        $resolver->setAllowedTypes(
            array(
                'connector' => '\RedKiteCms\Bridge\ElFinder\ElFinderConnectorInterface',
            )
        );
    }
}


<?php
namespace DasRed\Translation;

use DasRed\Translation\Exception\TranslatorIsNotDefined;

trait TranslatorAwareTrait
{

	/**
	 *
	 * @var Translator
	 */
	protected $translator;

	/**
	 * alias for translate
	 *
	 * @param string $key
	 * @param array $parameters
	 * @param string $locale
	 * @param string $default
	 * @param string $parseBBCode
	 * @return string
	 * @see self::translate
	 */
	public function __($key, array $parameters = [], $locale = null, $default = null, $parseBBCode = true)
	{
		return $this->translate($key, $parameters, $locale, $default, $parseBBCode);
	}

	/**
	 *
	 * @return Translator
	 */
	public function getTranslator()
	{
		return $this->translator;
	}

	/**
	 *
	 * @param Translator $translator
	 * @return self
	 */
	public function setTranslator(Translator $translator)
	{
		$this->translator = $translator;

		return $this;
	}

	/**
	 *
	 * @param string $key
	 * @param array $parameters
	 * @param string $locale
	 * @param string $default
	 * @param string $parseBBCode
	 * @return string
	 * @throws TranslatorIsNotDefined
	 */
	public function translate($key, array $parameters = [], $locale = null, $default = null, $parseBBCode = true)
	{
		if ($this->getTranslator() === null)
		{
			throw new TranslatorIsNotDefined();
		}

		return $this->getTranslator()->__($key, $parameters, $locale, $default, $parseBBCode);
	}
}


<?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\Structure;
use Pactum\ConfigBuilder;
use Pactum\ConfigBuilderObject;

/**
 * Structure for services.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class ServiceStructure implements Structure{

    /**
     * {@inheritdoc}
     */
	public function doConfig(ConfigBuilder $configBuilder){

        $configBuilder->addArray('service',new ConfigBuilderObject())->getValue()
            ->addString('class')
            ->addString('name')
            ->addBoolean('singleton',true)
            ->addArray('method',new ConfigBuilderObject())->getValue()
            ->addString('name')
            ->addArray('argument',new ConfigBuilderObject())->getValue()
            ->addString('type')
            ->addString('value'); //FIXME change to addMixed
    }
}


<?php

namespace Bridge;

use Bridge\Exception\KeyNotFoundInSetException;
use Bridge\Exception\KeyTakenInSetException;
use Psr\Cache\CacheItemPoolInterface;

/**
 * Bridge registry.
 */
class Registry
{
    /**
     * @var Service[] Service collection
     */
    public $services = array();

    /**
     * @var CacheItemPoolInterface[] Cache pools
     */
    public $cachePools = array();

    /**
     * Returns service object based on service name.
     *
     * @param string $name Service name
     *
     * @throws KeyNotFoundInSetException
     *
     * @return Service|null
     */
    public function getService($name)
    {
        if (array_key_exists($name, $this->services)) {
            return $this->services[$name];
        }

        throw new KeyNotFoundInSetException($name, array_keys($this->services), 'services');
    }

    /**
     * Adds service.
     *
     * @param Service $service
     *
     * @return $this
     *
     * @throws KeyTakenInSetException
     */
    public function addService(Service $service)
    {
        if (array_key_exists($service->getName(), $this->services)) {
            throw new KeyTakenInSetException($service->getName(), 'services');
        }

        $this->services[$service->getName()] = $service;

        return $this;
    }

    /**
     * Returns registered services.
     *
     * @return Service[]
     */
    public function getServices()
    {
        return $this->services;
    }

    /**
     * Returns a cache pool.
     *
     * @param string $name Cache pool name
     *
     * @throws KeyNotFoundInSetException
     *
     * @return CacheItemPoolInterface
     */
    public function getCachePool($name)
    {
        if (array_key_exists($name, $this->cachePools)) {
            return $this->cachePools[$name];
        }

        throw new KeyNotFoundInSetException($name, array_keys($this->cachePools), 'cache pools');
    }

    /**
     * @param CacheItemPoolInterface $cachePool
     */
    public function addCachePool($name, CacheItemPoolInterface $cachePool)
    {
        $this->cachePools[$name] = $cachePool;
    }

    /**
     * Returns cache pools.
     *
     * @return CacheItemPoolInterface[]
     */
    public function getCachePools()
    {
        return $this->cachePools;
    }

    /**
     * Generate cache ID.
     *
     * @param string $action
     * @param array  $arguments
     *
     * @return string
     */
    public function generateCacheItemKey($action, array $arguments)
    {
        return sprintf('%s.%s', $action, md5(serialize($arguments)));
    }

    /**
     * Returns either a service, group or action based on component path.
     *
     * @param string $component
     *
     * @return object
     */
    public function get($component)
    {
        $parts = explode('.', $component);

        if (count($parts) == 1) {
            return $this->getService($parts[0]);
        } elseif (count($parts) == 2) {
            return $this->getService($parts[0])->getGroup($parts[1]);
        } elseif (count($parts) == 3) {
            return $this->getService($parts[0])->getGroup($parts[1])->getAction($parts[2]);
        }

        throw new \LogicException('Malformed component path. Please use a dot-notated path (e.g. service.group.action)');
    }
}


<?php

namespace carlosV2\DumbsmartRepositoriesBundle\ObjectIdentifier;

use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Everzet\PersistedObjects\ObjectIdentifier;

class DoctrineObjectIdentifier implements ObjectIdentifier
{
    /**
     * @var ClassMetadata
     */
    private $metadata;

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

    /**
     * {@inheritdoc}
     */
    public function getIdentity($object)
    {
        $id = $this->metadata->getIdentifierValues($object);
        if (count($id) === 1) {
            $id = reset($id);
        }

        return $id;
    }
}


<?php

/**
 * Manage Form
 *
 * @category  	lib
 * @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
 *
 * @tutorial    == in the controller:
 *
 * 				$this->form
 * 					 ->add('task', 'text')
 *					 ->add('dueDate', 'date')
 *					 ->add('save', 'submit');
 *
 *				$this->view
 *					 ->assign('form', $this->form->getForm())
 *					 ->display();
 *
 *				in the template:
 *
 *				{$form}
 *
 *				== if you want test if the form is validated, you could do that:
 *
 *				if ($this->form->isValid()) { ... } // after the form definition
 *
 *				== check if the button is clicked:
 *
 *				if ($this->form->get('save')->isClicked()) { ... }
 */
namespace Venus\lib;

use \Attila\lib\Entity          as LibEntity;
use \Venus\lib\Form\Checkbox    as Checkbox;
use \Venus\lib\Form\Container   as Container;
use \Venus\lib\Form\Label       as Label;
use \Venus\lib\Form\Input       as Input;
use \Venus\lib\Form\Radio       as Radio;
use \Venus\lib\Form\Select      as Select;
use \Venus\lib\Form\Textarea    as Textarea;

/**
 * This class manage the Form
 *
 * @category  	lib
 * @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 Form
{
    /**
     * Elements of the form
     *
     *  @access private
     *  @var    array
     */
    private $_aElement = array();

    /**
     * Increment for form
     *
     *  @access private
     *  @var    int
     */
    private static $_iFormIncrement = 0;

    /**
     * number of form
     *
     *  @access private
     *  @var    int
     */
    private $_iFormNumber = 0;

    /**
     * Separator between fields of form
     *
     *  @access private
     *  @var    string
     */
    private $_sSeparator = '<br/>';

    /**
     * The entity to save with the formular
     *
     *  @access private
     *  @var    string
     */
    private $_sSynchronizeEntity = null;

    /**
     * The id of entity
     *
     *  @access private
     *  @var    int
     */
    private $_iIdEntity = null;

    /**
     * The entity to save with the formular
     *
     *  @access private
     *  @var    int
     */
    private $_iIdEntityCreated = null;

    /**
     * constructor that it increment (static) for all use
     *
     * @access public
     */
    public function __construct()
    {
        self::$_iFormIncrement++;
        $this->_iFormNumber = self::$_iFormIncrement;
    }

    /**
     * add an element in the form
     *
     * @access public
     * @param  string $sName name
     * @param  string|\Venus\lib\Form $mType type of field
     * @param  string $sLabel label of field
     * @param  mixed $mValue value of field
     * @parma  mixed $mOptions options (for select)
     * @return \Venus\lib\Form
     */
    public function add($sName, $mType, $sLabel = null, $mValue = null, $mOptions = null)
    {
        if ($mType instanceof Container) {

            $this->_aElement[$sName] = $mType;
        } else if ($mType === 'text' || $mType === 'submit' || $mType === 'password' || $mType === 'file' || $mType === 'tel'
            || $mType === 'url' || $mType === 'email' || $mType === 'search' || $mType === 'date' || $mType === 'time'
            || $mType === 'datetime' || $mType === 'month' || $mType === 'week' || $mType === 'number' || $mType === 'range'
            || $mType === 'color' || $mType === 'hidden') {

            $this->_aElement[$sName] = new Input($sName, $mType, $sLabel, $mValue);
        } elseif ($mType === 'textarea') {

            $this->_aElement[$sName] = new Textarea($sName, $sLabel, $mValue);
        } else  if ($mType === 'select') {

            $this->_aElement[$sName] = new Select($sName, $mOptions, $sLabel, $mValue);
        } else  if ($mType === 'label') {

            $this->_aElement[$sName] = new Label($sName);
        } else  if ($mType === 'list_checkbox') {

            $i = 0;

            $this->_aElement[$sName.'_'.$i++] = new Label($sLabel);

            foreach ($mValue as $mKey => $sValue) {

                $this->_aElement[$sName.'_'.$i++] = new Checkbox($sName, $sValue, $mKey, $mOptions);
            }
        } else  if ($mType === 'checkbox') {

            $this->_aElement[$sName] = new Checkbox($sName, $sLabel, $mValue, $mOptions);
        } else  if ($mType === 'radio') {

            $this->_aElement[$sName.rand(100000, 999999)] = new Radio($sName, $sLabel, $mValue, $mOptions);
        }

        return $this;
    }

    /**
     * get id entity created by the formular
     *
     * @access public
     * @return int
     */
    public function getIdEntityCreated() : int
    {
        return $this->_iIdEntityCreated;
    }

    /**
     * set id entity created by the formular
     *
     * @access public
     * @param  int $iIdEntityCreated
     * @return Form
     */
    public function setIdEntityCreated(int $iIdEntityCreated) : Form
    {
        $this->_iIdEntityCreated = $iIdEntityCreated;
        return $this;
    }

    /**
     * get form number
     *
     * @access public
     * @return int
     */
    public function getFormNumber() : int
    {
        return $this->_iFormNumber;
    }

    /**
     * set id entity created by the formular
     *
     * @access public
     * @param  int $iFormNumber
     * @return Form
     */
    public function setFormNumber(int $iFormNumber) : Form
    {
        $this->_iFormNumber = $iFormNumber;
        return $this;
    }

    /**
     * get global form
     *
     * @access public
     * @return \Venus\lib\Form\Container
     */
    public function getForm()
    {
        $oForm = $this->getFormInObject();

        $sFormContent = $oForm->start;

        foreach ($oForm->form as $sValue) {

            $sFormContent .= $sValue.$this->_sSeparator;
        }

        $sFormContent .= $oForm->end;

        $oContainer = new Container;
        $oContainer->setView($sFormContent)
                   ->setForm($this);

        return $oContainer;
    }

    /**
     * get global object form
     *
     * @access public
     * @return \stdClass
     */
    public function getFormInObject()
    {
        $sExKey = null;

        if ($this->_iIdEntity > 0 && $this->_sSynchronizeEntity !== null && count($_POST) < 1) {

            $sModelName = str_replace('Entity', 'Model', $this->_sSynchronizeEntity);
            $oModel = new $sModelName;

            $oEntity = new $this->_sSynchronizeEntity;
            $sPrimaryKey = LibEntity::getPrimaryKeyNameWithoutMapping($oEntity);
            $sMethodName = 'findOneBy'.$sPrimaryKey;
            $oCompleteEntity = call_user_func_array(array(&$oModel, $sMethodName), array($this->_iIdEntity));

            if (is_object($oCompleteEntity)) {

                foreach ($this->_aElement as $sKey => $sValue) {

					if ($sValue instanceof \Venus\lib\Form\Input && $sValue->getType() == 'submit') {
						continue;
					}

                    if ($sValue instanceof \Venus\lib\Form\Radio) {

                        $sExKey = $sKey;
                        $sKey = substr($sKey, 0, -6);
                    }

                    if ($sValue instanceof Form) {

                        ;
                    } else {

                        $sMethodNameInEntity = 'get_'.$sKey;
						if (method_exists($oCompleteEntity, $sMethodNameInEntity)) {
							$mValue = $oCompleteEntity->$sMethodNameInEntity();
						}

                        if ($sValue instanceof \Venus\lib\Form\Radio && method_exists($this->_aElement[$sExKey], 'setValueChecked')) {

                            $this->_aElement[$sExKey]->setValueChecked($mValue);
                        } else if (isset($mValue) && method_exists($this->_aElement[$sKey], 'setValue')) {

                            $this->_aElement[$sKey]->setValue($mValue);
                        }
                    }
                }
            }
        }

        $oForm = new \StdClass();
        $oForm->start = '<form name="form'.$this->_iFormNumber.'" method="post" enctype="multipart/form-data"><input type="hidden" value="1" name="validform'.$this->_iFormNumber.'">';
        $oForm->form = array();

        foreach ($this->_aElement as $sKey => $sValue) {

            if ($sValue instanceof Container) {

                $oForm->form[$sKey] = $sValue;
            } else {

                $oForm->form[$sKey] = $sValue->fetch();
            }
        }

        $oForm->end = '</form>';

        return $oForm;
    }

    /**
     * get an element of formular
     *
     * @access public
     * @param  string $sName name
     * @return object
     */
    public function get($sName)
    {
        return $this->_aElement[$sName];
    }

    /**
     * get the form separator
     *
     * @access public
     * @return string
     */
    public function getSeparator()
    {
        return $this->_sSeparator;
    }

    /**
     * set the form separator
     *
     * @access public
     * @param  string $sSeparator separator between the fields
     * @return \Venus\lib\Form
     */
    public function setSeparator($sSeparator)
    {
        $this->_sSeparator = $sSeparator;
        return $this;
    }

    /**
     * set the entity to synchronize with the formular
     *
     * @access public
     * @param $sSynchronizeEntity
     * @param  int $iId id of the primary key
     * @return Form
     * @internal param string $sSeparator separator between the fields
     */
    public function synchronizeEntity($sSynchronizeEntity, $iId = null)
    {
        if ($iId !== null) { $this->_iIdEntity = $iId; }

        $this->_sSynchronizeEntity = $sSynchronizeEntity;
        return $this;
    }

    /**
     * add constraint
     *
     * @access public
     * @param  string $sName field name
     * @param  object $oConstraint constraint on the field
     * @return \Venus\lib\Form
     */
    public function addConstraint($sName, $oConstraint)
    {
        if ($this->_aElement[$sName] instanceof Input || $this->_aElement[$sName] instanceof Textarea) {

            $this->_aElement[$sName]->setConstraint($oConstraint);
        }

        return $this;
    }

    /**
     * get all elements
     *
     * @access public
     * @return  array
     */
    public function getElement() {

        return $this->_aElement;
    }

    /**
     * get all elements
     *
     * @access public
     * @return int
     */
    public function getIdEntity() {

        return $this->_iIdEntity;
    }

    /**
     * get all elements
     *
     * @access public
     * @return string
     */
    public function getSynchronizeEntity() {

        return $this->_sSynchronizeEntity;
    }
}


<?php

/**
 * Manage Form
 *
 * @category  	lib
 * @package		lib\Form
 * @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\Form;

/**
 * This class manage the Form
 *
 * @category  	lib
 * @package		lib\Form
 * @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 Textarea extends Common
{
	/**
	 * the label of element
	 *
	 * @access private
	 * @var    string
	 */
	private $_sLabel = null;

	/**
	 * the value of element
	 *
	 * @access private
	 * @var    string
	 */
	private $_sValue = null;

	/**
	 * constructor that it increment (static) for all use
	 *
	 * @access public
	 * @param  string $sName name
	 * @param  string $sLabel label of textarea
	 * @param  string $sValue value of textarea
	 * @return \Venus\lib\Form\Textarea
	 */
	public function __construct(string $sName, string $sLabel = null, string $sValue = null)
	{
		$this->setName($sName);
		$this->setValue($sValue);

		if ($sLabel !== null) { $this->setLabel($sLabel); }
		else { $this->setLabel($sName); }
	}

	/**
	 * get the Value
	 *
	 * @access public
	 * @return string
	 */
	public function getValue() : string
	{
		return $this->_sValue;
	}

	/**
	 * set the Value
	 *
	 * @access public
	 * @param  string $sValue Value of input;
	 * @return \Venus\lib\Form\Textarea
	 */
	public function setValue(string $sValue) : Textarea
	{
		$this->_sValue = $sValue;
		return $this;
	}

	/**
	 * get the Label
	 *
	 * @access public
	 * @return string
	 */
	public function getLabel() : string
	{
		return $this->_sLabel;
	}

	/**
	 * set the Label
	 *
	 * @access public
	 * @param  string $sLabel Label of input;
	 * @return \Venus\lib\Form\Textarea
	 */
	public function setLabel(string $sLabel) : Textarea
	{
		$this->_sLabel = $sLabel;
		return $this;
	}

	/**
	 * if the button is clicked
	 *
	 * @access public
	 * @param  string $sType type of input;
	 * @return bool
	 */
	public function isClicked(string $sType) : bool
	{
		if ($this->getType() === 'submit' || $this->getType() === 'button') {

			if (isset($_POST[$this->getName()])) { return true; }
		}

		return false;
	}

	/**
	 * get the <html>
	 *
	 * @access public
	 * @return string
	 */
	public function fetch() : string
	{
		$sContent = '';

		if ($this->getLabel()) {

			$sContent .= '<label>'.$this->getLabel().'</label> ';
		}

		$sContent .= '<textarea name="'.$this->getName().'" id="'.$this->getName().'">';

		if ($this->getValue() !== null) { $sContent .= $this->getValue(); }

		$sContent .= '</textarea>';

		return $sContent;
	}
}


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

/**
 * UserServiceProvider.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    overtrue <i@overtrue.me>
 * @copyright 2015
 *
 * @see      https://github.com/overtrue/wechat
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Foundation\ServiceProviders;

use EasyWeChat\User\Group;
use EasyWeChat\User\Tag;
use EasyWeChat\User\User;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Class UserServiceProvider.
 */
class UserServiceProvider implements ServiceProviderInterface
{
    /**
     * Registers services on the given container.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param Container $pimple A container instance
     */
    public function register(Container $pimple)
    {
        $pimple['user'] = function ($pimple) {
            return new User($pimple['access_token']);
        };

        $group = function ($pimple) {
            return new Group($pimple['access_token']);
        };

        $tag = function ($pimple) {
            return new Tag($pimple['access_token']);
        };

        $pimple['user_group'] = $group;
        $pimple['user.group'] = $group;

        $pimple['user_tag'] = $tag;
        $pimple['user.tag'] = $tag;
    }
}


<?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\Validator\ValidatorAbstract;

/**
 * Service to validate
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class ValidatorService{

    /**
     *
     * @param string $validator
     * @param mixed $value
     * @return mixed
     */
	public function validate($validator,$value){
        /**
         * @var ValidatorAbstract $validator
         */
		$validator=new $validator();
		return $validator->validate($value);
	}

	/**
	 *
	 * @param mixed[][] $validators - array with value and validators:
	 * [
	 * 'field name'=>[
	 *		'validator rule class'
	 *		,'value'
	 *		]
	 *	,'another field name'=>[
	 *		'validator rule class'
	 *		,'value'
	 *		]
	 *	]
	 * @return array with errors. If success then empty array.
	 */
	public function multiValidate($validators){
		$errors=[];
		foreach($validators as $kValidate=>$validate){
			$error=$this->validate($validate[0],$validate[1]);
			if($error)
				$errors[]=['field'=>$kValidate,'message'=>$error];
		}

		return $errors;
	}

	/**
	 * Validate data from storage array.
	 *
	 * @param mixed[] $validators - array with rules validation example: ['nameField'=>'Validator\ExampleClassValidator']
	 * @param mixed[] $storage - array with values, example ['nameField1'=>'value1','nameField2'=>'value2']
	 * @return string[] with errors. If success then empty array.
	 */
	public function storageValidate($validators,$storage){
		$errors=[];
		foreach($validators as $kValidate=>$validate){
			if(!isset($storage[$kValidate])){
				$errors[]=['field'=>$kValidate,'message'=>'Value '.$kValidate.' not found.'];
				continue;
			}

			$error=$this->validate($validate,$storage[$kValidate]);
			if($error)
				$errors[]=['field'=>$kValidate,'message'=>$error];
		}

		return $errors;

	}
}


<?php

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

namespace dektrium\user\controllers;

use dektrium\user\Finder;
use dektrium\user\models\User;
use dektrium\user\models\UserSearch;
use yii\base\Model;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * AdminController allows you to administrate users.
 *
 * @property \dektrium\user\Module $module
 * @author Dmitry Erofeev <dmeroff@gmail.com
 */
class AdminController extends Controller
{
    /** @var Finder */
    protected $finder;

    /**
     * @param string $id
     * @param \yii\base\Module $module
     * @param Finder $finder
     * @param array $config
     */
    public function __construct($id, $module, Finder $finder, $config = [])
    {
        $this->finder = $finder;
        parent::__construct($id, $module, $config);
    }

    /** @inheritdoc */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete'  => ['post'],
                    'confirm' => ['post'],
                    'block'   => ['post']
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'create', 'update', 'delete', 'block', 'confirm'],
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function ($rule, $action) {
                            return \Yii::$app->user->identity->getIsAdmin();
                        }
                    ],
                ]
            ]
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel  = \Yii::createObject(UserSearch::className());
        $dataProvider = $searchModel->search($_GET);

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

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionCreate()
    {
        /** @var User $user */
        $user = \Yii::createObject([
            'class'    => User::className(),
            'scenario' => 'create',
        ]);

        $this->performAjaxValidation($user);

        if ($user->load(\Yii::$app->request->post()) && $user->create()) {
            \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'User has been created'));
            return $this->redirect(['index']);
        }

        return $this->render('create', [
            'user' => $user
        ]);
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'index' page.
     * @param  integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $user = $this->findModel($id);
        $user->scenario = 'update';
        $profile = $this->finder->findProfileById($id);
        $r = \Yii::$app->request;

        $this->performAjaxValidation([$user, $profile]);

        if ($user->load($r->post()) && $profile->load($r->post()) && $user->save() && $profile->save()) {
            \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'User has been updated'));
            return $this->refresh();
        }

        return $this->render('update', [
            'user'    => $user,
            'profile' => $profile,
            'module'  => $this->module,
        ]);
    }

    /**
     * Confirms the User.
     * @param integer $id
     * @param string  $back
     * @return \yii\web\Response
     */
    public function actionConfirm($id, $back = 'index')
    {
        $this->findModel($id)->confirm();
        \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'User has been confirmed'));
        $url = $back == 'index' ? ['index'] : ['update', 'id' => $id];
        return $this->redirect($url);
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param  integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if ($id == \Yii::$app->user->getId()) {
            \Yii::$app->getSession()->setFlash('danger', \Yii::t('user', 'You can not remove your own account'));
        } else {
            $this->findModel($id)->delete();
            \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'User has been deleted'));
        }
        return $this->redirect(['index']);
    }

    /**
     * Blocks the user.
     * @param  integer $id
     * @param  string  $back
     * @return \yii\web\Response
     */
    public function actionBlock($id, $back = 'index')
    {
        if ($id == \Yii::$app->user->getId()) {
            \Yii::$app->getSession()->setFlash('danger', \Yii::t('user', 'You can not block your own account'));
        } else {
            $user = $this->findModel($id);
            if ($user->getIsBlocked()) {
                $user->unblock();
                \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'User has been unblocked'));
            } else {
                $user->block();
                \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'User has been blocked'));
            }
        }
        $url = $back == 'index' ? ['index'] : ['update', 'id' => $id];
        return $this->redirect($url);
    }

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

    /**
     * Performs AJAX validation.
     * @param array|Model $models
     * @throws \yii\base\ExitException
     */
    protected function performAjaxValidation($models)
    {
        if (\Yii::$app->request->isAjax) {
            if (is_array($models)) {
                $result = [];
                foreach ($models as $model) {
                    if ($model->load(\Yii::$app->request->post())) {
                        \Yii::$app->response->format = Response::FORMAT_JSON;
                        $result = array_merge($result, ActiveForm::validate($model));
                    }
                }
                echo json_encode($result);
                \Yii::$app->end();
            } else {
                if ($models->load(\Yii::$app->request->post())) {
                    \Yii::$app->response->format = Response::FORMAT_JSON;
                    echo json_encode(ActiveForm::validate($models));
                    \Yii::$app->end();
                }
            }
        }
    }
}


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

namespace Praxigento\BonusHybrid\Service;

use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Request as AGetPeriodRequest;
use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Response as AGetPeriodResponse;
use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Service\Downgrade\Request as ARequest;
use Praxigento\BonusHybrid\Service\Downgrade\Response as AResponse;

/**
 * Change status for unqualified customers and change downline tree.
 *
 * This is internal service (for this module only), so it has no own interface.
 */
class Downgrade
{
    /** @var \Praxigento\BonusHybrid\Service\Downgrade\A\Calc */
    private $aCalc;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwl;
    /** @var \Praxigento\BonusBase\Repo\Dao\Calculation */
    private $daoCalc;
    /** @var \Praxigento\BonusHybrid\Helper\Marker\Downgrade */
    private $hlpMarkDowngrade;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent */
    private $servPeriodGet;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\BonusBase\Repo\Dao\Calculation $daoCalc,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwl,
        \Praxigento\BonusHybrid\Helper\Marker\Downgrade $hlpMarkDowngrade,
        \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent $servPeriodGet,
        \Praxigento\BonusHybrid\Service\Downgrade\A\Calc $aCalc
    ) {
        $this->logger = $logger;
        $this->daoCalc = $daoCalc;
        $this->daoBonDwl = $daoBonDwl;
        $this->hlpMarkDowngrade = $hlpMarkDowngrade;
        $this->servPeriodGet = $servPeriodGet;
        $this->aCalc = $aCalc;
    }

    /**
     * @param ARequest $req
     * @return AResponse
     * @throws \Throwable
     */
    public function exec($req)
    {
        assert($req instanceof ARequest);
        $this->logger->info("Unqualified customers downgrade is started.");

        /**
         * perform processing
         */
        $this->hlpMarkDowngrade->setMark();
        /* get dependent calculation data */
        /**
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $writeOffCalc
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $processCalc
         */
        list($writeOffCalc, $processCalc) = $this->getCalcData();
        $writeOffCalcId = $writeOffCalc->getId();
        $treePlain = $this->daoBonDwl->getByCalcId($writeOffCalcId);
        $this->aCalc->exec($treePlain);
        /* mark this calculation complete */
        $calcId = $processCalc->getId();
        $this->daoCalc->markComplete($calcId);
        $this->hlpMarkDowngrade->cleanMark();

        /* compose results  */
        $this->logger->info("Unqualified customers downgrade is completed.");
        $result = new AResponse();
        return $result;
    }

    /**
     * Get data for periods & calculations.
     *
     * @return array [$writeOffCalc, $writeOffPeriod, $processCalc]
     * @throws \Exception
     */
    private function getCalcData()
    {
        /**
         * Create Unqualified Process (Downgrade) calculation.
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode(Cfg::CODE_TYPE_CALC_PV_WRITE_OFF);
        $req->setDepCalcTypeCode(Cfg::CODE_TYPE_CALC_UNQUALIFIED_PROCESS);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $writeOffCalc */
        $writeOffCalc = $resp->getBaseCalcData();
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $pwWriteOffCalc */
        $processCalc = $resp->getDepCalcData();
        /**
         * Compose result.
         */
        $result = [$writeOffCalc, $processCalc];
        return $result;
    }

}


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

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

namespace EasyWeChat\Core;

use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\FilesystemCache;
use EasyWeChat\Core\Exceptions\HttpException;

/**
 * Class AccessToken.
 */
class AccessToken
{
    /**
     * App ID.
     *
     * @var string
     */
    protected $appId;

    /**
     * App secret.
     *
     * @var string
     */
    protected $secret;

    /**
     * Cache.
     *
     * @var Cache
     */
    protected $cache;

    /**
     * Cache Key.
     *
     * @var string
     */
    protected $cacheKey;

    /**
     * Http instance.
     *
     * @var Http
     */
    protected $http;

    /**
     * Query name.
     *
     * @var string
     */
    protected $queryName = 'access_token';

    /**
     * Response Json key name.
     *
     * @var string
     */
    protected $tokenJsonKey = 'access_token';

    /**
     * Cache key prefix.
     *
     * @var string
     */
    protected $prefix = 'easywechat.common.access_token.';

    // API
    const API_TOKEN_GET = 'https://api.weixin.qq.com/cgi-bin/token';

    /**
     * Constructor.
     *
     * @param string                       $appId
     * @param string                       $secret
     * @param \Doctrine\Common\Cache\Cache $cache
     */
    public function __construct($appId, $secret, Cache $cache = null)
    {
        $this->appId = $appId;
        $this->secret = $secret;
        $this->cache = $cache;
    }

    /**
     * Get token from WeChat API.
     *
     * @param bool $forceRefresh
     *
     * @return string
     */
    public function getToken($forceRefresh = false)
    {
        $cacheKey = $this->getCacheKey();
        $cached = $this->getCache()->fetch($cacheKey);

        if ($forceRefresh || empty($cached)) {
            $token = $this->getTokenFromServer();

            // XXX: T_T... 7200 - 1500
            $this->getCache()->save($cacheKey, $token[$this->tokenJsonKey], $token['expires_in'] - 1500);

            return $token[$this->tokenJsonKey];
        }

        return $cached;
    }

    /**
     * 设置自定义 token.
     *
     * @param string $token
     * @param int    $expires
     *
     * @return $this
     */
    public function setToken($token, $expires = 7200)
    {
        $this->getCache()->save($this->getCacheKey(), $token, $expires - 1500);

        return $this;
    }

    /**
     * Return the app id.
     *
     * @return string
     */
    public function getAppId()
    {
        return $this->appId;
    }

    /**
     * Return the secret.
     *
     * @return string
     */
    public function getSecret()
    {
        return $this->secret;
    }

    /**
     * Set cache instance.
     *
     * @param \Doctrine\Common\Cache\Cache $cache
     *
     * @return AccessToken
     */
    public function setCache(Cache $cache)
    {
        $this->cache = $cache;

        return $this;
    }

    /**
     * Return the cache manager.
     *
     * @return \Doctrine\Common\Cache\Cache
     */
    public function getCache()
    {
        return $this->cache ?: $this->cache = new FilesystemCache(sys_get_temp_dir());
    }

    /**
     * Set the query name.
     *
     * @param string $queryName
     *
     * @return $this
     */
    public function setQueryName($queryName)
    {
        $this->queryName = $queryName;

        return $this;
    }

    /**
     * Return the query name.
     *
     * @return string
     */
    public function getQueryName()
    {
        return $this->queryName;
    }

    /**
     * Return the API request queries.
     *
     * @return array
     */
    public function getQueryFields()
    {
        return [$this->queryName => $this->getToken()];
    }

    /**
     * Get the access token from WeChat server.
     *
     * @throws \EasyWeChat\Core\Exceptions\HttpException
     *
     * @return string
     */
    public function getTokenFromServer()
    {
        $params = [
            'appid' => $this->appId,
            'secret' => $this->secret,
            'grant_type' => 'client_credential',
        ];

        $http = $this->getHttp();

        $token = $http->parseJSON($http->get(self::API_TOKEN_GET, $params));

        if (empty($token[$this->tokenJsonKey])) {
            throw new HttpException('Request AccessToken fail. response: '.json_encode($token, JSON_UNESCAPED_UNICODE));
        }

        return $token;
    }

    /**
     * Return the http instance.
     *
     * @return \EasyWeChat\Core\Http
     */
    public function getHttp()
    {
        return $this->http ?: $this->http = new Http();
    }

    /**
     * Set the http instance.
     *
     * @param \EasyWeChat\Core\Http $http
     *
     * @return $this
     */
    public function setHttp(Http $http)
    {
        $this->http = $http;

        return $this;
    }

    /**
     * Set the access token prefix.
     *
     * @param string $prefix
     *
     * @return $this
     */
    public function setPrefix($prefix)
    {
        $this->prefix = $prefix;

        return $this;
    }

    /**
     * Set access token cache key.
     *
     * @param string $cacheKey
     *
     * @return $this
     */
    public function setCacheKey($cacheKey)
    {
        $this->cacheKey = $cacheKey;

        return $this;
    }

    /**
     * Get access token cache key.
     *
     * @return string $this->cacheKey
     */
    public function getCacheKey()
    {
        if (is_null($this->cacheKey)) {
            return $this->prefix.$this->appId;
        }

        return $this->cacheKey;
    }
}


<?php

namespace Dwo\FlaggingBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * @author Dave Www <davewwwo@gmail.com>
 */
class Configuration implements ConfigurationInterface
{
    /**
     * Generates the configuration tree builder.
     *
     * @return TreeBuilder The tree builder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('dwo_flagging');

        $rootNode
            ->children()

                ->arrayNode('manager')
                    ->addDefaultsIfNotSet()

                    ->children()
                        ->scalarNode('feature')->defaultValue('dwo_flagging.manager.feature.config')->end()
                        ->scalarNode('voter')->defaultValue('dwo_flagging.manager.voter.config')->end()
                    ->end()
                ->end()

                /**
                 *  Features
                 */
                ->arrayNode('features')
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->children()

                            /**
                             *  Breaker for Feature
                             */
                            ->arrayNode('breaker')
                                ->performNoDeepMerging()
                                ->prototype('array')
                                    ->prototype('array')
                                        ->prototype('variable')->end()
                                    ->end()
                                ->end()
                            ->end()

                            /**
                             *  Filter for Feature
                             */
                            ->arrayNode('filters')
                                ->performNoDeepMerging()
                                ->prototype('array')
                                    ->useAttributeAsKey('filter')
                                    ->prototype('array')
                                        ->prototype('variable')->end()
                                    ->end()
                                ->end()
                            ->end()

                            /**
                             *  Values for Feature
                             */
                            ->arrayNode('values')
                                ->performNoDeepMerging()
                                ->prototype('array')
                                    ->children()

                                        /**
                                         * Value
                                         */
                                        ->variableNode('value')->end()
                                        ->booleanNode('is_feature')->end()

                                        /**
                                         *  Filter for Value
                                         */
                                        ->arrayNode('filters')
                                            ->prototype('array')
                                                ->prototype('array')
                                                    ->prototype('variable')->end()
                                                ->end()
                                            ->end()
                                        ->end()

                                    ->end()
                                ->end()
                            ->end()

                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}


<?php

namespace Biigle\CachedOpenStack;

use DateTime;
use DateInterval;
use OpenStack\Identity\v3\Service;
use OpenStack\Common\Api\ApiInterface;
use OpenStack\Common\Api\ClientInterface;
use Illuminate\Cache\CacheManager as Cache;

class CachedIdentityService extends Service
{
   /**
    * The cache instance to use.
    *
    * @var Cache
    */
   protected $cache;

   /**
    * Set the cache instance to use.
    *
    * @param Cache $cache
    */
   public function setCache(Cache $cache)
   {
      $this->cache = $cache;
   }

   /**
    * {@inheritdoc}
    */
   public function authenticate(array $options): array
   {
      $options['cachedToken'] = $this->getCachedToken($options);

      return parent::authenticate($options);
   }

   /**
    * Get the cached token.
    *
    * Creates a new cached token if the old one is expired or does not exist.
    *
    * @param array $options OpenStack options.
    *
    * @return array
    */
   protected function getCachedToken(array $options)
   {
      $authOptions = array_intersect_key($options, $this->api->postTokens()['params']);

      // Determine a unique key for the used authentication options. We add the authUrl
      // because it is possible to use the same credentials for a different OpenStack
      // instance, which should use a different authentication token.
      $optionsToHash = array_merge($authOptions, array_intersect_key($options, [
         'authUrl' => true,
      ]));
      // Do not include the password in the insecure hash.
      if (isset($optionsToHash['user'])) {
         unset($optionsToHash['user']['password']);
      }
      $key = 'openstack-token-'.md5(json_encode($optionsToHash));

      if ($this->cache->has($key)) {
         return $this->cache->get($key);
      }

      $token = $this->generateToken($authOptions);
      $cachedToken = $token->export();

      // Cache the token for 1 minute less than it's considered valid to avoid the edge case
      // discussed here: https://github.com/mzur/laravel-openstack-swift/issues/1
      $expiresAt = new DateTime($cachedToken['expires_at']);
      $this->cache->put($key, $cachedToken, $expiresAt->sub(new DateInterval('PT1M')));

      return $cachedToken;
   }
}


<?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\Configuration\Option;

use Predis\Configuration\OptionInterface;
use Predis\Configuration\OptionsInterface;
use Predis\Connection\Factory;
use Predis\Connection\FactoryInterface;

/**
 * Configures a connection factory used by the client to create new connection
 * instances for single Redis nodes.
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class Connections implements OptionInterface
{
    /**
     * {@inheritdoc}
     */
    public function filter(OptionsInterface $options, $value)
    {
        if (is_callable($value)) {
            $value = call_user_func($value, $options);
        }

        if ($value instanceof FactoryInterface) {
            return $value;
        } elseif (is_array($value)) {
            $factory = $this->getDefault($options);

            foreach ($value as $scheme => $initializer) {
                $factory->define($scheme, $initializer);
            }

            return $factory;
        } else {
            $class = get_called_class();

            throw new \InvalidArgumentException("$class expects a valid connection factory");
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDefault(OptionsInterface $options)
    {
        $factory = new Factory();

        if ($options->defined('parameters')) {
            $factory->setDefaultParameters($options->parameters);
        }

        return $factory;
    }
}


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

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

	/**
	 *
	 * @var Environment
	 */
	private $environment;

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

    /**
     * {@inheritdoc}
     */
	public function execute(\Exception $exception){
		error_log($exception->getMessage()." ".$exception->getFile()."(".$exception->getLine().")");

		if(!$this->environment->isDebug()){
			return;
		}

		$presenter=new HTTPErrorPresenter($this->environment);
		$response=new Response();
		$response->setContent($exception);
		$request=new EmptyRequest('',null);

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

	}

}


<?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\Action\Block;

use RedKiteCms\Action\BaseAction;
use RedKiteCms\Content\BlockManager\BlockManagerAdd;
use RedKiteCms\Content\BlockManager\BlockManagerRemove;
use Silex\Application;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class RemoveBlockAction defines the object assigned to remove a block from a web site page
 *
 * @package RedKiteCms\Action
 */
class RemoveBlockAction extends BaseAction
{
    /**
     * {@inheritdoc}
     */
    public function execute(array $options, $username)
    {
        $data = $options["data"];
        $removeOptions = array(
            'page' => $data['page'],
            'language' => $data['language'],
            'country' => $data['country'],
            'slot' => $data['slot'],
            'blockname' => $data['name'],
        );

        $blockManager = $this->app["red_kite_cms.blocks_manager_factory"]->create('remove');

        return $blockManager->remove($this->app["red_kite_cms.configuration_handler"]->siteDir(), $removeOptions, $username);
    }
}


<?php

namespace Senhung\CLI;

require_once 'Command.php';
require_once 'Help.php';

/**
 * Class CommandEntry
 * @package Senhung\CLI
 */
class CommandEntry
{
    /** @var array $commands */
    private static $commands;
    /** @var bool $initialized */
    private static $initialized = false;

    /**
     * Initialize the class if haven't been initialized
     *
     * @return void
     */
    private static function initialize(): void
    {
        /* If Not Initialized, Initialize */
        if (!self::$initialized) {
            self::$commands = Service::getAllCommands();
        }
    }

    /**
     * Command entry for running the desire command
     *
     * @param $argv
     * @return void
     */
    public static function entry($argv): void
    {
        self::initialize();

        /* Check Command Entered */
        if (isset($argv[1])) {
            $command = $argv[1];
        } else {
            return;
        }

        /* Check Command Defined */
        if (!in_array($command, array_keys(self::$commands))) {
            return;
        }

        $arguments = [];
        $options = [];

        /* Parse Arguments and Options */
        for ($index = 2; $index < count($argv); $index++) {
            /* Get Argument/Option Key and Value */
            list($key, $value) = Service::parse($argv[$index]);

            /* Is Option */
            if (Service::determineTypeOfWord($argv[$index]) == Service::OPTION_TYPE) {
                /* Flag */
                if (!$value) {
                    $options[$key] = true;
                }

                /* Parameter */
                else {
                    $options[$key] = $value;
                }
            }

            /* Is Argument */
            else {
                $arguments[] = $key;
            }
        }

        /* Run Command Handle */
        Service::runCommand(self::$commands[$command], $arguments, $options);
    }

    /**
     * Load all command classes
     *
     * @param string $dir
     * @return void
     */
    public static function load(string $dir): void
    {
        self::initialize();

        /* Make Directory */
        $commandDir = $_SERVER['DOCUMENT_ROOT'] . $dir;

        /* Get All Files In Directory */
        $files = scandir($commandDir);

        /* Require Files */
        foreach ($files as $file) {
            if ($file == '.' || $file == '..') {
                continue;
            }

            require_once $_SERVER['DOCUMENT_ROOT'] . $dir . '/' . $file;
        }
    }

    /**
     * Get all commands
     *
     * @return array
     */
    public static function getCommands(): array
    {
        return self::$commands;
    }
}


<?php

/*
 * Copyright (C) 2015 Champs-Libres Coopérative <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\PersonBundle\Timeline;

use Chill\MainBundle\Timeline\TimelineProviderInterface;
use Doctrine\ORM\EntityManager;

/**
 * Provide method to build timeline for accompanying periods
 *
 * This class is resued by TimelineAccompanyingPeriodOpening (for opening)
 * and TimelineAccompanyingPeriodClosing (for closing)
 *
 * @author Julien Fastré <julien.fastre@champs-libres.coop>
 */
abstract class AbstractTimelineAccompanyingPeriod implements TimelineProviderInterface
{
    /**
     *
     * @var EntityManager
     */
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     *
     * {@inheritDoc}
     */
    public function getEntities(array $ids)
    {
        $periods = $this->em
                ->getRepository('ChillPersonBundle:AccompanyingPeriod')
                ->findBy(array('id' => $ids));

        //set results in an associative array with id as indexes
        $results = array();
        foreach($periods as $period) {
            $results[$period->getId()] = $period;
        }

        return $results;
    }

    /**
     * prepare fetchQuery without `WHERE` and `TYPE` clause
     *
     * @param string $context
     * @param array $args
     * @return array
     * @throws \LogicException
     */
    protected function basicFetchQuery($context, array $args)
    {
        if ($context !== 'person') {
            throw new \LogicException('TimelineAccompanyingPeriod is not able '
                    . 'to render context '.$context);
        }

        $metadata = $this->em
                ->getClassMetadata('ChillPersonBundle:AccompanyingPeriod')
                ;

        return array(
            'id' => $metadata->getColumnName('id'),
            'date' => $metadata->getColumnName('openingDate'),
            'FROM' => $metadata->getTableName(),
        );
    }

    /**
     * return the expected response for TimelineProviderInterface::getEntityTemplate
     *
     * @param string $template the template for rendering
     * @param mixed $entity
     * @param string $context
     * @param array $args
     * @return array
     */
    protected function getBasicEntityTemplate($template, $entity, $context, array $args)
    {
        return array(
            'template' => $template,
            'template_data' => ['person' => $args['person'], 'period' => $entity]
        );
    }
}


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

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use RedKiteCms\Rendering\Controller\Queue\SaveQueueController as BaseSaveQueueController;
use Symfony\Component\HttpFoundation\Response;

/**
 * This object implements the Silex controller to save the frontend operations queue to the backend
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Page
 */
class SaveQueueController extends BaseSaveQueueController
{
    /**
     * Saves the queue action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function saveAction(Request $request, Application $app)
    {
        $options = array(
            "request" => $request,
            "configuration_handler" => $app["red_kite_cms.configuration_handler"],
            'security' => $app["security"],
            "queue_manager" => $app["red_kite_cms.queue_manager"],
        );

        $response = parent::save($options);
        if ($app["red_kite_cms.queue_manager"]->hasQueue() && $response->getContent() == "Queue saved") {
            $lastRoute = $request->getSession()->get('last_uri');
            return $app->redirect($lastRoute);
        }

        return $response;
    }
}


<?php

/*
 * This file is part of the YepsuaGeneratorBundle.
 *
 * (c) Omar Yepez <omar.yepez@yepsua.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Yepsua\GeneratorBundle\Generator;

use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Doctrine\ORM\Mapping\ClassMetadataInfo;

/**
 * Generates a CRUD controller.
 *
 * @author Omar Yepez <omar.yepez@yepsua.com>
 */
class DoctrineCrudGenerator extends \Sensio\Bundle\GeneratorBundle\Generator\DoctrineCrudGenerator
{
    protected $options;

    protected function renderFile($template, $target, $parameters)
    {
       $parameters = array_merge($parameters, array(
         'consoleOptions' => $this->getOptions(),
         'fields' => $this->metadata->fieldMappings,
         'associationMappings' => $this->metadata->associationMappings)
       );
       parent::renderFile($template, $target, $parameters);
    }

    /**
     * Generate the CRUD controller.
     *
     * @param BundleInterface   $bundle           A bundle object
     * @param string            $entity           The entity relative class name
     * @param ClassMetadataInfo $metadata         The entity class metadata
     * @param string            $format           The configuration format (xml, yaml, annotation)
     * @param string            $routePrefix      The route name prefix
     * @param array             $needWriteActions Wether or not to generate write actions
     *
     * @throws \RuntimeException
     */
    public function generate(BundleInterface $bundle, $entity, ClassMetadataInfo $metadata, $format, $routePrefix, $needWriteActions, $forceOverwrite)
    {
        parent::generate($bundle, $entity, $metadata, $format, $routePrefix, $needWriteActions, $forceOverwrite);
        if($this->getOption('with_kanban')){
            $dir = sprintf('%s/Resources/views/%s', $this->bundle->getPath(), str_replace('\\', '/', $this->entity));
            $this->generateKanbanView($dir);
        }

    }

    /**
     * Generates the show.html.twig template in the final bundle.
     *
     * @param string $dir The path to the folder that hosts templates in the bundle
     */
    protected function generateKanbanView($dir)
    {
        $this->renderFile('crud/views/kanban.html.twig.twig', $dir.'/kanban.html.twig', array(
            'bundle'            => $this->bundle->getName(),
            'entity'            => $this->entity,
            'fields'            => $this->metadata->fieldMappings,
            'actions'           => $this->actions,
            'route_prefix'      => $this->routePrefix,
            'route_name_prefix' => $this->routeNamePrefix,
        ));
    }

    public function getOptions() {
        return $this->options;
    }

    public function getOption($key) {
        return $this->options[$key];
    }

    public function addOption($key, $value) {
        return $this->options[$key] = $value;
    }

    public function setOptions($options) {
        $this->options = $options;
    }
}


<?php
namespace core\manage\logic;

use think\Db;
use think\Config;
use cms\Logic;
use cms\Common;
use MySQLDump;
use lookfeel\common\Format;

class DatabaseLogic extends Logic
{

    /**
     * 备份记录
     *
     * @return array
     */
    public function getList()
    {
        $list = $this->model->order('id desc')->select();
        $user_select = MemberLogic::instance()->getUserSelect();
        foreach ($list as &$vo) {
            $vo['dump_size'] = Common::formatBytes($vo['dump_size']);
            $vo['user'] = isset($user_select[$vo['dump_uid']]) ? $user_select[$vo['dump_uid']] : [
                'name' => 'unknown'
            ];
        }
        return $list;
    }

    /**
     * 数据表
     *
     * @return array
     */
    public function getTableList()
    {
        $list = array_map('array_change_key_case', Db::query('SHOW TABLE STATUS'));
        foreach ($list as &$vo) {
            $vo['data_format'] = Common::formatBytes($vo['data_length']);
        }
        return $list;
    }

    /**
     * 备份
     *
     * @param number $user_id
     * @return array
     */
    public function addBakup($user_id)
    {
        try {

            $connection = $this->getConnection();
            $dump = new MySQLDump($connection);

            // 备份数据库
            $bakup_path = $this->getBakupPath();
            $file_path = '/dump_' . date('Ymd_His') . '.sql';
            $dump->save($bakup_path . $file_path);

            // 备份记录
            $data = [
                'dump_uid' => $user_id,
                'dump_size' => filesize($bakup_path . $file_path),
                'dump_file' => $file_path,
                'dump_time' => time()
            ];
            $this->model->add($data);

            return Format::formatResult(1, '备份数据库成功');
        } catch (\Exception $e) {
            return Format::formatResult(0, '备份数据库失败:' . $e->getMessage());
        }
    }

    /**
     * 删除备份
     *
     * @param number $bakup_id
     * @return number
     */
    public function delBakup($bakup_id)
    {
        try {
            $bakup_path = $this->getBakupPath();
            $bakup = $this->model->get($bakup_id);
            unlink($bakup_path . $bakup['dump_file']);
        } catch (\Exception $e) {}

        return $this->model->del($bakup_id);
    }

    /**
     * 优化表
     */
    public function optimize()
    {
        $list = array_map('array_change_key_case', Db::query('SHOW TABLE STATUS'));
        foreach ($list as $vo) {
            Db::query('OPTIMIZE TABLE `' . $vo['name'] . '`');
        }
    }

    /**
     * 修复表
     */
    public function repair()
    {
        $list = array_map('array_change_key_case', Db::query('SHOW TABLE STATUS'));
        foreach ($list as $vo) {
            Db::query('REPAIR TABLE `' . $vo['name'] . '`');
        }
    }

    /**
     * 数据库连接
     *
     * @return \mysqli
     */
    public function getConnection()
    {
        $database = Config::get('database');
        return new \mysqli($database['hostname'], $database['username'], $database['password'], $database['database'], $database['hostport']);
    }

    /**
     * 备份路径
     *
     * @return atring
     */
    public function getBakupPath()
    {
        return Config::get('bakup_path');
    }
}


<?php

namespace BlogBundle\Twig;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Twig_SimpleFunction;
use BlogBundle\Entity\Category;
use BlogBundle\Entity\Tag;

/**
 * Class BlogExtension
 */
class BlogExtension extends \Twig_Extension
{

    private $container;

    public function setContainer($container)
    {
        $this->container = $container;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return array(
            new Twig_SimpleFunction('blog_list', array($this, 'blogList'), array('is_safe' => array('html'))),
            new Twig_SimpleFunction('blog_search', array($this, 'blogSearch')),
            new Twig_SimpleFunction('blog_categories', array($this, 'blogCategories')),
            new Twig_SimpleFunction('blog_tags', array($this, 'blogTags')),
            new Twig_SimpleFunction('blog_feed', array($this, 'blogFeed')),
            new Twig_SimpleFunction('blog_social', array($this, 'blogSocial')),
            new Twig_SimpleFunction('blog_history', array($this, 'blogHistory')),
            new Twig_SimpleFunction('countArrayValues', array($this, 'countArrayValues')),
            new Twig_SimpleFunction('shareUrlBlog', array($this, 'shareUrlBlog'), array('is_safe' => array('html'))),
            new Twig_SimpleFunction('countPost', array($this, 'countPost')),
            new Twig_SimpleFunction('get_carousel_items_blog', array($this, 'getCarouselItemsBlog')),
            new Twig_SimpleFunction('get_posts', array($this, 'getPosts')),
            new Twig_SimpleFunction('get_tags', array($this, 'getTags')),
            new Twig_SimpleFunction('get_blog_categories', array($this, 'getCategories')),
            new Twig_SimpleFunction('get_blog_total_items', array($this, 'getBlogTotalItems')),
        );
    }

    public function blogList($limit=null, $categoryId=null, $tagId=null)
    {
        $twig = $this->container->get('twig');
        $em = $this->container->get('doctrine')->getManager();

        $qb = $em->getRepository('BlogBundle:Post')->createQueryBuilder('p')
                ->join('p.translations', 't');
        if(!is_null($limit)){
            $qb->setMaxResults($limit);
        }
        if(!is_null($categoryId)){
            $qb->join('p.categories', 'c')
               ->where('c.id = :categoryId')
               ->setParameter('categoryId', $categoryId);
        }
        if(!is_null($tagId)){
            $qb->join('p.tags', 'tag')
               ->where('tag.id = :tag')
               ->setParameter('tag', $tagId);
        }
        $qb->orderBy('p.published', 'ASC');

        $posts = $qb->getQuery()->getResult();

        $content = $twig->render('BlogBundle:Blog/Block:_list.html.twig', array('posts' => $posts, 'categoryId' => $categoryId));
        return $content;
    }

    public function blogSearch()
    {
        $twig = $this->container->get('twig');
        $content = $twig->render('BlogBundle:Blog/Block:_search.html.twig', array());
        return $content;
    }

    public function blogCategories()
    {
        $twig = $this->container->get('twig');
        $content = $twig->render('BlogBundle:Blog/Block:_categories.html.twig', array());
        return $content;
    }
    public function blogTags()
    {
        $twig = $this->container->get('twig');
        $content = $twig->render('BlogBundle:Blog/Block:_tags.html.twig', array());
        return $content;
    }

    public function blogFeed()
    {
        $twig = $this->container->get('twig');

        $content = $twig->render('BlogBundle:Blog/Block:_feed.html.twig', array());

        return $content;
    }

    public function blogSocial()
    {
        $twig = $this->container->get('twig');

        $content = $twig->render('BlogBundle:Blog/Block:_social.html.twig', array());

        return $content;
    }

    public function blogHistory()
    {
        $blogManager = $this->container->get('blog_manager');
        $history = $blogManager->blogHistory();

        $twig = $this->container->get('twig');

        $content = $twig->render('BlogBundle:Blog/Block:_blog.history.html.twig', array(
            'history' => $history
            ));

        return $content;
    }

     public function countArrayValues($array)
    {
        $count = 0;

        foreach($array as $item) {  // go thought the first level
            foreach($item as $value) {  // go through the second level
                $count++;
            }
        }

        return $count;
    }

    /**
    * Returns the part of a feedID
    *
    * @param string $feedID  ID of the feed to load
    */
    public function shareUrlBlog($url, $big=false, $title)
    {
        if (!is_numeric(strpos($url, 'http'))) {
            $core = $this->container->getParameter('core');
            $url = $core['server_base_url'] . $url;
        }
        $text = $title;
        $tweetUrl =  'https://twitter.com/share?url='.$url.'&counturl='.$url.'&text='.$text;
        $faceUrl = 'http://www.facebook.com/sharer/sharer.php?u='.$url.'&text='.$text;
        $googleUrl = 'https://plus.google.com/share?url='.$url;
        $linkedUrl = 'https://www.linkedin.com/shareArticle?summary=&ro=false&title='.$text.'&mini=true&url='.$url.'&source=';

        $twig = $this->container->get('twig');
        $content = $twig->render('BlogBundle:Blog/Block:_share.html.twig', array(
            "tweetUrl" => $tweetUrl,
            "faceUrl" => $faceUrl,
            "googleUrl" => $googleUrl,
            "linkedUrl" => $linkedUrl,
            "id" => uniqid(),
            "big" => $big
        ));

        return $content;
    }

    /**
    * Returns integer counter
    *
    * @param object $actor
    */
    public function countPost($actor)
    {
        $em = $this->container->get('doctrine')->getManager();
        $entities = $em->getRepository('BlogBundle:Post')->findBy(array('actor' => $actor));

        return count($entities);
    }

    /**
     * Returns all items from blog category.
     *
     * @return ArrayCollection
     */
    public function getCarouselItemsBlog($entity)
    {
        $em = $this->container->get('doctrine')->getManager();

        if($entity instanceof Category){
            $qb = $em->getRepository('BlogBundle:Post')
                ->createQueryBuilder('p')
                ->join('p.categories', 'c')
                ->join('p.translations', 't')
                ->where('c.id = :category')
                ->andWhere('p.highlighted = true')
                ->setParameter('category', $entity->getId())
                ->setMaxResults(3)
                ->orderBy('p.published', 'DESC');
        }elseif($entity instanceof Tag){
            $qb = $em->getRepository('BlogBundle:Post')
                ->createQueryBuilder('p')
                ->join('p.tags', 'tag')
                ->join('p.translations', 't')
                ->where('t.id = :tag')
                ->andWhere('p.highlighted = true')
                ->setParameter('tag', $entity->getId())
                ->setMaxResults(3)
                ->orderBy('p.published', 'DESC');
        }

        $entities = $qb->getQuery()->getResult();
        return $entities;
    }

    /**
    * Returns array posts
    *
    * @param object $post
    */
    public function getPosts($limit=null, $offset=null)
    {
        $em = $this->container->get('doctrine')->getManager();
        if(is_null($limit) && is_null($offset)){
            $entities = $em->getRepository('BlogBundle:Post')->findBy(array(),array('published' =>  'DESC'));
        }elseif(is_null($limit) && !is_null($offset)){
            $entities = $em->getRepository('BlogBundle:Post')->findBy(array(),array('published' =>  'DESC'), $limit);
        }elseif(!is_null($limit) && !is_null($offset)){
            $entities = $em->getRepository('BlogBundle:Post')->findBy(array(),array('published' =>  'DESC'), $limit, $offset);
        }

        return $entities;
    }

    /**
    * Returns array tags
    *
    * @param object $tag
    */
    public function getCategories()
    {
        $em = $this->container->get('doctrine')->getManager();
        $entities = $em->getRepository('BlogBundle:Category')->findBy(array('active' => true),array('name' =>  'ASC'));

        return $entities;
    }

    /**
    * Returns array tags
    *
    * @param object $tag
    */
    public function getTags()
    {
        $em = $this->container->get('doctrine')->getManager();
        $entities = $em->getRepository('BlogBundle:Tag')->findBy(array(),array('name' =>  'ASC'));

        return $entities;
    }

    /**
    * Returns integer
    *
    * @param itenger $total_items
    */
    public function getBlogTotalItems($categoryId=null)
    {
        $em = $this->container->get('doctrine')->getManager();
        $total_items = $em->getRepository('BlogBundle:Post')->countTotal($categoryId);

        return $total_items;
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'blog_extension';
    }
}


<?php

namespace Bridge\EventSubscriber;

use Bridge\Event\BridgeEvents;
use Bridge\Event\PostActionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Action activity subscriber.
 */
class ActionActivitySubscriber implements EventSubscriberInterface
{
    /**
     * @var array List of action activities
     */
    private $activity;

    /**
     * @var float Total execution time
     */
    private $totalExecutionTime = 0.0;

    /**
     * @var int Total call count
     */
    private $totalCallCount = 0;

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            BridgeEvents::POST_ACTION => 'collectActivity',
        );
    }

    /**
     * Returns collected activity.
     *
     * @return array
     */
    public function getActivity()
    {
        return $this->activity;
    }

    /**
     * Returns total execution time.
     *
     * @return float Total execution time
     */
    public function getTotalExecutionTime()
    {
        return round($this->totalExecutionTime * 1000, 2);
    }

    /**
     * Returns total call count.
     *
     * @return int Total call count
     */
    public function getTotalCallCount()
    {
        return $this->totalCallCount;
    }

    /**
     * Collects activity.
     *
     * @param PostActionEvent $event
     */
    public function collectActivity(PostActionEvent $event)
    {
        $this->activity[] = array(
            'action_name' => $event->getAction()->getName(),
            'group_name' => $event->getAction()->getGroup()->getName(),
            'service_name' => $event->getAction()->getGroup()->getService()->getName(),
            'execution_time' => round($event->getExecutionTime() * 1000, 2),
            'arguments' => $event->getArguments(),
            'extra_data' => $event->getExtraData(),
        );

        $this->totalExecutionTime += $event->getExecutionTime();
        $this->totalCallCount += 1;
    }
}