<?php
namespace Lab123\Odin\Logger;

use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Processor\WebProcessor;
use Monolog\Processor\MemoryUsageProcessor;
use Monolog\Formatter\LineFormatter;

class Logger
{

    /**
     * Instance MonoLogger
     *
     * @var loggers
     */
    protected $logger;

    /**
     * Default log Name (index Mono Log)
     *
     * @var file_name
     */
    protected $log_name = 'custom';

    /**
     * Default file name
     *
     * @var file_name
     */
    protected $file_name = 'custom';

    /**
     * Default format line
     *
     * @var formater
     */
    protected $formater = "[%datetime%] %channel%.%level_name%: %message% %extra% %context%\n";

    /**
     * Constructor Class
     *
     * @return void
     */
    public function __construct()
    {
        $this->logger = new MonoLogger($this->log_name);
    }

    /**
     * Emergency Log
     *
     * @return void
     */
    public function emergency($message, array $context = [])
    {
        if (! $this->canLog()) {
            return;
        }

        $this->config();

        $this->logger->addEmergency($this->formatData($message), $context);
    }

    /**
     * Alert Log
     *
     * @return void
     */
    public function alert($message, array $context = [])
    {
        if (! $this->canLog()) {
            return;
        }

        $this->config();

        $this->logger->addAlert($this->formatData($message), $context);
    }

    /**
     * Critical Log
     *
     * @return void
     */
    public function critical($message, array $context = [])
    {
        if (! $this->canLog()) {
            return;
        }

        $this->config();

        $this->logger->addCritical($this->formatData($message), $context);
    }

    /**
     * Error Log
     *
     * @return void
     */
    public function error($message, array $context = [])
    {
        if (! $this->canLog()) {
            return;
        }

        $this->config();

        $this->logger->addError($this->formatData($message), $context);
    }

    /**
     * Warning Log
     *
     * @return void
     */
    public function warning($message, array $context = [])
    {
        if (! $this->canLog()) {
            return;
        }

        $this->config();

        $this->logger->addWarning($this->formatData($message), $context);
    }

    /**
     * Notice Log
     *
     * @return void
     */
    public function notice($message, array $context = [])
    {
        if (! $this->canLog()) {
            return;
        }

        $this->config();

        $this->logger->addNotice($this->formatData($message), $context);
    }

    /**
     * Info Log
     *
     * @return void
     */
    public function info($message, array $context = [])
    {
        if (! $this->canLog()) {
            return;
        }

        $this->config();

        $this->logger->addInfo($this->formatData($message), $context);
    }

    /**
     * Debug Log
     *
     * @return void
     */
    public function debug($message, array $context = [])
    {
        if (! $this->canLog()) {
            return;
        }

        $this->config();

        $this->logger->addDebug($this->formatData($message), $context);
    }

    /**
     * Validate can log data
     *
     * @return boolean
     */
    protected function canLog()
    {
        return true;
    }

    /**
     * Full Location Log
     *
     * @return string
     */
    public function getFullPath()
    {
        return storage_path() . "/logs/{$this->file_name}.log";
    }

    /**
     * Return Line Formater
     *
     * @return \Monolog\Formatter\LineFormatter
     */
    public function getLineFormater()
    {
        return new LineFormatter($this->formater);
    }

    /**
     * Configuration MonoLogger Instance
     *
     * @return void
     */
    private function config()
    {
        $handler = new RotatingFileHandler($this->getFullPath(), 0, MonoLogger::INFO);

        $handler->setFormatter($this->getLineFormater());

        $this->logger->pushHandler($handler);

        $this->logger->pushProcessor(new WebProcessor());

        $this->logger->pushProcessor(new MemoryUsageProcessor());
    }

    /**
     * Format data to String
     *
     * @return string
     */
    private function formatData($data)
    {
        if (! is_string($data)) {
            $data = json_encode($data);
        }

        return $data;
    }
}


<?php

/*
 * (c) Markus Lanthaler <mail@markus-lanthaler.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ML\GitSynchronizer;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Process\Process;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

/**
 * GitSynchronizer
 *
 * @author Markus Lanthaler <mail@markus-lanthaler.com>
 */
class GitSynchronizer extends Application
{
    /**
     * Constructor
     *
     * Objects and parameters can be passed as argument to the constructor.
     *
     * @param array $values The parameters or objects.
     */
    public function __construct(array $values = array())
    {
        parent::__construct($values);

        $this->get('/', array($this, 'getStatus'));
        $this->post('/{token}', array($this, 'handleSynchronizationRequest'));

        $this->error(array($this, 'errorHandler'));
    }

    /**
     * Returns the current status
     *
     * Currently, it just returns a message saying how many repositories are
     * tracked.
     *
     * @return string The current status
     */
    public function getStatus()
    {
        $message = 'Tracking ';
        $numRepos = 0;

        if (isset($this['repositories']) &&
            (1 === ($numRepos = count($this['repositories'])))) {
            $message .= '1 repository.';
        } else {
            $message .= $numRepos . ' repositories.';
        }

        return $message;
    }

    /**
     * Handles a synchronization request
     *
     * @param Request         $request The request
     * @param string          $token   The token
     *
     * @return Response The response
     */
    public function handleSynchronizationRequest(Request $request, $token = null)
    {
        $data = json_decode($request->get('payload'), false);

        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new Exception(400, 'The JSON data cannot be parsed');
        } elseif (false === isset($data->repository->url)) {
            throw new Exception(400, 'The JSON data does not contain the required information');
        }

        if (false === $this->synchronize($data->repository->url, $token)) {
            throw new Exception(500, 'Internal error', $data->repository->url);
        }

        return new Response('', 204);
    }

    /**
     * Handles a synchronization request
     *
     * @param string $reposity The URL of the repository to synchronize
     *
     * @return boolean Returns true on success, false on failure. Please
     *                 note that post-sync-commands do not affect the return
     *                 value.
     */
    public function synchronize($repository, $token)
    {
        $this->log(LogLevel::INFO, 'Synchronization request for ' . $repository);

        if (false === isset($this['repositories'][$repository])) {
            throw new Exception(400, 'The repository has not been registered', $repository);
        }

        $repo = $this['repositories'][$repository];
        $reqToken = (is_array($repo) && isset($repo['token'])) ? $repo['token'] : $this['token'];
        $directory = (is_array($repo)) ? $repo['path'] : $repo;
        $preSyncCommands = (is_array($repo) && isset($repo['pre-sync-command'])) ? $repo['pre-sync-command'] : array();
        $postSyncCommands = (is_array($repo) && isset($repo['post-sync-command'])) ? $repo['post-sync-command'] : array();

        if (false === is_dir($directory)) {
            throw new Exception(500, 'Configuration error', $repository);
        }

        if ($token !== $reqToken) {
            throw new Exception(401, 'Wrong token, got "' . $token . '"', $repository);
        }

        $this->runCommands($preSyncCommands, $repository);

        $process = new Process("git pull");
        $process->setWorkingDirectory($directory);
        $process->setTimeout(120);
        $process->run();

        $success = false;

        if ($process->isSuccessful()) {
            $this->log(
                LogLevel::NOTICE,
                'Successfully pulled ' . $repository,
                array('output' => $process->getOutput())
            );

            $success = true;
        } else {
            $this->log(
                LogLevel::ERROR,
                'Git pull failed',
                array(
                    'repository' => $repository,
                    'directory' => $directory,
                    'output' => $process->getErrorOutput()
                )
            );
        }

        $this->runCommands($postSyncCommands, $repository);

        return $success;
    }

    /**
     * Runs pre/post-sync commands in the context of the specified repository
     *
     * @param string $reposity The URL of the repository
     */
    protected function runCommands($commands, $repository)
    {
        $repo = $this['repositories'][$repository];
        $directory = (is_array($repo)) ? $repo['path'] : $repo;

        foreach ($commands as $cmd) {
            $process = new Process($cmd);
            $process->setWorkingDirectory($directory);
            $process->setTimeout(180);
            $process->run();

            if ($process->isSuccessful()) {
                $this->log(
                    LogLevel::NOTICE,
                    'Successfully executed pre/post-sync-command',
                    array(
                        'repository' => $repository,
                        'cmd' => $cmd,
                        'output' => $process->getOutput()
                    )
                );
            } else {
                $this->log(
                    LogLevel::ERROR,
                    'Executing pre/post-sync-command failed',
                    array(
                        'repository' => $repository,
                        'cmd' => $cmd,
                        'output' => $process->getErrorOutput()
                    )
                );
            }
        }
    }

    /**
     * Transforms uncaughted exceptions into HTTP responses
     *
     * @param \Exception $exception The URL of the repository to synchronize
     */
    public function errorHandler(\Exception $exception)
    {
        if ($exception instanceof Exception) {
            return new Response($exception->getPublicMessage());
        } else {
            return new Response('Whoops, looks like something went wrong.');
        }
    }

    /**
     * Log a message
     *
     * @param mixed $level
     * @param string $message
     * @param array $context
     *
     * @return null
     */
    public function log($level, $message, array $context = array())
    {
        if (isset($this['monolog'])) {
            $this['monolog']->log($level, $message, $context);
        }
    }
}


<?php

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

namespace Predis\Command;

/**
 * Command factory for the mainline Redis server.
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class RedisFactory extends Factory
{
    /**
     *
     */
    public function __construct()
    {
        $this->commands = array(
            'ECHO' => 'Predis\Command\Redis\ECHO_',
            'EVAL' => 'Predis\Command\Redis\EVAL_',
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getCommandClass($commandID)
    {
        $commandID = strtoupper($commandID);

        if (isset($this->commands[$commandID]) || array_key_exists($commandID, $this->commands)) {
            $commandClass = $this->commands[$commandID];
        } elseif (class_exists($commandClass = "Predis\Command\Redis\\$commandID")) {
            $this->commands[$commandID] = $commandClass;
        } else {
            return;
        }

        return $commandClass;
    }
}


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

use Assetic\Filter\CssRewriteFilter;
use Doctrine\Common\Annotations\AnnotationRegistry;
use JMS\Serializer\SerializerBuilder;
use Monolog\Logger;
use RedKiteCms\Action\FactoryAction;
use RedKiteCms\Bridge\Assetic\AsseticFactoryBuilder;
use RedKiteCms\Bridge\Dispatcher\Dispatcher;
use RedKiteCms\Bridge\ElFinder\ElFinderFilesConnector;
use RedKiteCms\Bridge\ElFinder\ElFinderMediaConnector;
use RedKiteCms\Bridge\Form\FormFactory;
use RedKiteCms\Bridge\Monolog\DataLogger;
use RedKiteCms\Bridge\Routing\RoutingGenerator;
use RedKiteCms\Bridge\Security\UserProvider;
use RedKiteCms\Bridge\Translation\Loader\TranslationLoader;
use RedKiteCms\Bridge\Translation\Translator;
use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Configuration\SiteBuilder;
use RedKiteCms\Content\Block\BlockFactory;
use RedKiteCms\Content\BlockManager\BlockManager;
use RedKiteCms\Content\BlockManager\BlockManagerApprover;
use RedKiteCms\Content\BlockManager\BlockManagerFactory;
use RedKiteCms\Content\Deploy\Deployer;
use RedKiteCms\Content\PageCollection\PageCollectionManager;
use RedKiteCms\Content\PageCollection\PagesCollectionParser;
use RedKiteCms\Content\PageCollection\PermalinkManager;
use RedKiteCms\Content\Page\PageManager;
use RedKiteCms\Content\SitemapGenerator\SitemapGenerator;
use RedKiteCms\Content\SlotsManager\SlotsManagerFactory;
use RedKiteCms\Content\Theme\ThemeSlotsGenerator;
use RedKiteCms\Content\Theme\Theme;
use RedKiteCms\Content\Theme\ThemeAligner;
use RedKiteCms\Content\Theme\ThemeDeployer;
use RedKiteCms\Content\Theme\ThemeGenerator;
use RedKiteCms\EventSystem\CmsEvents;
use RedKiteCms\EventSystem\Event\Cms\CmsBootedEvent;
use RedKiteCms\EventSystem\Event\Cms\CmsBootingEvent;
use RedKiteCms\EventSystem\Listener\Block\BlockEditingListener;
use RedKiteCms\EventSystem\Listener\Cms\CmsBootingListener;
use RedKiteCms\EventSystem\Listener\Exception\ExceptionListener;
use RedKiteCms\EventSystem\Listener\PageCollection\PageRemovedListener;
use RedKiteCms\EventSystem\Listener\PageCollection\PageSavedListener;
use RedKiteCms\EventSystem\Listener\PageCollection\TemplateChangedListener;
use RedKiteCms\EventSystem\Listener\Page\PermalinkChangedListener;
use RedKiteCms\EventSystem\Listener\Request\QueueListener;
use RedKiteCms\EventSystem\Listener\Request\ThemeAlignerListener;
use RedKiteCms\FilesystemEntity\Page;
use RedKiteCms\FilesystemEntity\SlotParser;
use RedKiteCms\Flint\ChainMatcher;
use RedKiteCms\Flint\ChainUrlGenerator;
use RedKiteCms\Plugin\PluginManager;
use RedKiteCms\Rendering\PageRenderer\PageRendererBackend;
use RedKiteCms\Rendering\PageRenderer\PageRendererProduction;
use RedKiteCms\Rendering\Queue\QueueManager;
use RedKiteCms\Rendering\TemplateAssetsManager\TemplateAssetsManager;
use RedKiteCms\Rendering\Toolbar\ToolbarManager;
use Silex\Application;
use Silex\Provider\FormServiceProvider;
use Silex\Provider\MonologServiceProvider;
use Silex\Provider\SecurityServiceProvider;
use Silex\Provider\SessionServiceProvider;
use Silex\Provider\TranslationServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Silex\Provider\UrlGeneratorServiceProvider;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\OptionsResolver\OptionsResolver;
use RedKiteCms\Bridge\Routing\Routing;

/**
 * Class RedKiteCms is the object assigned to bootstrap the CMS. This object is the application entry point and it is
 * used in front-controllers.
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms
 */
abstract class RedKiteCms
{
    private $app;
    private $siteName;
    private $frameworkAbsoluteDir;

    /**
     * Returns an array of options to change RedKite CMS configuration
     * @return array
     */
    abstract protected function configure();

    /**
     * Registers additional services
     *
     * @param Application $app
     */
    abstract protected function register(Application $app);

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

    /**
     * Bootstraps the application
     *
     * @param string $rootDir
     * @param string $siteName
     */
    public function bootstrap($rootDir, $siteName)
    {
        $this->app["red_kite_cms.root_dir"] = $rootDir;
        $this->siteName = $siteName;

        $this->checkPermissions($rootDir);
        $this->initCmsRequiredServices();
        $this->registerProviders();
        $this->registerServices();
        $this->registerListeners();
        $this->register($this->app);
        $this->boot();
        $this->addWebsiteRoutes();

        $this->app["dispatcher"]->dispatch(
            CmsEvents::CMS_BOOTED,
            new CmsBootedEvent($this->app["red_kite_cms.configuration_handler"])
        );
    }

    private function initCmsRequiredServices()
    {
        $configurationOptions = $this->configure();
        $this->app["red_kite_cms.configuration_handler"] = new ConfigurationHandler(
            $this->app["red_kite_cms.root_dir"],
            $this->siteName
        );
        $this->app["red_kite_cms.configuration_handler"]->setConfigurationOptions($configurationOptions);
        $siteNameDir = $this->app["red_kite_cms.root_dir"] . '/app/data/' . $this->siteName;
        if (!is_dir($siteNameDir)) {
            $siteBuilder = new SiteBuilder($this->app["red_kite_cms.root_dir"], $this->siteName);
            $siteBuilder->build();
        }

        $this->app["red_kite_cms.configuration_handler"]->boot();
        $this->frameworkAbsoluteDir = $this->app["red_kite_cms.configuration_handler"]->frameworkAbsoluteDir();
    }

    private function registerTwig()
    {
        $this->app->register(
            new TwigServiceProvider(),
            array(
                'twig.path' => array(
                    $this->app["red_kite_cms.root_dir"] . '/' . $this->frameworkAbsoluteDir . '/plugins/RedKiteCms/Core',
                    $this->app["red_kite_cms.root_dir"] . '/' . $this->frameworkAbsoluteDir . '/plugins/RedKiteCms/Block',
                    $this->app["red_kite_cms.root_dir"] . '/' . $this->frameworkAbsoluteDir . '/plugins/RedKiteCms/Theme',
                    $this->app["red_kite_cms.root_dir"] . '/vendor/redkite-labs/redkitecms-plugins/RedKiteCms/Block',
                    $this->app["red_kite_cms.root_dir"] . '/vendor/redkite-labs/redkitecms-plugins/RedKiteCms/Theme',
                    $this->app["red_kite_cms.root_dir"] . '/app/plugins/RedKiteCms/Block',
                    $this->app["red_kite_cms.root_dir"] . '/app/plugins/RedKiteCms/Theme',
                    $this->app["red_kite_cms.root_dir"] . '/src',
                ),
                'twig.options' => array(
                    'cache' => $this->app["red_kite_cms.configuration_handler"]->siteCacheDir() . '/twig',
                ),
            )
        );

        $this->app['twig'] = $this->app->share(
            $this->app->extend(
                'twig',
                function ($twig, $app) {
                    $twig->addGlobal('cms_language', 'en');

                    return $twig;
                }
            )
        );
    }

    private function registerProviders()
    {
        AnnotationRegistry::registerAutoloadNamespace(
            'JMS\Serializer\Annotation',
            $this->app["red_kite_cms.root_dir"] . '/vendor/jms/serializer/src'
        );

        $app = $this->app;
        $this->app['security.firewalls'] = array(
            'backend' => array(
                'pattern' => '^/backend',
                'form' => array(
                    'login_path' => '/login',
                    'check_path' => '/backend/login_check',
                ),
                'logout' => array(
                    'logout_path' => '/backend/logout',
                    'target_url' => '/login',
                ),
                'users' => $this->app->share(
                    function () use ($app) {
                        return new UserProvider($app["red_kite_cms.configuration_handler"]);
                    }
                ),
            ),
        );

        // TODO setup roles dinamically
        $app['security.access_rules'] = array(
            array('^.*$', 'ROLE_USER'),
        );

        $this->app->register(new UrlGeneratorServiceProvider());
        $this->app->register(new SecurityServiceProvider());
        $this->app->register(new SessionServiceProvider());

        $this->app->boot();

        $this->app->register(
            new TranslationServiceProvider(),
            array(
                'locale_fallbacks' => array('en'),
            )
        );
        $this->app->register(new FormServiceProvider());

        $this->registerTwig();

        $frameworkAbsoluteDir = $this->frameworkAbsoluteDir;
        $this->app['translator'] = $this->app->share(
            $this->app->extend(
                'translator',
                function ($translator, $app) use($frameworkAbsoluteDir) {
                    $resources = array(
                        $app["red_kite_cms.root_dir"] . '/' . $frameworkAbsoluteDir . '/plugins/RedKiteCms/Core/RedKiteCms/Resources/translations',
                        $app["red_kite_cms.root_dir"] . '/' . $frameworkAbsoluteDir . '/plugins/RedKiteCms/Block/*/Resources/translations',
                    );

                    // This is a workaround required because Symfony2 Finder throws an exception when a folder does not exist, so the
                    // path for custom bundles cannot be added arbitrarily.
                    // This code looks for at least once "translations" folder for custom plugins and when it finds one, it adds the
                    // path to find translations for custom plugins
                    foreach ($app["red_kite_cms.plugin_manager"]->getBlockPlugins() as $plugin) {
                        if ($plugin->isCore()) {
                            continue;
                        }

                        if ($plugin->isTranslated()) {
                            $resources[] = $app["red_kite_cms.root_dir"] . '/app/plugins/RedKiteCms/Block/*/Resources/translations';

                            break;
                        }
                    }

                    $translationLoader = new TranslationLoader();
                    $translationLoader->registerResources($translator, $resources);
                    $translator->addLoader('xliff', $translationLoader);

                    return $translator;
                }
            )
        );

        $logFileName = $this->siteName;
        if ($this->app["debug"]){
            $logFileName .= '_dev';
        }
        $logPath = sprintf('%s/%s.log', $this->app["red_kite_cms.configuration_handler"]->logDir(), $logFileName);
        $level = $this->app["debug"] ? Logger::DEBUG : Logger::CRITICAL;
        $app->register(
            new MonologServiceProvider(),
            array(
                'monolog.name' => 'RedKiteCms',
                'monolog.logfile' => $logPath,
                'monolog.level' => $level,
            )
        );

        $app['router'] = Routing::create($this->app["red_kite_cms.configuration_handler"], $this->app["debug"])->getRouter();

        $generator = new ChainUrlGenerator(array($this->app['url_generator'], $this->app['router']));
        $generator->setContext($this->app['request_context']);
        $this->app['url_generator'] = $generator;
    }

    private function registerServices()
    {
        $optionsResolver = new OptionsResolver();

        $this->app["jms.serializer"] = SerializerBuilder::create()->build();
        $this->app["red_kite_cms.plugin_manager"] = new PluginManager($this->app["red_kite_cms.configuration_handler"]);
        $this->app["red_kite_cms.slot_parser"] = new SlotParser($this->app["jms.serializer"]);
        $this->app["red_kite_cms.page"] = new Page(
            $this->app["jms.serializer"],
            clone $optionsResolver,
            $this->app["red_kite_cms.slot_parser"]
        );

        $this->app["red_kite_cms.blocks_manager_factory"] = new BlockManagerFactory(
            $this->app["jms.serializer"],
            clone $optionsResolver
        );
        $this->app["red_kite_cms.pages_collection_parser"] = new PagesCollectionParser($this->app["red_kite_cms.configuration_handler"]);
        $this->app["red_kite_cms.form_factory"] = new FormFactory(
            $this->app["red_kite_cms.configuration_handler"],
            $this->app["form.factory"],
            $this->app["red_kite_cms.pages_collection_parser"]
        );
        $this->app["red_kite_cms.assetic"] = new AsseticFactoryBuilder(
            $this->app["red_kite_cms.configuration_handler"]
        );
        $this->app["red_kite_cms.template_assets"] = new TemplateAssetsManager(
            $this->app["red_kite_cms.configuration_handler"], $this->app["red_kite_cms.assetic"]
        );
        $this->app["red_kite_cms.page_renderer_backend"] = new PageRendererBackend(
            $this->app["twig"],
            $this->app["red_kite_cms.pages_collection_parser"]
        );
        $this->app["red_kite_cms.page_renderer_production"] = new PageRendererProduction(
            $this->app["red_kite_cms.configuration_handler"], $this->app["jms.serializer"], $this->app["twig"]
        );
        $this->app["red_kite_cms.slots_manager_factory"] = new SlotsManagerFactory(
            $this->app["red_kite_cms.configuration_handler"]
        );
        $this->app["red_kite_cms.page_collection_manager"] = new PageCollectionManager(
            $this->app["red_kite_cms.configuration_handler"],
            $this->app["red_kite_cms.slots_manager_factory"]
        );
        $this->app["red_kite_cms.page_manager"] = new PageManager(
            $this->app["red_kite_cms.configuration_handler"]
        );
        $this->app["red_kite_cms.deployer"] = new Deployer(
            $this->app["red_kite_cms.configuration_handler"]
        );
        $this->app["red_kite_cms.elfinder_media_connector"] = new ElFinderMediaConnector(
            $this->app["red_kite_cms.configuration_handler"]
        );
        $this->app["red_kite_cms.elfinder_files_connector"] = new ElFinderFilesConnector(
            $this->app["red_kite_cms.configuration_handler"]
        );
        $this->app["red_kite_cms.permalink_manager"] = new PermalinkManager(
            $this->app["red_kite_cms.configuration_handler"]
        );
        $this->app["red_kite_cms.theme"] = new Theme(
            $this->app["red_kite_cms.configuration_handler"],
            $this->app["red_kite_cms.slots_manager_factory"]
        );
        $this->app["red_kite_cms.toolbar_manager"] = new ToolbarManager(
            $this->app["red_kite_cms.plugin_manager"],
            $this->app["twig"]
        );
        $this->app["red_kite_cms.theme_generator"] = new ThemeGenerator($this->app["red_kite_cms.configuration_handler"]);
        $this->app["red_kite_cms.slots_generator"] = new ThemeSlotsGenerator($this->app["red_kite_cms.configuration_handler"], $this->app["red_kite_cms.slots_manager_factory"]);
        $this->app["red_kite_cms.theme_aligner"] = new ThemeAligner($this->app["red_kite_cms.configuration_handler"]);
        $this->app["red_kite_cms.theme_deployer"] = new ThemeDeployer($this->app["red_kite_cms.configuration_handler"]);
        $this->app["red_kite_cms.factory_action"] = new FactoryAction($this->app);
        $this->app["red_kite_cms.queue_manager"] = new QueueManager($this->app["red_kite_cms.configuration_handler"], $this->app["red_kite_cms.factory_action"], $this->app["twig"]);

        $this->app["red_kite_cms.sitemap_generator"] = new SitemapGenerator($this->app["red_kite_cms.configuration_handler"],$this->app["red_kite_cms.pages_collection_parser"],$this->app["twig"]);
    }

    private function checkPermissions($rootDir)
    {
        $permissions = array();
        if (!is_writable($rootDir . '/app')) {
            $permissions[] = $rootDir . '/app';
        }
        if (!is_writable($rootDir . '/app/data')) {
            $permissions[] = $rootDir . '/app/data';
        }
        $webDir = str_replace('/..', '', $rootDir);
        if (!is_writable($webDir)) {
            $permissions[] = $webDir;
        }

        if (!empty($permissions)) {
            $this->registerTwig();
            echo $this->app["twig"]->render('RedKiteCms/Resources/views/Permissions/permissions.html.twig', array("permissions" => $permissions));
            exit;
        }
    }

    private function registerListeners()
    {
        $this->app["red_kite_cms.listener.exception"] = new ExceptionListener(
            $this->app["twig"],
            $this->app["translator"],
            $this->app["debug"]
        );
        $this->app["dispatcher"]->addListener(
            'kernel.exception',
            array($this->app["red_kite_cms.listener.exception"], 'onKernelException')
        );

        $this->app["dispatcher"]->addListener(
            'kernel.request',
            array(new QueueListener($this->app["red_kite_cms.queue_manager"], $this->app["security"]), 'onKernelRequest')
        );

        $this->app["dispatcher"]->addListener(
            'kernel.request',
            array(new ThemeAlignerListener($this->app["red_kite_cms.configuration_handler"], $this->app["red_kite_cms.pages_collection_parser"], $this->app["security"], $this->app["red_kite_cms.theme_generator"], $this->app["red_kite_cms.slots_generator"], $this->app["red_kite_cms.theme_aligner"], clone($this->app["red_kite_cms.page"])), 'onKernelRequest')
        );

        $this->app["red_kite_cms.listener.cms_booting"] = new CmsBootingListener(
            $this->app["red_kite_cms.plugin_manager"]
        );
        $this->app["dispatcher"]->addListener(
            'cms.booting',
            array($this->app["red_kite_cms.listener.cms_booting"], 'onCmsBooting')
        );
        $this->app["red_kite_cms.listener.block_edited"] = new BlockEditingListener(
            $this->app["red_kite_cms.page_renderer_production"], $this->app["red_kite_cms.permalink_manager"]
        );
        $this->app["dispatcher"]->addListener(
            'block.editing',
            array($this->app["red_kite_cms.listener.block_edited"], 'onBlockEditing')
        );
        $this->app["red_kite_cms.listener.permalink_changed"] = new PermalinkChangedListener(
            $this->app["red_kite_cms.configuration_handler"], $this->app["red_kite_cms.permalink_manager"]
        );
        $this->app["dispatcher"]->addListener(
            'page.permalink_changed',
            array($this->app["red_kite_cms.listener.permalink_changed"], 'onPermalinkChanged')
        );
        $this->app["red_kite_cms.listener.page_removed"] = new PageRemovedListener(
            $this->app["red_kite_cms.pages_collection_parser"], $this->app["red_kite_cms.permalink_manager"]
        );
        $this->app["dispatcher"]->addListener(
            'page.collection.removed',
            array($this->app["red_kite_cms.listener.page_removed"], 'onPageRemoved')
        );
        $this->app["red_kite_cms.listener.template_changed"] = new TemplateChangedListener(
            $this->app["red_kite_cms.theme"], $this->app["red_kite_cms.configuration_handler"]
        );
        $this->app["dispatcher"]->addListener(
            'page.collection.template_changed',
            array($this->app["red_kite_cms.listener.template_changed"], 'onTemplateChanged')
        );
        $this->app["red_kite_cms.listener.page_saved"] = new PageSavedListener(
            $this->app["red_kite_cms.configuration_handler"], $this->app["red_kite_cms.page_renderer_production"]
        );
        $this->app["dispatcher"]->addListener(
            'page.saved',
            array($this->app["red_kite_cms.listener.page_saved"], 'onPageSaved')
        );
    }

    private function boot()
    {

        BlockFactory::boot($this->app["red_kite_cms.configuration_handler"]);
        Dispatcher::setDispatcher($this->app["dispatcher"]);
        DataLogger::init($this->app["monolog"]);
        Translator::setTranslator($this->app["translator"]);

        $this->app["red_kite_cms.plugin_manager"]->boot();
        $theme = $this->app["red_kite_cms.plugin_manager"]->getActiveTheme();
        $this->app["red_kite_cms.theme"]->boot($theme);

        $this->app["red_kite_cms.theme_generator"]->boot($theme);
        $this->app["red_kite_cms.slots_generator"]->boot($theme);
        $this->app["red_kite_cms.theme_aligner"]->boot($theme);

        $siteIncompleteFile = $this->app["red_kite_cms.root_dir"] . '/app/data/' . $this->siteName . '/incomplete.json';
        if (file_exists($siteIncompleteFile)) {
            $this->createWebsitePages($theme);
            unlink($siteIncompleteFile);
        }

        $this->app["dispatcher"]->dispatch(
            CmsEvents::CMS_BOOTING,
            new CmsBootingEvent($this->app["red_kite_cms.configuration_handler"])
        );

        $this->app["red_kite_cms.template_assets"]->boot();
        $this->app["red_kite_cms.assetic"]->addFilter('cssrewrite', new CssRewriteFilter());
    }

    private function addWebsiteRoutes()
    {
        // FIXME This information comes from security and it is not available at this level
        $user = null;
        if (!$this->app["red_kite_cms.configuration_handler"]->isTheme()) {
            $user = 'admin';
        }
        $routingGenerator = new RoutingGenerator($this->app["red_kite_cms.configuration_handler"]);
        Routing::create($this->app["red_kite_cms.configuration_handler"])->generateWebsiteRoutes($routingGenerator, $user);
        $this->app["red_kite_cms.website_routes"] = $routingGenerator->getRoutes();

        $matcher = new ChainMatcher(array($this->app['url_matcher'], $this->app['router']->getMatcher()));
        $matcher->setContext($this->app['request_context']);
        $this->app['url_matcher'] = $matcher;
    }

    private function createWebsitePages($theme)
    {
        $isTheme = $this->app["red_kite_cms.configuration_handler"]->isTheme();
        $user = null;
        if (!$isTheme) {
            $user = 'admin';
        }

        $language = "en_GB";
        $pages = $theme->getPages();
        if (null == $pages) {
            $this->registerTwig();
            echo $this->app["twig"]->render('RedKiteCms/Resources/views/Bootstrap/bootstrap.html.twig', array("theme_name" => $theme->getName(), "site_path" => $this->app["red_kite_cms.configuration_handler"]->siteDir()));
            exit;
        }
        $this->app["red_kite_cms.page_collection_manager"]->contributor($user);

        $theme = $this->app["red_kite_cms.theme"];
        $this->app["red_kite_cms.slots_generator"]->generate();
        foreach($pages as $pageName => $templateName) {
            $page = array(
                "name" => $pageName,
                "template" => $templateName,
                "seo" => array(
                    array(
                        "permalink" => str_replace('_', '-', strtolower($language)) . "-" . $pageName,
                        "changed_permalinks" => array(),
                        "title" => $pageName . '-title',
                        "description" => $pageName . '-description',
                        "keywords" => $pageName . '-keywords',
                        "sitemap_frequency" => 'monthly',
                        "sitemap_priority" => '0.5',
                        "language" => $language,
                    ),)
            );
            $this->app["red_kite_cms.page_collection_manager"]
                ->add($theme, $page)
            ;

            $page = new Page($this->app["jms.serializer"],
                new OptionsResolver(),
                $this->app["red_kite_cms.slot_parser"]
            );
            $pageOptions = array(
                'page' => $pageName,
                'language' => 'en',
                'country' => 'GB',
            );
            $page->render($this->app["red_kite_cms.configuration_handler"]->siteDir(), $pageOptions, $user);
            $this->savePermalinks($page->getPageSlots());
            $this->savePermalinks($page->getCommonSlots());
            $this->app["red_kite_cms.permalink_manager"]->save();
        }

        if (!$isTheme) {
            $blockManager = new BlockManagerApprover(
                $this->app["jms.serializer"],
                new OptionsResolver()
            );
            $this->app["red_kite_cms.deployer"]
                ->contributor('admin')
                ->saveAllPages($blockManager, array('en_GB'))
            ;
        }

        $fileSystem = new Filesystem();
        $fileSystem->remove($this->app["red_kite_cms.configuration_handler"]->siteCacheDir());
    }

    private function savePermalinks($slots)
    {
        foreach($slots as $slot) {
            foreach($slot->getEntitiesInUse() as $block) {
                $slotDir = $slot->getDirInUse();
                $decodedBlock = json_decode($block, true);
                $blockFile = $slotDir . '/blocks/' . $decodedBlock["name"] . '.json';
                $htmlBlock = $this->app["red_kite_cms.page_renderer_production"]->renderBlock($block);
                $this->app["red_kite_cms.permalink_manager"]->add($blockFile, $htmlBlock);
            }
        }
    }
}


<?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\EventSystem\Event;

use RedKiteCms\Bridge\Monolog\DataLogger;

/**
 * Class JsonFileEvent is the object assigned to handle the base properties for an event which involves a json file management
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\EventSystem\Event
 */
abstract class JsonFileEvent extends Event
{
    /**
     * @type null|string
     */
    protected $fileContent;
    /**
     * @type null|string
     */
    protected $filePath;

    /**
     * Constructor
     *
     * @param null $filePath
     * @param null $fileContent
     */
    public function __construct($filePath = null, $fileContent = null)
    {
        $this->filePath = $filePath;
        $this->fileContent = $fileContent;
    }

    /**
     * Returns the json file path
     *
     * @return null|string
     */
    public function getFilePath()
    {
        return $this->filePath;
    }

    /**
     * Sets the json file path
     * @param $filePath
     *
     * @return $this
     */
    public function setFilePath($filePath)
    {
        $this->filePath = $filePath;

        return $this;
    }

    /**
     * Returns the json file contents
     *
     * @return null|string
     */
    public function getFileContent()
    {
        return $this->fileContent;
    }

    /**
     * Sets the json file contents
     * @param $fileContent
     *
     * @return $this
     */
    public function setFileContent($fileContent)
    {
        // Accapts only a json value
        if (null === json_decode($fileContent)) {
            DataLogger::log(
                sprintf(
                    'Event "%s" discharged the "%s" content because it is not a valid json',
                    get_class($this),
                    $fileContent
                ),
                DataLogger::WARNING
            );

            return $this;
        }

        $this->fileContent = $fileContent;

        return $this;
    }
}


<?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\OptionsInterface;
use Predis\Connection\Replication\MasterSlaveReplication;
use Predis\Connection\Replication\SentinelReplication;

/**
 * Configures an aggregate connection used for master/slave replication among
 * multiple Redis nodes.
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class Replication extends Aggregate
{
    /**
     * Returns a connection initializer from a descriptive name.
     *
     * @param OptionsInterface $options     Client options.
     * @param string           $description Identifier of a replication backend (`predis`, `sentinel`)
     *
     * @return callable
     */
    protected function getConnectionInitializerByDescription(OptionsInterface $options, $description)
    {
        if ($description === 'predis') {
            $callback = $this->getDefault($options);
        } elseif ($description === 'sentinel') {
            $callback = function ($options, $sentinels) {
                return new SentinelReplication($options->service, $sentinels, $options->connections);
            };
        } else {
            throw new \InvalidArgumentException(
                'String value for the replication option must be either `predis` or `sentinel`'
            );
        }

        return $this->getConnectionInitializer($options, $callback);
    }

    /**
     * {@inheritdoc}
     */
    public function filter(OptionsInterface $options, $value)
    {
        if (is_string($value)) {
            return $this->getConnectionInitializerByDescription($options, $value);
        } else {
            return $this->getConnectionInitializer($options, $value);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDefault(OptionsInterface $options)
    {
        return function ($options) {
            $connection = new MasterSlaveReplication();

            if ($options->autodiscovery) {
                $connection->setConnectionFactory($options->connections);
                $connection->setAutoDiscovery(true);
            }

            return $connection;
        };
    }
}


<?php

/*
 * Copyright (c) 2013, Flaming Code
 *
 */

namespace FlamingBase\View\Helper;

use DOMDocument;
use DOMXPath;
use Zend\View\Helper\AbstractHelper;

/**
 * BootstrapifyMenu
 *
 * @author Flemming Andersen <flemming@flamingcode.com>
 * @copyright (c) 2013, Flaming Code
 * @link https://github.com/FlamingCode/FlamingBase for the canonical source repository
 * @license http://opensource.org/licenses/MIT MIT
 */
class BootstrapifyMenu extends AbstractHelper
{
	/**
	 *
	 * @param string|null $html
	 * @return BootstrapifyMenu|string
	 */
	public function __invoke($html = null)
	{
		if (null === $html)
			return $this;

		if (empty($html))
			return '';

		return $this->applyBootstrapClassesAndIds($html);
	}

	/**
	 * Applies the custom Twitter Bootstrap dropdown class/id attributes where
	 * necessary.
	 *
	 * @param  string $html The HTML
	 * @return string
	 */
	protected function applyBootstrapClassesAndIds($html)
	{
		$domDoc = new DOMDocument('1.0', 'utf-8');
		$domDoc->loadXML('<?xml version="1.0" encoding="utf-8"?>' . $html);

		$xpath = new DOMXPath($domDoc);

		foreach ($xpath->query('//a[starts-with(@href, "#")]') as $item) {
			$result = $xpath->query('../ul', $item);

			if ($result->length === 1) {
				$ul = $result->item(0);
				$ul->setAttribute('class', 'dropdown-menu');

				$li = $item->parentNode;
				$li->setAttribute('id', substr($item->getAttribute('href'), 1));

				if (($existingClass = $li->getAttribute('class')) !== '')
					$li->setAttribute('class', $existingClass . ' dropdown');
				else
					$li->setAttribute('class', 'dropdown');

				$item->setAttribute('data-toggle', 'dropdown');

				if (($existingClass = $item->getAttribute('class')) !== '')
					$item->setAttribute('class', $item->getAttribute('class') . ' dropdown-toggle');
				else
					$item->setAttribute('class', 'dropdown-toggle');

				$space = $domDoc->createTextNode(' ');

				$item->appendChild($space);

				$caret = $domDoc->createElement('b', ' ');
				$caret->setAttribute('class', 'caret');

				$item->appendChild($caret);
			}
		}

		return $domDoc->saveXML($xpath->query('/ul')->item(0));
	}
}


<?php
namespace Ecompassaro\Pagamento;

use Ecompassaro\Autenticacao\Autenticacao;
use \DateTime;

class Pagamento
{
    private $id;

    private $autenticacaoId;

    private $autenticacao;

    private $valor;

    private $data;

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

    /**
     *
     * @param int $id
     * @return Pagamento
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    /**
     *
     * @return int
     */
    public function getAutenticacaoId()
    {
        return (int) $this->autenticacaoId;
    }

    /**
     *
     * @return Autenticacao
     */
    public function getAutenticacao()
    {
        return $this->autenticacao;
    }

    /**
     *
     * @param int $autenticacaoId
     * @return Pagamento
     */
    public function setAutenticacaoId($autenticacaoId)
    {
        $this->autenticacaoId = $autenticacaoId;
        return $this;
    }

    /**
     *
     * @param Autenticacao $autenticacao
     * @return Pagamento
     */
    public function setAutenticacao(Autenticacao $autenticacao)
    {
        $this->autenticacao = $autenticacao;
        return $this;
    }

    /**
     *
     * @return \DateTime
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     *
     * @param \DateTime|string $data se string deve vir no formato Y-m-d H:i:s
     * @return Pagamento
     */
    public function setData($data)
    {
        if(!($data instanceof DateTime)) {
            $data = explode('.', $data)[0];
            $data = DateTime::createFromFormat('Y-m-d H:i:s', $data);
        }
        $this->data = $data;
        return $this;
    }

    /**
     * @return double
     */
    public function getValor()
    {
        return (double) $this->valor;
    }

    /**
     * @param double $valor
     * @return Pagamento
     */
    public function setValor($valor)
    {
        $this->valor = $valor;
        return $this;
    }

    /**
     * Obtem a estrutura da entity Pagamento em formato array
     *
     * @return array
     */
    public function toArray()
    {
        return array(
            'autenticacao_id' => $this->autenticacaoId,
            'valor' => $this->valor
        );
    }

    /**
     * Preenche a entidade a partir de um array
     * @return Pagamento
     */
    public function exchangeArray($array)
    {
        return $this->setId(isset($array['id'])?$array['id']:null)
            ->setAutenticacaoId($array['autenticacao_id'])
            ->setValor($array['valor'])
            ->setData(isset($array['data'])?$array['data']:null);
    }
}


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

use RedKiteCms\Content\Theme\ThemeDeployer;
use RedKiteCms\Rendering\Controller\BaseController;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class SaveThemeController is the object assigned to save a theme
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Rendering\Controller\Theme
 */
abstract class SaveThemeController extends BaseController
{
    /**
     * Implements the action to save the theme
     * @param array $options
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function save(array $options)
    {
        $resolver = new OptionsResolver();
        $this->configureOptions($resolver);
        $this->options = $resolver->resolve($options);

        $pluginManager = $options["plugin_manager"];
        $options["theme_deployer"]
            ->boot($pluginManager->getActiveTheme())
            ->deploy()
        ;

        return $this->buildJSonResponse(array());
    }

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

        $resolver->setAllowedTypes(
            array(
                'configuration_handler' => '\RedKiteCms\Configuration\ConfigurationHandler',
                'plugin_manager' => '\RedKiteCms\Plugin\PluginManager',
                'theme_deployer' => '\RedKiteCms\Content\Theme\ThemeDeployer',
                'page' => '\RedKiteCms\FilesystemEntity\Page',
            )
        );
    }
}


<?php
namespace DasRed\Translation\Command\Executor\Log;

class ToCsv extends Parse
{

	/**
	 * (non-PHPdoc)
	 * @see \DasRed\Translation\Command\Executor\Log\Parse::execute()
	 */
	public function execute()
	{
		$file = $this->getArguments()[1];
		if (file_exists($file) === true)
		{
			unlink($file);
		}

		$this->write('File', 'LineNumber', 'Key', 'Locale', 'Count of Matches');

		return parent::execute();
	}

	/**
	 * @return int
	 */
	protected function getMaxCountOfArguments()
	{
		return 2;
	}

	/**
	 *
	 * @param string $file
	 * @param int $lineNumber
	 * @param string $key
	 * @param string $locale
	 * @param int $count
	 * @return self
	 */
	protected function write($file, $lineNumber, $key, $locale, $count)
	{
		$fHandle = fopen($this->getArguments()[1], 'a');
		fputcsv($fHandle, [
			$file,
			$lineNumber,
			$key,
			$locale,
			$count
		], ';', '"');
		fclose($fHandle);

		return $this;
	}
}


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

namespace CmsUser\Initializer;

use Zend\ServiceManager\AbstractPluginManager,
    Zend\ServiceManager\InitializerInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    CmsUser\Options\UserServiceOptionsInterface,
    CmsUser\Options\ModuleOptions,
    CmsUser\Service\UserServiceAwareInterface;

class UserServiceInitializer implements InitializerInterface
{
    /**
     * {@inheritDoc}
     */
    public function initialize($instance, ServiceLocatorInterface $services)
    {
        if ($instance instanceof UserServiceAwareInterface) {
            if ($services instanceof AbstractPluginManager) {
                $services = $services->getServiceLocator();
            }

            /* @var $options UserServiceOptionsInterface */
            $options = $services->get(ModuleOptions::class);
            $instance->setUserService($services->get('DomainServiceManager')->get($options->getUserEntityClass()));
        }
    }
}


<?php

namespace AdminBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('admin');

        $rootNode
            ->children()
                ->arrayNode('admin_menus')
                    ->isRequired()
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->ignoreExtraKeys()
                        ->children()
                            ->scalarNode('icon_class')->defaultNull()->end()
                            ->scalarNode('label')->defaultNull()->end()
                            //fix expected always array
                            ->variableNode('options')
                                ->validate()
                                ->always(function ($v) {
                                    if (is_string($v) || is_array($v)) {
                                        return $v;
                                    }
                                    throw new InvalidTypeException();
                                })
                            ->end()->end()

//                            ->arrayNode('options')
//                                ->useAttributeAsKey('name')
//                                ->prototype('array')
//                                    ->ignoreExtraKeys()
//                                    ->children()
//                                        ->scalarNode('icon_class')->defaultNull()->end()
//                                        ->scalarNode('label')->defaultNull()->end()
//                                        ->arrayNode('options')
//                                            ->useAttributeAsKey('name')
//                                            ->prototype('scalar')->end()
//                                        ->end()
//                                    ->end()
//                                ->end()
//                            ->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('company_menus')
                    ->isRequired()
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->ignoreExtraKeys()
                        ->children()
                            ->scalarNode('icon_class')->defaultNull()->end()
                            ->scalarNode('label')->defaultNull()->end()
                            //fix expected always array
                            ->variableNode('options')
                                ->validate()
                                ->always(function ($v) {
                                    if (is_string($v) || is_array($v)) {
                                        return $v;
                                    }
                                    throw new InvalidTypeException();
                                })
                            ->end()->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('apis')
                    ->isRequired()
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->ignoreExtraKeys()
                        ->children()
                            ->arrayNode('options')
                            ->useAttributeAsKey('name')
                            ->prototype('scalar')->end()
                        ->end()
                    ->end()
                ->end()
            ->end();
        return $treeBuilder;
    }
}


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

namespace CmsUser\Factory\Authentication;

use Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    CmsUser\Authentication\Adapter\DefaultAdapter,
    CmsUser\Options\AuthenticationOptionsInterface,
    CmsUser\Options\ModuleOptions;

class AdapterFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return DefaultAdapter
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /* @var $options AuthenticationOptionsInterface */
        $options = $serviceLocator->get(ModuleOptions::class);

        return new DefaultAdapter(
            $serviceLocator->get('MapperManager')->get($options->getUserEntityClass()),
            $options
        );
    }
}


<?php namespace Origami\Notice;

use Illuminate\Support\ServiceProvider;

class NoticeServiceProvider extends ServiceProvider {

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

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
    {
		$this->loadViewsFrom(__DIR__.'/views', 'notice');

		$this->publishes([
	        __DIR__.'/views' => base_path('resources/views/vendor/notice'),
	    ]);
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
        $this->app->singleton('notice', function()
        {
        	$session = $this->app->make('Illuminate\Session\Store');

            return new Notice($session, 'flash_notice');
        });
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array('notice');
	}

}


<?php
declare(ticks=1);
namespace MQK\Process;

use Monolog\Logger;

abstract class AbstractWorker implements Worker
{
    /**
     * 进程ID
     * @var int
     */
    protected $id;

    /**
     * @var int
     */
    protected $createdAt = 0;

    /**
     * @var Logger
     */
    protected $logger;

    public function __construct($logger=null)
    {
        if (null == $logger)
            $this->logger = new Logger(__CLASS__);
    }

    /**
     * 启动进程
     * @return int pid
     */
    public function start()
    {
        $pid = pcntl_fork();

        if (-1 == $pid) {
            exit(1);
        } else if ($pid) {
            $this->id = $pid;
            return $pid;
        }
        pcntl_signal(SIGINT, function ($signalNumber) {
            $this->logger->debug("process {$this->id} got int signal");
            $this->quit();
            exit(0);
        });
        pcntl_signal(SIGQUIT, function ($signalNumber) {
            $this->logger->debug("process {$this->id} got quit signal");
            $this->graceFullQuit();
        });
        pcntl_signal(SIGTERM, function ($signalNumber) {
            $this->logger->debug("process {$this->id} got terminal signal");
            $this->quit();
            exit(0);
        });
        pcntl_signal(SIGUSR1, function ($sigalNumber) {
            $this->logger->debug("reopen logs");
            $this->reopenLogs();
        });
        $this->id = posix_getpid();
        $this->createdAt = time();

        // TODO: 进程退出后通知
        $this->run();
        exit();
    }

    /**
     * 抽象方法，进程启动成功后调用run方法。
     *
     * @return void
     */
    public function run()
    {
        $this->logger->debug("Worker process on {$this->id}");
    }

    protected function graceFullQuit()
    {
    }

    protected function reopenLogs()
    {

    }

    protected function quit()
    {

    }

    /**
     * @return void
     */
    protected function willTerminalProcess()
    {
    }

    protected function willQuitProcess()
    {

    }

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

    /**
     * 阻塞直到子进程退出
     */
    public function join()
    {
        $status = null;
        pcntl_waitpid($this->id, $status);
    }

}


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

namespace Praxigento\BonusHybrid\Service\Calc\Bonus\Team;

use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Repo\Data\Downline as EBonDwnl;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Data\Bonus as DBonus;
use Praxigento\Downline\Repo\Data\Customer as ECustomer;

/**
 * Calculate Team bonus according to EU scheme.
 */
class CalcEu
{
    /** @var \Praxigento\Downline\Api\Helper\Tree */
    private $hlpDwnlTree;
    /** @var \Praxigento\Core\Api\Helper\Format */
    private $hlpFormat;
    /** @var  \Praxigento\BonusHybrid\Api\Helper\Scheme */
    private $hlpScheme;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\Downline\Repo\Dao\Customer */
    private $daoDwnl;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Core\Api\Helper\Format $hlpFormat,
        \Praxigento\BonusHybrid\Api\Helper\Scheme $hlpScheme,
        \Praxigento\Downline\Api\Helper\Tree $hlpDwnlTree,
        \Praxigento\Downline\Repo\Dao\Customer $daoDwnl,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl
    )
    {
        $this->logger = $logger;
        $this->hlpFormat = $hlpFormat;
        $this->hlpScheme = $hlpScheme;
        $this->hlpDwnlTree = $hlpDwnlTree;
        $this->daoDwnl = $daoDwnl;
        $this->daoBonDwnl = $daoBonDwnl;
    }

    /**
     * Walk trough the compressed downline & calculate team bonus for EU scheme.
     *
     * @param int $calcId ID of the compression calculation to get downline.
     * @return Data[]
     */
    public function exec($calcId)
    {
        $result = [];
        /* collect additional data */
        $bonusPercent = Cfg::TEAM_BONUS_EU_PERCENT;
        $dwnlCompress = $this->daoBonDwnl->getByCalcId($calcId);
        $dwnlCurrent = $this->daoDwnl->get();
        /* create maps to access data */
        $mapDwnlById = $this->hlpDwnlTree->mapById($dwnlCompress, EBonDwnl::A_CUST_REF);
        $mapCustById = $this->hlpDwnlTree->mapById($dwnlCurrent, ECustomer::A_CUSTOMER_REF);
        /**
         * Go through all customers from compressed tree and calculate bonus.
         *
         * @var int $custId
         * @var EBonDwnl $custDwnl
         */
        foreach ($mapDwnlById as $custId => $custDwnl) {
            /** @var ECustomer $custData */
            $custData = $mapCustById[$custId];
            $custMlmId = $custData->getMlmId();
            $pv = $custDwnl->getPv();
            $parentId = $custDwnl->getParentRef();
            /** @var EBonDwnl $parentDwnl */
            $parentDwnl = $mapDwnlById[$parentId];
            /** @var ECustomer $parentData */
            $parentData = $mapCustById[$parentId];
            $parentMlmId = $parentData->getMlmId();
            $scheme = $this->hlpScheme->getSchemeByCustomer($parentData);
            if ($scheme == Cfg::SCHEMA_EU) {
                $pvParent = $parentDwnl->getPv();
                if ($pvParent > (Cfg::PV_QUALIFICATION_LEVEL_EU - Cfg::DEF_ZERO)) {
                    $bonus = $this->hlpFormat->roundBonus($pv * $bonusPercent);
                    if ($bonus > Cfg::DEF_ZERO) {
                        $entry = new DBonus();
                        $entry->setCustomerRef($parentId);
                        $entry->setDonatorRef($custId);
                        $entry->setValue($bonus);
                        $result[] = $entry;
                    }
                    $this->logger->debug("parent #$parentId (ref. #$parentMlmId) has '$bonus' as EU Team Bonus from downline customer #$custId (ref. #$custMlmId ).");
                } else {
                    $this->logger->debug("parent #$parentId (ref. #$parentMlmId) does not qualified t oget EU Team Bonus from downline customer #$custId (ref. #$custMlmId ).");
                }
            } else {
                $this->logger->debug("Parent #$parentId (ref. #$parentMlmId) has incompatible scheme '$scheme' for EU Team Bonus.");
            }
        }
        unset($mapCustById);
        unset($mapDwnlById);
        return $result;
    }

}


<?php

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

namespace Predis\Command\Redis;

use Predis\Command\Command as RedisCommand;

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

    /**
     * {@inheritdoc}
     */
    public function setArguments(array $arguments)
    {
        if (is_array(end($arguments))) {
            foreach (array_pop($arguments) as $modifier => $value) {
                $modifier = strtoupper($modifier);

                if ($modifier === 'COPY' && $value == true) {
                    $arguments[] = $modifier;
                }

                if ($modifier === 'REPLACE' && $value == true) {
                    $arguments[] = $modifier;
                }
            }
        }

        parent::setArguments($arguments);
    }
}


<?php
/**
 * This file is part of the MimeMailer package.
 *
 * Copyright (c) 2013-2016 Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The source code of this package is available online at
 * <http://github.com/atelierspierrot/mime-mailer>.
 */

namespace MimeMailer;

use \Library\Helper\Directory as DirectoryHelper;
use \Library\Helper\File as FileHelper;

/**
 * @author  piwi <me@e-piwi.fr>
 */
class SpoolManager
    implements SpoolInterface, CacheInterface
{

    /**
     * @var string The directory where to create spooled mails files
     */
    protected $spool_dir;

    /**
     * @var int The number of emails to send from spool for each sending
     */
    protected $spool_limit = 50;

    /**
     * @var \MimeMailer\SpoolingCacheInterface The cache object for emails spooling
     */
    protected $cache;

    /**
     * @var int Index of collection
     */
    protected $position = 0;

    /**
     * @var array Collection
     */
    protected $collection = array();

    /**
     * Construction of a MimeEmail object
     *
     * @param string $spool_dir
     */
    public function __construct($spool_dir = null)
    {
        if (!empty($spool_dir)) {
            $this->setSpoolDirectory($spool_dir);
        }
        $this->rewind();
    }

// -----------------------
// SpoolInterface
// -----------------------

    /**
     * Set the spooled mails directory
     *
     * @param string $dir The directory where to create spooled mails files
     * @return self
     * @throws \Exception if the directory doesn't exist and can't be created
     * @see \Library\Helper\Directory::ensureExists()
     */
    public function setSpoolDirectory($dir)
    {
        if (!DirectoryHelper::ensureExists($dir)) {
            throw new \Exception(
                sprintf('Can not create emails spooling directory "%s"!', $dir)
            );
        }
        $this->spool_dir = $dir;
        return $this;
    }

    /**
     * Get the spooled mails directory
     *
     * @return string
     */
    public function getSpoolDirectory()
    {
        return !empty($this->spool_dir) ? DirectoryHelper::slashDirname($this->spool_dir) : '';
    }

    /**
     * Set the spooled files ordering rule
     *
     * @param string $rule
     */
    public function setOrderBy($rule = 'mdate asc')
    {
    }

    public function addMessageToSpool($id, $contents)
    {
        $content = is_array($contents) ? serialize($contents) : $contents;
        return $this->cacheFile($id, $content, true);
    }

    public function getMessageFromSpool($id)
    {
    }

// -----------------------
// CacheInterface
// -----------------------

    /**
     *
     */
    public function cacheFile($filename, $content, $encode_filename = true)
    {
        if (empty($filename)) {
            $filename = uniqid();
        }
        if (true===$encode_filename) {
            $filename = $this->encodeFilename($filename);
        }
        $_fc = $this->getSpoolDirectory().$filename;
//var_export($_fc);
        $cached = fopen($_fc, "w");
        if ($cached) {
            fwrite($cached, $content);
            fclose($cached);
            return $_fc;
        }
        return false;
    }

    /**
     *
     */
    public function isCachedFile($filename)
    {
        $_fc = $this->getSpoolDirectory().$filename;
        if (file_exists($_fc)) {
            return true;
        }
        $_fce = $this->getSpoolDirectory().$this->encodeFilename($filename);
        if (file_exists($_fce)) {
            return true;
        }
        return false;
    }

    /**
     *
     */
    public function getCachedFile($filename)
    {
        $_fc = $this->getSpoolDirectory().$filename;
        if (file_exists($_fc)) {
            return file_get_contents($_fc);
        }
        $_fce = $this->getSpoolDirectory().$this->encodeFilename($filename);
        if (file_exists($_fce)) {
            return file_get_contents($_fce);
        }
        return null;
    }

    /**
     *
     */
    public function encodeFilename($filename)
    {
        return md5($filename);
    }

// -----------------------
// Iterator
// -----------------------

    public function rewind()
    {
        $this->position = 0;
    }

    public function current()
    {
        return $this->collection[$this->position];
    }

    public function key()
    {
        return $this->position;
    }

    public function next()
    {
        ++$this->position;
    }

    public function valid()
    {
        return isset($this->collection[$this->position]);
    }
}

// Endfile


<?php
namespace eMacros\Runtime\Builder;

use eMacros\Runtime\GenericFunction;
use eMacros\Applicable;
use eMacros\GenericList;
use eMacros\Scope;

class ArrayBuilder implements Applicable {
	/**
	 * Builds an array with the specified elements
	 * Usage: (array 1 null "Hello" (-7 56.25) ("key" "val"))
	 * Returns: array
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		$values = [];

		foreach ($arguments as $arg) {
			if ($arg instanceof GenericList) {
				if (count($arg) < 1) throw new \InvalidArgumentException("ArrayBuilder: No key defined.");
				if (count($arg) < 2) throw new \InvalidArgumentException("ArrayBuilder: No value defined.");
				//obtain symbol pair
				list($key, $value) = $arg;
				$key = $key->evaluate($scope);
				$values[$key] = $value->evaluate($scope);
			}
			else $values[] = $arg->evaluate($scope);
		}

		return $values;
	}
}
?>


<?php

namespace Bavix\SDK;

use Bavix\Exceptions\Invalid;
use Bavix\Helpers\Arr;
use Bavix\Helpers\File;
use Bavix\Helpers\JSON;
use Bavix\Helpers\Str;
use Bavix\Slice\Slice;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;

class Corundum
{

    /**
     * @var array
     */
    protected $tokens = [];

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

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

    /**
     * @var Slice
     */
    protected $slice;

    /**
     * @var Slice
     */
    protected $fake;

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

    /**
     * @var Slice
     */
    protected $results;

    /**
     * Corundum constructor.
     *
     * @param Slice $slice
     */
    public function __construct(Slice $slice)
    {
        $clientId = $slice->getRequired('app.client_id');
        $secret   = $slice->getRequired('app.client_secret');

        $this->slice    = $slice;
        $this->basic    = \base64_encode($clientId . ':' . $secret);
        $this->urlToken = $slice->getRequired('app.url.token');
    }

    /**
     * @return array
     */
    public function getTokens(): array
    {
        return $this->tokens;
    }

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

    /**
     * @return Slice
     */
    protected function fake(): Slice
    {
        if (!$this->fake)
        {
            $this->fake = new Slice([]);
        }

        return $this->fake;
    }

    /**
     * @return string
     *
     * @throws \RuntimeException
     */
    public function getBody(): string
    {
        return $this->response->getBody()
            ->getContents();
    }

    /**
     * @return Slice|null
     */
    public function getResults()
    {
        return $this->results;
    }

    /**
     * @return int|null
     */
    public function getCode()
    {
        if ($this->response)
        {
            return $this->response->getStatusCode();
        }

        return null;
    }

    /**
     * @param mixed $value
     *
     * @return mixed
     */
    protected function value($value)
    {
        if (Str::first($value) === '@')
        {
            return fopen(Str::withoutFirst($value), 'rb');
        }

        return $value;
    }

    /**
     * @param array $params
     *
     * @return array
     */
    protected function multipart(array $params): array
    {
        $results = [];

        foreach ($params as $key => $value)
        {
            $content = [
                'name'     => $key,
                'contents' => $this->value($value)
            ];

            if (\is_resource($content['contents']))
            {
                $content['filename'] = basename($value);
            }

            $results[] = $content;
        }

        return $results;
    }

    /**
     * @param Slice $options
     *
     * @return Slice|null
     *
     * @throws Invalid
     */
    protected function apiRequest(Slice $options)
    {
        $allow404 = $options->getData('allow404', false);
        $type     = $options->getData('token_type', 'Basic');
        $method   = $options->getData('method', 'POST');
        $token    = $options->getData('access_token', $this->basic);
        $url      = $options->getData('url', $this->urlToken);
        $params   = $options->getData('params', []);
        $headers  = $options->getData('headers', []);

        // headers
        $headers['Authorization'] = $type . ' ' . $token;

        $client = new Client([
            'debug'       => $this->slice->getData('debug', false),
            'http_errors' => false
        ]);

        $data = [
            'headers'   => $headers,
            'multipart' => $this->multipart($params),
        ];

        $this->response = $client->request(
            Str::upp($method),
            $url,
            $data
        );

        $this->results = null;

        $response = JSON::decode(
            $this->getBody()
        );

        if (JSON::errorNone())
        {
            $this->results = new Slice($response);
        }

        $code = $this->getCode();

        if ($allow404 && $code === 404)
        {
            return $this->getResults();
        }

        if ($code > 199 && $code < 300)
        {
            return $this->getResults();
        }

        throw new Invalid(
            'Error: ' . $this->response->getReasonPhrase(),
            $code
        );
    }

    /**
     * @param string $user
     * @param array  $params
     *
     * @return Slice
     *
     * @throws Invalid
     */
    protected function authorize(string $user, array $params = []): Slice
    {
        $grantType = $this->slice->getData('grant_type', 'password');
        $userData  = $this->slice->getSlice('users.' . $user);
        $defaults  = [
            'username'   => $userData->getRequired('username'),
            'password'   => $userData->getRequired('password'),
            'grant_type' => $grantType,
        ];

        $response = $this->apiRequest(new Slice([
            'params' => Arr::merge($defaults, $params)
        ]));

        if ($response)
        {
            $response->expires = Carbon::now()
                ->addSeconds($response->expires_in);
        }

        return $response;
    }

    /**
     * @param string $user
     * @param string $scope
     *
     * @return Slice
     *
     * @throws Invalid
     */
    protected function getToken(string $user, string $scope = ''): Slice
    {
        if (!isset($this->tokens[$user]))
        {
            $this->tokens[$user] = $this->authorize($user, [
                'scope' => $scope
            ]);
        }

        return $this->tokens[$user];
    }

    /**
     * @param string $user
     *
     * @return Slice
     *
     * @throws Invalid
     */
    protected function refreshToken(string $user): Slice
    {
        /**
         * @var $token Slice
         */
        $token = $this->tokens[$user];

        return $this->tokens[$user] = $this->authorize($user, [
            'grant_type'    => 'refresh_token',
            'refresh_token' => $token->getRequired('refresh_token'),
        ]);
    }

    /**
     * @param string $user
     * @param string $file
     * @param Slice  $options
     *
     * @return Slice
     *
     * @throws Invalid
     */
    public function upload(string $user, string $file, Slice $options = null): Slice
    {
        if (!File::isFile($file))
        {
            throw new \Bavix\Exceptions\NotFound\Path('File not found!');
        }

        if (!$options)
        {
            $options = $this->fake();
        }

        $token = $this->getToken(
            $user,
            $options->getData('scope', '')
        );

        return $this->apiSend(
            $this->uploadSlice($token, $options, $file),
            function () use ($user, $options, $file) {
                return $this->uploadSlice(
                    $this->tokenUpdate($user, $options),
                    $options,
                    $file
                );
            }
        );
    }

    /**
     * @param string     $user
     * @param string     $name
     * @param Slice|null $options
     *
     * @return Slice
     */
    public function update(string $user, string $name, Slice $options = null): Slice
    {
        if (!$options)
        {
            $options = $this->fake();
        }

        $token = $this->getToken(
            $user,
            $options->getData('scope', '')
        );

        $options->allow404 = true;

        $urlUpload    = $this->slice->getRequired('app.url.upload');
        $options->url = Path::slash($urlUpload) . $name;

        return $this->apiSend(
            $this->uploadSlice($token, $options),
            function () use ($user, $options) {
                return $this->uploadSlice(
                    $this->tokenUpdate($user, $options),
                    $options
                );
            }
        );
    }

    /**
     * @param string     $user
     * @param string     $name
     * @param Slice|null $options
     *
     * @return Slice|null
     */
    public function delete(string $user, string $name, Slice $options = null)
    {
        if (!$options)
        {
            $options = $this->fake();
        }

        $token = $this->getToken(
            $user,
            $options->getData('scope', '')
        );

        $options->allow404 = true;

        $urlUpload    = $this->slice->getRequired('app.url.upload');
        $options->url = Path::slash($urlUpload) . $name;

        $options->method = 'delete';

        return $this->apiSend(
            $this->uploadSlice($token, $options),
            function () use ($user, $options) {
                return $this->uploadSlice(
                    $this->tokenUpdate($user, $options),
                    $options
                );
            }
        );
    }

    /**
     * @param Slice    $slice
     * @param callable $callback
     *
     * @return Slice|null
     */
    protected function apiSend(Slice $slice, callable $callback)
    {
        try
        {
            return $this->apiRequest($slice);
        }
        catch (\Throwable $throwable)
        {
            return $this->apiRequest($callback());
        }
    }

    /**
     * @param Slice  $token
     * @param Slice  $options
     * @param string $file
     *
     * @return Slice
     */
    protected function uploadSlice(Slice $token, Slice $options, string $file = null): Slice
    {
        $params = $options->getData('params', []);

        if ($file)
        {
            $params = Arr::merge($params, [
                'file' => '@' . \ltrim($file, '@')
            ]);
        }

        return new Slice([
            'token_type'   => $token->getRequired('token_type'),
            'access_token' => $token->getRequired('access_token'),
            'method'       => $options->getData('method', 'post'),
            'url'          => $options->getData(
                'url',
                $this->slice->getRequired('app.url.upload')
            ),

            'allow404' => $options->getData('allow404', false),

            'headers' => Arr::merge($options->getData('headers', []), [
                'Accept' => 'application/json'
            ]),

            'params' => $params
        ]);
    }

    /**
     * @param Slice $token
     *
     * @return Slice
     *
     * @throws Invalid
     */
    protected function verify(Slice $token): Slice
    {
        return $this->apiRequest(new Slice([
            'token_type'   => $token->getRequired('token_type'),
            'access_token' => $token->getRequired('access_token'),
            'url'          => $this->slice->getRequired('app.url.verify'),
            'headers'      => [
                'Accept' => 'application/json'
            ]
        ]));
    }

    /**
     * @param string $user
     * @param Slice  $slice
     *
     * @return Slice
     *
     * @throws Invalid
     */
    protected function tokenUpdate(string $user, Slice $slice): Slice
    {
        try
        {
            $token  = $this->refreshToken($user);
            $verify = $this->verify($token);

            if (!$verify || !$verify->getRequired('verify'))
            {
                throw new Invalid('The token isn\'t verified');
            }
        }
        catch (Invalid $invalid)
        {
            $this->tokens[$user] = null;

            $token = $this->getToken(
                $user,
                $slice->getData('scope', '')
            );
        }

        return $token;
    }

}


<?php
namespace Lead\Benchmark;

use Exception;
use Lead\Benchmark\Reporter\Text;

class Benchmark
{
    /**
     * The repetition number.
     *
     * @var array
     */
    protected $_repeat = 1;

    /**
     * The task collection.
     *
     * @var array
     */
    protected $_tasks = [];

    /**
     * The matrix instance.
     *
     * @var object
     */
    protected $_matrix = null;

    /**
     * The textual reporter instance.
     *
     * @var object
     */
    protected $_text = null;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->_text = new Text($this);
    }

    /**
     * Gets/sets the repeat number.
     *
     * @param  integer $repeat The repeat value to set or none the get the current one.
     * @return integer         The repeat value or `$this` on set.
     */
    public function repeat($repeat = null)
    {
        if (!func_num_args()) {
            return $this->_repeat;
        }
        $this->_repeat = $repeat;
        return $this;
    }

    /**
     * Wraps a callable with start() and end() calls
     *
     * Additional arguments passed to this method will be passed to
     * the callable.
     *
     * @param  callable $callable
     * @param  mixed    ...
     * @return mixed
     */
    public function run($taskName, $callback)
    {
        $args = func_get_args();
        array_shift($args);
        array_shift($args);

        $task = $this->start($taskName, $this->repeat());
        for ($i = 0; $i < $task->repeat(); $i++) {
            if (($success = call_user_func_array($callback, $args)) === false)   {
                $task->failed(true);
                break;
            }
        }
        $this->end($taskName);
        return $task;
    }

    /**
     * Starts the timer for a task
     *
     * @param  string  $taskName The taskname to start.
     * @param  integer $repeat   The number of times the task will be executed.
     * @return object            The started task.
     */
    public function start($taskName, $repeat = null)
    {
        $task = new Task();
        $task->name($taskName);
        if ($repeat) {
            $task->repeat($repeat);
        }
        if (isset($this->_tasks[$taskName])) {
            throw new Exception("Task {$taskName} is already defined.");
        }
        $this->_tasks[$taskName] = $task;
        $task->start();
        return $task;
    }

    /**
     * Ends the timer for a task
     *
     * @param  string $taskName The taskname to stop the timer for.
     * @return object           The stopped task.
     */
    public function end($taskName)
    {
        if (!isset($this->_tasks[$taskName])) {
            throw new Exception("Undefined task name: `'{$taskName}`.");
        }
        $task = $this->_tasks[$taskName];
        $task->end();
        return $task;
    }

    /**
     * Returns a specific task.
     *
     * @return string $name The task name.
     */
    public function task($name)
    {
        return $this->_tasks[$name];
    }

    /**
     * Returns all created tasks.
     *
     * @return array
     */
    public function tasks()
    {
        return array_values($this->_tasks);
    }

    /**
     * Returns the total duration.
     *
     * @return integer The total duration (in microseconds).
     */
    public function duration()
    {
        $duration = 0;
        foreach ($this->_tasks as $task) {
            $duration += $task->duration();
        }
        return $duration;
    }

    /**
     * Returns the processed matrix result report.
     *
     * @return object
     */
    public function matrix()
    {
        if ($this->_matrix) {
            return $this->_matrix;
        }
        $this->_matrix = new Matrix($this->tasks());
        $this->_matrix->process();
        return $this->_matrix;
    }

    /**
     * Returns the reporter
     *
     * @return object
     */
    public function __call($name, $params)
    {
        return call_user_func_array([$this->_text, $name], $params);
    }

    /**
     * Returns the system info.
     *
     * @return string The system info.
     */
    public static function systemInfo()
    {
        $result .= 'PHP Version: ' . PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION . ' [' . PHP_OS . ']' . "\n";

        if(extension_loaded('xdebug')) {
            $result .= "With XDebug Extension.\n";
        }
        return $result;
    }

    /**
     * Titleizes a string
     *
     * @param string $title The string to titleize.
     */
    public static function title($title, $pad = '=')
    {
        $rest = (int) (78 - mb_strlen($title)) / 2;

        $result = "\n\n";
        $result .= str_repeat($pad, $rest);
        $result .= ' ' . $title . ' ';
        $result .= str_repeat($pad, $rest);
        $result .= "\n\n";
        return $result;
    }
}


<?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 Silex\Application;
use Symfony\Component\OptionsResolver\OptionsResolver;

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

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

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


<?php

declare (strict_types=1);

namespace Coshi\Variator\Variation;

use Coshi\Variator\ConfigResolver;

abstract class AbstractVariation implements VariationInterface
{
    /**
     * @var array
     */
    protected $requiredArgs = [];

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

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

    /**
     * @var bool
     */
    protected $contextDependent;

    /**
     * @var callable[]
     */
    protected $contextCallbacks;

    /**
     * @var VariationInterface[];
     */
    protected $nested = [];

    /**
     * @var ConfigResolver
     */
    protected $configResolver;

    /**
     * @var int
     */
    private $sumKey = 0;

    public function __construct(string $name, array $parameters, ConfigResolver $configResolver)
    {
        $this->name = $name;
        $this->parameters = $parameters;
        $this->configResolver = $configResolver;

        if (isset($parameters['context_dependent'])) {
            $this->contextDependent = $parameters['context_dependent'];
        }
        $this->requireArguments($parameters);
    }

    /**
     * @return void
     */
    abstract protected function doRewind();

    /**
     * @return void
     */
    abstract protected function pushForward();

    /**
     * @return bool
     */
    abstract protected function isValid() : bool;

    /**
     * @return mixed
     */
    abstract protected function getCurrent();

    /**
     * {@inheritdoc}
     */
    public function current()
    {
        $result = [];

        if (!$this->isRoot()) {
            $result = [
                $this->getName() => $this->getCurrent(),
            ];
        }
        $nested = $this->getNested();

        foreach ($nested as $variation) {
            $result = array_merge($result, $variation->current());
        }

        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function next()
    {
        ++$this->sumKey;
        $nested = $this->getNested();

        foreach ($nested as $variation) {
            if (!$variation->valid()) {
                continue;
            }
            $variation->next();

            if (!$variation->valid()) {
                continue;
            }
            $this->reset();

            return;
        }
        $this->pushForward();

        if (!$this->isValid()) {
            return;
        }
        $this->reset(false);
    }

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

    /**
     * {@inheritdoc}
     */
    public function valid()
    {
        foreach ($this->getNested() as $variation) {
            if ($variation->isValid()) {
                return true;
            }
        }

        return $this->isValid();
    }

    /**
     * {@inheritdoc}
     */
    public function rewind()
    {
        $this->doRewind();
        $this->reset(false);
    }

    /**
     * {@inheritdoc}
     */
    public function isContextDependent() : bool
    {
        return (bool) $this->contextDependent;
    }

    /**
     * {@inheritdoc}
     */
    public function dependsOn(string $name) : bool
    {
        return $this->isContextDependent();
    }

    /**
     * {@inheritdoc}
     */
    public function getNested() : array
    {
        return $this->nested;
    }

    /**
     * {@inheritdoc}
     */
    public function addNested(VariationInterface $variation) : VariationInterface
    {
        $this->configResolver->addCallback($this);
        $this->nested[] = $variation;

        return $this;
    }

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

    /**
     * @param array  $arguments
     * @param string $name
     *
     * @return bool
     */
    protected function containsArgumentsPattern(array $arguments, string $name) : bool
    {
        return $this->configResolver->containsArgumentsPattern($arguments, $name);
    }

    /**
     * @param array $parameters
     *
     * @return bool
     *
     * @throws \Coshi\Variator\Exception\InvalidConfigurationException
     */
    protected function requireArguments(array $parameters) : bool
    {
        return $this->configResolver->requireArguments($this->requiredArgs, $parameters, $this->getType());
    }

    /**
     * @return bool
     */
    protected function isRoot() : bool
    {
        return 'container' === $this->getType();
    }

    /**
     * @param bool $strict
     *
     * @return bool
     */
    private function reset(bool $strict = true) : bool
    {
        foreach ($this->getNested() as $variation) {
            if (!$strict || !$variation->isValid()) {
                $variation->rewind();
            }
        }

        return true;
    }
}


<?php namespace Ordercloud\Cart;

use Ordercloud\Cart\Entities\Cart;
use Ordercloud\Cart\Entities\Policies\BaseCartPolicy;
use Ordercloud\Cart\Entities\Policies\CartPolicy;
use Ordercloud\Cart\Exceptions\CartItemNotFoundException;
use Ordercloud\Cart\Exceptions\CartNotFoundException;
use Ordercloud\Cart\Infrastructure\CartRepository;
use Ordercloud\Entities\Products\Product;

class CartService
{
    /**
     * @var CartRepository
     */
    private $repository;
    /**
     * @var CartPolicy
     */
    private $cartPolicy;

    /**
     * @param CartRepository $repository
     * @param CartPolicy     $defaultCartPolicy
     */
    public function __construct(CartRepository $repository, CartPolicy $defaultCartPolicy = null)
    {
        $this->repository = $repository;
        $this->cartPolicy = is_null($defaultCartPolicy) ? new BaseCartPolicy() : $defaultCartPolicy;
    }

    /**
     * @return Cart
     */
    public function createCart()
    {
        $cart = new Cart(uniqid(), $this->cartPolicy);

        $this->saveCart($cart);

        return $cart;
    }

    /**
     * @param string $id
     *
     * @return Cart
     *
     * @throws CartNotFoundException
     */
    public function getCartById($id)
    {
        return $this->repository->findById($id);
    }

    /**
     * @param Cart $cart
     */
    protected function saveCart(Cart $cart)
    {
        $this->repository->save($cart);
    }

    /**
     * @param int $cartId
     *
     * @throws CartNotFoundException
     */
    public function destroyCart($cartId)
    {
        $cart = $this->getCartById($cartId);

        $this->repository->destroy($cart);
    }

    /**
     * @param int     $cartId
     * @param Product $product
     * @param int     $quantity
     * @param array   $options array( optionSetId => optionId, ... )
     * @param array   $extras array( extraSetId_extraId, ... )
     * @param string  $note
     *
     * @throws CartNotFoundException
     */
    public function addItem($cartId, Product $product, $quantity = 1, array $options = [], array $extras = [], $note = null)
    {
        $cart = $this->getCartById($cartId);

        $cart->addItem($product, $quantity, $options, $extras, $note);

        $this->saveCart($cart);
    }

    /**
     * @param int    $cartId
     * @param string $itemPuid
     *
     * @throws CartNotFoundException
     * @throws CartItemNotFoundException
     */
    public function removeItem($cartId, $itemPuid)
    {
        $cart = $this->getCartById($cartId);

        $cart->removeItem($itemPuid);

        $this->saveCart($cart);
    }

    /**
     * @param int    $cartId
     * @param string $itemPuid
     * @param int    $quantity
     *
     * @throws CartNotFoundException
     * @throws CartItemNotFoundException
     */
    public function updateItemQuantity($cartId, $itemPuid, $quantity)
    {
        $cart = $this->getCartById($cartId);

        $cart->updateItemQuantity($itemPuid, $quantity);

        $this->saveCart($cart);
    }

    /**
     * @param string $cartId
     * @param string $note
     */
    public function changeNote($cartId, $note)
    {
        $cart = $this->getCartById($cartId);

        $cart->changeNote($note);

        $this->saveCart($cart);
    }
}