<?php

namespace Dothiv\Bundle\ContentfulBundle\Controller;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Persistence\ObjectManager;
use Dothiv\Bundle\ContentfulBundle\Adapter\ContentfulContentTypeReader;
use Dothiv\Bundle\ContentfulBundle\Adapter\ContentfulEntityReader;
use Dothiv\Bundle\ContentfulBundle\DothivContentfulBundleEvents;
use Dothiv\Bundle\ContentfulBundle\Event\ContentfulAssetEvent;
use Dothiv\Bundle\ContentfulBundle\Event\ContentfulContentTypeEvent;
use Dothiv\Bundle\ContentfulBundle\Event\ContentfulEntryEvent;
use Dothiv\Bundle\ContentfulBundle\Event\DeletedContentfulEntryEvent;
use Dothiv\Bundle\ContentfulBundle\Item\ContentfulContentType;
use Dothiv\Bundle\ContentfulBundle\Logger\LoggerAwareTrait;
use Dothiv\Bundle\ContentfulBundle\Repository\ContentfulContentTypeRepository;
use Psr\Log\LoggerAwareInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class WebhookController implements LoggerAwareInterface
{
    use LoggerAwareTrait;

    public function __construct(
        ContentfulContentTypeRepository $contentTypeRepo,
        EventDispatcherInterface $dispatcher,
        ObjectManager $em)
    {
        $this->contentTypeRepo = $contentTypeRepo;
        $this->dispatcher      = $dispatcher;
        $this->em              = $em;
    }

    public function webhookAction(Request $request)
    {
        $topic = $request->headers->get('X-Contentful-Topic');
        if (!$topic) {
            $this->log('Missing X-Contentful-Topic header!');
            throw new BadRequestHttpException(sprintf(
                'Missing X-Contentful-Topic header!'
            ));
        }
        $data = json_decode($request->getContent());
        if (!is_object($data) || !property_exists($data, 'sys')) {
            throw new BadRequestHttpException('JSON object expected.');
        }
        $id      = $data->sys->id;
        $spaceId = $data->sys->space->sys->id;
        $this->log('%s Webhook called for space %s: type: %s, id: %s', $topic, $spaceId, $data->sys->type, $id);

        switch ($topic) {
            case 'ContentManagement.ContentType.publish':
                $reader      = new ContentfulContentTypeReader($spaceId);
                $contentType = $reader->getContentType($data);
                $this->dispatcher->dispatch(
                    DothivContentfulBundleEvents::CONTENT_TYPE_SYNC,
                    new ContentfulContentTypeEvent($contentType)
                );
                break;
            case 'ContentManagement.ContentType.unpublish':
                // TODO: Implement "ContentManagement.ContentType.unpublish"
                break;
            case 'ContentManagement.Entry.publish':
                $reader = new ContentfulEntityReader($spaceId, $this->getContentTypes($spaceId));
                $entry  = $reader->getEntry($data);
                $this->dispatcher->dispatch(
                    DothivContentfulBundleEvents::ENTRY_SYNC,
                    new ContentfulEntryEvent($entry)
                );
                break;
            case 'ContentManagement.Entry.unpublish':
                $reader = new ContentfulEntityReader($spaceId, $this->getContentTypes($spaceId));
                $entry  = $reader->getEntry($data);
                $this->dispatcher->dispatch(
                    DothivContentfulBundleEvents::ENTRY_DELETE,
                    new DeletedContentfulEntryEvent($entry)
                );
                break;
            case 'ContentManagement.Asset.publish':
                $reader = new ContentfulEntityReader($spaceId, $this->getContentTypes($spaceId));
                $entry  = $reader->getEntry($data);
                $this->dispatcher->dispatch(
                    DothivContentfulBundleEvents::ASSET_SYNC,
                    new ContentfulAssetEvent($entry)
                );
                break;
            case 'ContentManagement.Asset.unpublish':
                // TODO: Implement "ContentManagement.Asset.unpublish"
                break;
        }

        $this->em->flush();

        $response = new Response('', 204);
        return $response;
    }

    /**
     * @param string $spaceId
     *
     * @return ArrayCollection|ContentfulContentType[]
     */
    protected function getContentTypes($spaceId)
    {
        $ctypes = new ArrayCollection();
        foreach ($this->contentTypeRepo->findAllBySpaceId($spaceId) as $c) {
            $ctypes->set($c->getId(), $c);
        }
        return $ctypes;
    }
}


<?php

namespace carlosV2\DumbsmartRepositoriesBundle\Metadata;

use carlosV2\DumbsmartRepositories\Exception\MetadataNotFoundException;
use carlosV2\DumbsmartRepositories\Metadata;
use carlosV2\DumbsmartRepositories\MetadataManager;
use carlosV2\DumbsmartRepositories\Relation\OneToManyRelation;
use carlosV2\DumbsmartRepositories\Relation\OneToOneRelation;
use carlosV2\DumbsmartRepositories\Relation\Relation;

class AliasedMetadataFactory
{
    /**
     * @var MetadataManager
     */
    private $manager;

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

    /**
     * @param array $alias
     *
     * @return Metadata
     *
     * @throws MetadataNotFoundException
     */
    public function createMetadata(array $alias)
    {
        $metadata = $this->manager->getMetadataForClassName($alias['class']);
        $aliasedMetadata = new Metadata($metadata->getObjectIdentifier());

        foreach ($metadata->getRelations() as $relation) {
            if (array_key_exists($relation->getField(), $alias['mapping'])) {
                $aliasedMetadata->setRelation(
                    $this->createAliasedRelation(
                        $alias['mapping'][$relation->getField()],
                        $relation
                    )
                );
            } else {
                $aliasedMetadata->setRelation($relation);
            }
        }

        return $aliasedMetadata;
    }

    /**
     * @param string   $field
     * @param Relation $relation
     *
     * @return Relation
     */
    private function createAliasedRelation($field, Relation $relation)
    {
        if ($relation instanceof OneToOneRelation) {
            return new OneToOneRelation($field);
        } elseif ($relation instanceof OneToManyRelation) {
            return new OneToManyRelation($field);
        }
    }
}


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

namespace Controller\Page;

use RedKiteCms\Rendering\Controller\Page\PublishPageController as BasePublishPageController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * This object implements the Silex controller to publish a page in production
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Seo
 */
class PublishPageController extends BasePublishPageController
{
    /**
     * Publish page action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function publishAction(Request $request, Application $app)
    {
        $options = array(
            "request" => $request,
            "page_manager" => $app["red_kite_cms.page_manager"],
            "username" => $this->fetchUsername($app["security"], $app["red_kite_cms.configuration_handler"]),
        );

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


<?php

namespace Senhung\CLI;

/**
 * Class Service
 * @package Senhung\CLI
 *
 * Helper class for Senhung\CLI\Command and Senhung\CLI\CommandEntry
 */
class Service
{
    /** Command Types */
    public const COMMAND_TYPE = 'COMMAND_TYPE';
    public const ARGUMENT_TYPE = 'ARGUMENT_TYPE';
    public const OPTION_TYPE = 'OPTION_TYPE';

    /**
     * Get all registered commands
     *
     * @return array
     */
    public static function getAllCommands(): array
    {
        /* Get All Commands */
        $commands = [];
        foreach (get_declared_classes() as $class) {
            if (is_subclass_of($class, 'Senhung\CLI\Command')) {
                $commandObject = new $class;
                $command = $commandObject->getCommand();
                $commands[$command] = $class;
            }
        }

        return $commands;
    }

    /**
     * Parse command signature to command, arguments and options
     *
     * @param string $signature
     * @return array
     */
    public static function parseSignature(string $signature): array
    {
        /* Parse Signature to Array */
        $signature = explode(' ', trim($signature));

        /* Initialize */
        $command = trim($signature[0]);
        $arguments = [];
        $options = [];

        /* Check Each Word */
        foreach ($signature as $word) {
            $type = self::determineTypeOfWord($word);

            /* Option */
            if ($type == self::OPTION_TYPE) {
                list($key, $defaultValue) = self::parse($word);
                $options[$key] = $defaultValue;
            }

            /* Argument */
            elseif ($type == self::ARGUMENT_TYPE) {
                list($key, $defaultValue) = self::parse($word);
                $arguments[$key] = $defaultValue;
            }
        }

        return [$command, $arguments, $options];
    }

    /**
     * Run command handle
     *
     * @param string $command
     * @param array|null $arguments
     * @param array|null $options
     * @return void
     */
    public static function runCommand(string $command, array $arguments = null, array $options = null): void
    {
        $commandObject = new $command($arguments, $options);

        $commandObject->update($arguments, $options);

        $commandObject->handle();
    }

    /**
     * Parse an argument or option to its key and value
     *
     * @param string $word
     * @return array
     */
    public static function parse(string $word): array
    {
        $word = ltrim(rtrim(trim($word), '}'), '{');

        /* Having Default Value */
        if ($separatorPosition = strpos($word, '=')) {
            $key = substr($word, 0, $separatorPosition);
            $defaultValue = substr($word, $separatorPosition + 1);
            return [$key, $defaultValue];
        }

        return [$word, null];
    }

    /**
     * Determine the type of a string
     * Option: --option
     * Argument: :argument
     * Command: command
     *
     * @param string $word
     * @return string
     */
    public static function determineTypeOfWord(string $word): string
    {
        $word = ltrim(rtrim(trim($word), '}'), '{');

        /* Is Option Type */
        if (substr($word, 0, 2) == '--') {
            return self::OPTION_TYPE;
        }

        /* Is Argument Type */
        elseif (substr($word, 0, 1) == ':') {
            return self::ARGUMENT_TYPE;
        }

        /* Is Command Type */
        return self::COMMAND_TYPE;
    }
}


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

namespace RedKiteCms\Content\SlotsManager;

/**
 * Class SlotsManagerLanguage is the object assigned to cretae a slot repeated at language level
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\SlotsManager
 */
class SlotsManagerLanguage extends SlotsManager
{
    /**
     *{@inheritdoc}
     */
    public function addSlot($slotName, $blocks = array(), $username = null)
    {
        $slotsDir = $this->siteDir . '/slots/' . $slotName;
        foreach ($this->siteInfo["languages"] as $languageName) {
            $languageDir = $slotsDir . '/' . $languageName;
            $this->generateSlot($languageDir, $blocks, $username);
        }
    }
}


<?php

/**
 * (c) Paulus Gandung Prakosa (rvn.plvhx@gmail.com)
 */

namespace DependencyInjection;

use Psr\Container\ContainerInterface;
use DependencyInjection\Exception\ContainerException;
use DependencyInjection\Exception\NotFoundException;

class Container implements \ArrayAccess, ContainerInterface
{
    /**
     * @var array
     */
    private $bindings = [];

    /**
     * @var array
     */
    private $resolved = [];

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

    /**
     * Resolving all dependencies in the supplied class or object instance constructor.
     *
     * @param string $instance The class name.
     * @param array $parameters List of needed class dependency.
     * @return object
     */
    public function make($instance, $parameters = [])
    {
        return $this->resolve($instance, is_array($parameters) ? $parameters
            : array_slice(func_get_args(), 1));
    }

    /**
     * Register a service alias.
     *
     * @param string $alias The alias name.
     * @param string $abstract The class name.
     */
    public function register($alias, $abstract)
    {
        if (!is_string($alias) || !is_string($abstract)) {
            throw new \InvalidArgumentException(
                sprintf("Parameter 1 and 2 of %s must be a string.", __METHOD__)
            );
        }

        if (!isset($this->aliases[$alias])) {
            $this->aliases[$alias] = $this->make($abstract);
        }

        return $this;
    }

    /**
     * Determine if registered alias were exists.
     *
     * @param string $alias The alias name.
     */
    public function isAliasExists($alias)
    {
        return isset($this->aliases[$alias]);
    }

    /**
     * Finds an entry of the container by its identifier and returns it.
     *
     * @param string $id Identifier of the entry to look for.
     *
     * @throws NotFoundExceptionInterface  No entry was found for **this** identifier.
     * @throws ContainerExceptionInterface Error while retrieving the entry.
     *
     * @return mixed Entry.
     */
    public function get($id)
    {
        if (!$this->isAliasExists($id)) {
            throw new NotFoundException(
                sprintf("Identifier %s was not found in our service container stack.", $id)
            );
        }

        return $this->aliases[$id];
    }

    /**
     * Returns true if the container can return an entry for the given identifier.
     * Returns false otherwise.
     *
     * `has($id)` returning true does not mean that `get($id)` will not throw an exception.
     * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
     *
     * @param string $id Identifier of the entry to look for.
     *
     * @return bool
     */
    public function has($id)
    {
        return $this->isAliasExists($id);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetExists($offset)
    {
        return $this->isBound($offset);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetGet($offset)
    {
        return $this->make($offset);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetSet($offset, $value)
    {
        $this->bind($offset, $value instanceof \Closure ? $value : $this->turnIntoResolvableClosure($offset, $value));
    }

    /**
     * {@inheritdoc}
     */
    public function offsetUnset($offset)
    {
        unset($this->bindings[$offset], $this->resolved[$offset]);
    }

    /**
     * Determine if defined abstract class name were in resolved concrete stack and it was a
     * singleton.
     *
     * @param string $abstract The resolved abstract class name.
     */
    public function hasResolvedSingleton($abstract)
    {
        $flag = $this->getResolvedConcreteFlag($abstract);

        return in_array('singleton', $flag, true);
    }

    /**
     * Get singleton resolved concrete from defined abstract class name.
     *
     * @param string $abstract The resolved abstract class name.
     */
    public function getResolvedSingleton($abstract)
    {
        return ($this->hasResolvedSingleton($abstract)
            ? $this->resolved[$abstract]['concrete']
            : null);
    }

    /**
     * Determine if defined abstract class name were in resolved concrete stack.
     *
     * @param string $abstract The resolved abstract class name.
     */
    public function hasResolvedConcrete($abstract)
    {
        return isset($this->resolved[$abstract]);
    }

    /**
     * Get flag of resolved concrete behavior on abstract class name.
     *
     * @param string $abstract The resolved abstract class name.
     */
    public function getResolvedConcreteFlag($abstract)
    {
        if (!$this->hasResolvedConcrete($abstract)) {
            throw Internal\Exception\ReflectionExceptionFactory::invalidArgument(
                sprintf(
                    "Parameter 1 of %s must be an abstract class name which exists in resolved concrete stack.",
                     __METHOD__
                )
            );
        }

        return explode('|', $this->resolved[$abstract]['flag']);
    }

    /**
     * Get resolved concrete from defined abstract class name.
     *
     * @param string $abstract The resolved abstract class name.
     */
    public function getResolvedConcrete($abstract)
    {
        return ($this->hasResolvedConcrete($abstract)
            ? $this->resolved[$abstract]['concrete']
            : null);
    }

    /**
     * Get list of unresolved class name from class binding stack.
     *
     * @return string
     */
    protected function getAbstracts()
    {
        return array_keys($this->bindings);
    }

    /**
     * Determine if unresolved class name is exists.
     *
     * @param string $abstract The unresolved class name.
     * @return bool
     */
    public function isAbstractExists($abstract)
    {
        return array_key_exists($abstract, $this->bindings);
    }

    /**
     * Determine if unresolved abstract is an interface.
     *
     * @param string $abstract The unresolved abstract name.
     */
    public function isInterface($abstract)
    {
        $reflector = Internal\ReflectionClassFactory::create($abstract);

        return $reflector->isInterface();
    }

    /**
     * Get concrete list of dependencies based on supplied class name.
     *
     * @param string $abstract The unresolved class name.
     * @return array
     */
    public function getAbstractDependencies($abstract)
    {
        return ($this->isAbstractExists($abstract) ? $this->bindings[$abstract] : null);
    }

    /**
     * Resolve class dependencies in the supplied class name.
     *
     * @param string $instance The class name.
     * @param array $parameters The needed class dependency.
     * @return object
     */
    protected function resolve($instance, $parameters = [])
    {
        // If the current abstract is an interface,
        // just return the concrete implementation to the callee.
        if ($this->isInterface($instance)) {
            return $this->getConcreteFromInterface($instance);
        }

        // If the current abstract type being managed as a singleton,
        // just return it to the caller instead of reinstantiating it.
        try {
            return $this->getResolvedSingleton($instance);
        } catch (\Exception $e) {
        }

        $concrete = $this->getConcrete($instance);

        if (!is_null($concrete)) {
            $object = $this->build($instance,
                $concrete instanceof \Closure ? $concrete($this) : $concrete);

            if ($this->isShared($instance)) {
                $this->markAsResolved($instance, $object, 'singleton');
            } else {
                $this->markAsResolved($instance, $object);
            }
        } else {
            $object = $this->build($instance, $parameters);
        }

        return $object;
    }

    protected function build($instance, $parameters = [])
    {
        $parameters = (is_null($parameters)
            ? []
            : (is_array($parameters)
                ? $parameters
                : array_slice(func_get_args(), 1)));

        $reflector = Internal\ReflectionClassFactory::create($instance);

        if (!$this->hasConstructor($reflector)) {
            return $this->resolveInstanceWithoutConstructor($reflector);
        }

        if (is_array($parameters) && empty(sizeof($parameters))) {
            $constructorParams = $this->getMethodParameters($reflector, '__construct');

            if (!is_null($constructorParams)) {
                $params = $this->resolveMethodParameters($constructorParams);
            }
        } elseif (is_array($parameters) && !empty(sizeof($parameters))) {
            $params = $this->resolveMethodParameters($parameters);
        }

        return $reflector->newInstanceArgs(!empty($parameters) ? $parameters : $params);
    }

    /**
     * Resolve method parameters.
     *
     * @param array $params The unresolvable method.
     * @return array
     */
    protected function resolveMethodParameters($params = [])
    {
        if (!is_array($params)) {
            throw new \InvalidArgumentException(
                sprintf("Parameter 1 of %s must be an array.", __METHOD__)
            );
        }

        foreach ($params as $key => $value) {
            if ($value instanceof \ReflectionParameter) {
                $class = $value->getClass();

                if ($class instanceof \ReflectionClass) {
                    if ($class->isInterface()) {
                        $params[$key] = $this->getConcreteFromInterface($class->getName());
                    } else {
                        $params[$key] = $this->circularDependencyResolver($class->getName());
                    }
                } else {
                    $params[$key] = ($value->isDefaultValueAvailable()
                        ? $value->getDefaultValue() : null);
                }
            } else {
                if (is_string($value) && class_exists($value)) {
                    $params[$key] = $this->circularDependencyResolver($value);
                } elseif ($value instanceof \Closure) {
                    $params[$key] = $value($this);
                } else {
                    $params[$key] = $value;
                }
            }
        }

        return $params;
    }

    /**
     * Recursively resolving class dependency.
     *
     * @param string $class The valid class name.
     * @return object
     */
    protected function circularDependencyResolver($class)
    {
        if (!is_string($class) && !class_exists($class)) {
            throw Internal\Exception\ReflectionExceptionFactory::invalidArgument(
                sprintf("Parameter 1 of %s must be a string of valid class name.", __METHOD__)
            );
        }

        $reflector = Internal\ReflectionClassFactory::create($class);

        if (!$this->hasConstructor($reflector)) {
            return $this->resolveInstanceWithoutConstructor($reflector);
        } else {
            $param = $this->getMethodParameters($reflector, '__construct');

            if (empty($param)) {
                return $reflector->newInstance();
            } else {
                foreach ($param as $key => $value) {
                    $class = $value->getClass();

                    if ($class instanceof \ReflectionClass) {
                        if ($class->isInterface()) {
                            $param[$key] = $this->getConcreteFromInterface($class->getName());
                        } else {
                            $param[$key] = $this->circularDependencyResolver($class->getName());
                        }
                    }
                }

                return $reflector->newInstanceArgs($param);
            }
        }
    }

    /**
     * Get concrete implementation from given abstract.
     *
     * @param string $abstract
     * @return \Closure|string|null
     */
    public function getConcrete($abstract)
    {
        return (isset($this->bindings[$abstract])
            ? $this->bindings[$abstract]['concrete']
            : null);
    }

    /**
     * Get concrete implementation from abstract.
     *
     * @param string $interface The interface name.
     * @return object
     */
    protected function getConcreteFromInterface($interface)
    {
        if (!$this->isAbstractExists($interface)) {
            throw Internal\Exception\ReflectionExceptionFactory::runtime(
                sprintf("%s has no concrete implementation in the class binding stack.", $interface)
            );
        }

        try {
            return $this->getResolvedSingleton($interface);
        } catch (\Exception $e) {
        }

        $concrete = $this->bindings[$interface]['concrete'];

        $object = $concrete instanceof \Closure ? $concrete($this) : $this->build($concrete);

        if ($this->isShared($interface)) {
            $this->markAsResolved($interface, $object, 'singleton');
        } else {
            $this->markAsResolved($interface, $object);
        }

        return $object;
    }

    /**
     * Determine if current reflection object has constructor.
     *
     * @param \ReflectionClass $refl The current reflection class object.
     * @return boolean
     */
    protected function hasConstructor(Internal\ReflectionClassFactory $refl)
    {
        return $refl->hasMethod('__construct');
    }

    /**
     * Determine if unresolvable class name has cloneable.
     *
     * @param \ReflectionClass $refl The current reflection class object.
     * @return boolean
     */
    protected function isCloneable(Internal\ReflectionClassFactory $refl)
    {
        return $refl->hasMethod('__clone');
    }

    /**
     * Determine if unresolvable class name has serializable.
     *
     * @param \ReflectionClass $refl The current reflection class object.
     * @return boolean
     */
    protected function isSerializable(Internal\ReflectionClassFactory $refl)
    {
        return $refl->hasMethod('__sleep');
    }

    /**
     * Resolving class name without constructor.
     *
     * @param \ReflectionClass $refl An instance of \ReflectionClass
     */
    protected function resolveInstanceWithoutConstructor(Internal\ReflectionClassFactory $refl)
    {
        return $refl->newInstanceWithoutConstructor();
    }

    /**
     * Get method parameters.
     *
     * @param \ReflectionClass $refl An reflection class instance.
     * @param string $method The method name.
     * @return array
     */
    protected function getMethodParameters(Internal\ReflectionClassFactory $refl, $method)
    {
        return ($refl->hasMethod($method) ? $refl->getMethod($method)->getParameters() : null);
    }

    /**
     * Mark resolved class name to true.
     *
     * @param string $abstract The resolved class name.
     * @param object $resolvedInstance The object instance of resolved abstract.
     * @param mixed $flag The concrete-resolving behavior.
     * @return void
     */
    protected function markAsResolved($abstract, $resolvedInstance, $flag = [])
    {
        if (!is_array($flag)) {
            $flag = array_slice(func_get_args(), 2);
        }

        if ($this->isAbstractExists($abstract)) {
            $this->resolved[$abstract] = [
                'concrete' => $resolvedInstance,
                'resolved' => true,
                'flag' => join('|', $flag)
            ];
        }
    }

    /**
     * Register binding into container stack.
     *
     * @param string $abstract The unresolvable class name.
     * @param \Closure|string $concrete Closure or class name being bound to the class name.
     */
    public function bind($abstract, $concrete = null, $shared = false)
    {
        if (is_null($concrete)) {
            $concrete = $abstract;
        }

        if (!($concrete instanceof \Closure)) {
            $concrete = $this->turnIntoResolvableClosure($abstract, $concrete);
        }

        $this->bindings[$abstract] = compact('concrete', 'shared');
    }

    /**
     * Register shared binding into container stack.
     *
     * @param string $abstract The unresolvable abstract
     * @param \Closure|string|null The concrete form of supplied abstract.
     */
    public function singleton($abstract, $concrete = null)
    {
        $this->bind($abstract, $concrete, true);
    }

    /**
     * Bind service into binding container stack if supplied class name
     * not being bound.
     *
     * @param string $abstract The unresolvable class name.
     * @param \Closure|string $concrete Closure or class name begin bound to the class name.
     */
    public function bindIf($abstract, $concrete)
    {
        if (!$this->isBound($abstract)) {
            $this->bind($abstract, $concrete);
        }
    }

    /**
     * Call defined instance.
     *
     * @param string $instance The class name to invoke/call.
     * @param array $args The class name __invoke method argument.
     * @return mixed|void
     */
    public function callInstance($instance, $args = [])
    {
        $args = (is_array($args) ? $args : array_slice(func_get_args(), 1));

        $current = $this->make($instance);

        return call_user_func_array($current, $args);
    }

    /**
     * Determine if class name has been bound or not.
     *
     * @param string $abstract The unresolvable class name.
     * @return bool
     */
    public function isBound($abstract)
    {
        return $this->isAbstractExists($abstract);
    }

    /**
     * Determine if a given type is shared.
     *
     * @param string $abstract
     * @return bool
     */
    public function isShared($abstract)
    {
        if (!isset($this->bindings[$abstract])) {
            throw Internal\Exception\ReflectionExceptionFactory::invalidArgument(
                sprintf("Parameter 1 of %s must be valid keys in binding container stack.", __METHOD__)
            );
        }

        return ($this->bindings[$abstract]['shared'] ? true : false);
    }

    /**
     * Turn class name into resolvable closure.
     *
     * @param string $abstract The class name
     * @param \Closure|string $concrete Can be instance of \Closure or class name.
     * @return \Closure
     */
    protected function turnIntoResolvableClosure($abstract, $concrete)
    {
        return function (Container $container, $parameters = []) use ($abstract, $concrete) {
            return ($abstract == $concrete ? $container->resolve($abstract)
                : $container->resolve($concrete, $parameters));
        };
    }
}


<?php

/*
 * This file is part of the Fuel Menu package.
 *
 * (c) Indigo Development Team
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Knp\Menu\Providers;

use League\Container\ServiceProvider;
use Knp\Menu;

/**
 * Provides menu services
 *
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
class FuelServiceProvider extends ServiceProvider
{
	/**
	 * @var array
	 */
	protected $provides = [
		'menu',
		'menu.factory',
		'menu.matcher',
		'menu.loader.array',
		'menu.provider',
		'menu.renderer_provider',
		'menu.renderer.list',
		'menu.renderer.fuel',
		'menu.twig.helper',
		'menu.twig.extension',
	];

	/**
	 * {@inheritdoc}
	 */
	public function register()
	{
		$this->container->add('menu', function($title = null, array $options = [])
		{
			$factory = $this->container->get('menu.factory');

			return $factory->createItem($title, $options);
		});

		$this->container->singleton('menu.factory', 'Knp\\Menu\\MenuFactory');
		$this->container->add('menu.matcher', 'Knp\\Menu\\Matcher\\Matcher');

		$this->container->add('menu.loader.array', 'Knp\\Menu\\Loader\\ArrayLoader')
			->withArgument('menu.factory');

		$this->container->add('menu.provider', function(array $menus = [])
		{
			$config = $this->container->get('configInstance', [false]);
			$config->load('menu', true);

			$menus = array_merge($config->get('menu.menus', []), $menus);

			return new Menu\Provider\FuelProvider($this->container, $menus);
		});

		$this->container->add('menu.renderer_provider', function(array $renderers = [], $default = null)
		{
			$config = $this->container->get('configInstance', [false]);
			$config->load('menu', true);

			$renderers = array_merge(
				['fuel' => 'menu.renderer.fuel', 'list' => 'menu.renderer.list'],
				$config->get('menu.renderers', []),
				$renderers
			);

			$default = $default ?: $config->get('menu.default_renderer');

			return new Menu\Renderer\FuelProvider($this->container, $renderers, $default);
		});

		$this->container->add('menu.renderer.list', 'Knp\\Menu\\Renderer\\ListRenderer')
			->withArgument('menu.matcher');

		$this->container->add('menu.renderer.fuel', function(array $defaultOptions = [])
		{
			$matcher = $this->container->get('menu.matcher');

			return new Menu\Renderer\FuelRenderer($matcher, $defaultOptions);
		});

		$this->container->add('menu.twig.helper', 'Knp\\Menu\\Twig\\Helper')
			->withArgument('menu.renderer_provider')
			->withArgument('menu.provider');

		$this->container->add('menu.twig.extension', 'Knp\\Menu\\Twig\\MenuExtension')
			->withArgument('menu.twig.helper');
	}
}


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

namespace cascade\components\dataInterface\connectors\file;

/**
 * SourceFileLine [[@doctodo class_description:cascade\components\dataInterface\connectors\file\SourceFileLine]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class SourceFileLine extends \canis\base\Object
{
    /**
     * @var [[@doctodo var_type:sourceFile]] [[@doctodo var_description:sourceFile]]
     */
    public $sourceFile;
    /**
     * @var [[@doctodo var_type:lineNumber]] [[@doctodo var_description:lineNumber]]
     */
    public $lineNumber;
    /**
     * @var [[@doctodo var_type:_content]] [[@doctodo var_description:_content]]
     */
    protected $_content;
    /**
     * @var [[@doctodo var_type:_id]] [[@doctodo var_description:_id]]
     */
    protected $_id;

    /**
     * Get content.
     *
     * @return [[@doctodo return_type:getContent]] [[@doctodo return_description:getContent]]
     */
    public function getContent()
    {
        if (!isset($this->_content)) {
            $this->_content = $this->sourceFile->readLine($this->lineNumber);
        }

        return $this->_content;
    }

    /**
     * Set content.
     *
     * @param [[@doctodo param_type:content]] $content [[@doctodo param_description:content]]
     */
    public function setContent($content)
    {
        $this->_content = $content;
    }

    /**
     * Get attributes.
     *
     * @return [[@doctodo return_type:getAttributes]] [[@doctodo return_description:getAttributes]]
     */
    public function getAttributes()
    {
        $attributes = [];
        foreach ($this->sourceFile->headers as $key => $header) {
            $attributes[$header] = isset($this->content[$key]) ? $this->content[$key] : null;
        }

        return $attributes;
    }

    /**
     * Get id.
     *
     * @return [[@doctodo return_type:getId]] [[@doctodo return_description:getId]]
     */
    public function getId()
    {
        if (!isset($this->_id)) {
            $this->_id = $this->generateId();
        }

        return $this->_id;
    }

    /**
     * [[@doctodo method_description:generateId]].
     *
     * @param [[@doctodo param_type:column]] $column [[@doctodo param_description:column]] [optional]
     *
     * @return [[@doctodo return_type:generateId]] [[@doctodo return_description:generateId]]
     */
    protected function generateId($column = null)
    {
        if (is_null($column)) {
            $column = $this->sourceFile->idColumn;
        }
        if (is_array($column)) {
            $id = [];
            foreach ($column as $subcolumn) {
                $id[] = $this->generateId($subcolumn);
            }

            return implode('.', $id);
        }
        if (isset($this->attributes[$column])) {
            return $this->attributes[$column];
        } else {
            return;
        }
    }

    /**
     * [[@doctodo method_description:clean]].
     */
    public function clean()
    {
        $this->content = null;
    }
}


<?php

/*
 * This File is part of the Thapp\Jmg\Http\Prs7 package
 *
 * (c) iwyg <mail@thomas-appel.com>
 *
 * For full copyright and license information, please refer to the LICENSE file
 * that was distributed with this package.
 */

namespace Thapp\Jmg\Http\Psr7;

use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\ResponseInterface;
use Thapp\Jmg\Resource\ImageResourceInterface as ResourceInterface;

/**
 * @class ImageResponse
 *
 * @package Thapp\Jmg\Http\Psr7
 * @version $Id$
 * @author iwyg <mail@thomas-appel.com>
 */
class ImageResponse implements ResponseInterface
{
    /** @var ResourceInterface */
    private $image;

    /** @var array */
    private $headers;

    /** @var int */
    private $status;

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

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

    /** @var ImageStream */
    private $stream;

    /** @var ImageStream */
    protected static $allowedHeaders = [
        'accept', 'accept-rages', 'date', 'keep-alive', 'connection', 'content-transfer-encoding',
        'etag', 'content-encoding', 'content-length', 'content-type', 'last-modified', 'cache-control'
    ];

    /**
     * Constructor.
     *
     * @param ImageResourceInterface $image
     * @param array $headers
     * @param string $version
     */
    public function __construct(ResourceInterface $image, array $headers = [], $version = '1.1')
    {
        $this->version = $version;
        $this->status  = 200;
        $this->reason  = 'Ok';
        $this->image   = $image;
        $this->setHeaders($this->filterHeaders($headers));
    }

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

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

    /**
     * {@inheritdoc}
     */
    public function withStatus($status, $reasonPhrase = '')
    {
        $response = clone $this;
        $response->status = $status;
        $response->reason = $reasonPhrase;

        return $response;
    }

    /**
     * {@inheritdoc}
     */
    public function getBody()
    {
        if ($this->usesXSendFile()) {
            return null;
        }

        return $this->getImageStream();
    }

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

    /**
     * {@inheritdoc}
     */
    public function withProtocolVersion($version)
    {
        $response = clone $this;
        $response->version = $version;

        return $response;
    }

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

    /**
     * {@inheritdoc}
     */
    public function hasHeader($name)
    {
        return isset($this->headers[strtolower($name)]);
    }

    /**
     * {@inheritdoc}
     */
    public function getHeader($name)
    {
        if (!$this->hasHeader($name)) {
            return [];
        }

        return $this->headers[strtolower($name)];
    }

    /**
     * {@inheritdoc}
     */
    public function getHeaderLine($name)
    {
        if (!$this->hasHeader($name)) {
            return '';
        }

        return implode(',', $this->getHeader($name));
    }

    /**
     * {@inheritdoc}
     */
    public function withHeader($name, $value)
    {
        $response = clone $this;

        if ($this->isAllowedHeader($name = strtolower($name))) {
            $response->headers[$name] = $this->getHeaderValue($value);
        }

        return $response;
    }

    /**
     * {@inheritdoc}
     */
    public function withAddedHeader($name, $value)
    {
        $response = clone $this;

        if ($this->isAllowedHeader($name = strtolower($name))) {
            $value = $this->getHeaderValue($value);
            $header = $this->getHeader($name);
            $response->headers[$name] = array_merge($header, $value);
        }

        return $response;
    }

    /**
     * {@inheritdoc}
     */
    public function withoutHeader($header)
    {
        $header = strtolower($header);
        $response = clone $this;
        $response->headers = array_filter($this->headers, function ($key) use ($header) {
            return $key !== $header;
        }, ARRAY_FILTER_USE_KEY);

        return $response;
    }

    /**
     * {@inheritdoc}
     */
    public function withBody(StreamInterface $body)
    {
        if (!$body instanceof ImageStream) {
            throw new \RuntimeException;
        }

        $response = clone $this;

        $response->image = null;
        $response->stream = $body;
        $response->headers = $this->removeXsendfileHeaders($this->headers);

        return $response;
    }

    /**
     * getDefaultHeader
     *
     * @return array
     */
    protected function getDefaultHeader()
    {
        return ['Content-Transfer-Encoding' => 'binary'];
    }

    /**
     * isSaneHeader
     *
     * @param string $key
     *
     * @return bool
     */
    protected function isAllowedHeader($key)
    {
        return in_array($key, static::$allowedHeaders);
    }

    /**
     * prepareHeaders
     *
     * @param array $headers
     *
     * @return array
     */
    protected function prepareHeaders(array $headers)
    {
        return array_merge($headers, $this->getDefaultHeader(), [
            'content-type'              => $this->image->getMimeType(),
            'accept-ranges'             => 'bytes',
            'keep-alive'                => 'timeout=15, max=200',
            'cache-control'             => 'public, must-revalidate',
            'connection'                => 'Keep-Alive',
        ]);
    }

    private function setHeaders(array $headers = [])
    {
        $this->headers = array_change_key_case(array_map(function ($value) {
            return $this->getHeaderValue($value);
        }, $this->prepareHeaders($headers)), CASE_LOWER);
    }

    /**
     * usesXSendFile
     *
     * @return bool
     */
    private function usesXSendFile()
    {
        return isset($this->headers['x-sendfile']) &&
            isset($this->headers['content-lenght']) &&
            isset($this->headers['content-disposition']);
    }

    /**
     * removeXsendfileHeaders
     *
     * @param array $headers
     *
     * @return array
     */
    private function removeXsendfileHeaders(array $headers)
    {
        $filter = ['x-sendfile', 'content-disposition'];
        return array_filter($headers, function ($key) use ($filter) {
            return !in_array($key, $filter);
        }, ARRAY_FILTER_USE_KEY);
    }

    /**
     * filterHeaders
     *
     * @param array $headers
     *
     * @return array
     */
    private function filterHeaders(array $headers)
    {
        return array_filter(array_change_key_case($headers), [$this, 'isAllowedHeader'], ARRAY_FILTER_USE_KEY);
    }

    /**
     * getHeaderValue
     *
     * @param mixed $value
     *
     * @return array
     */
    private function getHeaderValue($value)
    {
        return is_scalar($value) ? (array)$value : (is_array($value) ? $value : []);
    }

    /**
     * getImageStream
     *
     * @return Psr\Http\Message\StreamInterface
     */
    private function getImageStream()
    {
        return null !== $this->stream ? $this->stream :
            (null !== $this->image ? $this->stream = new ImageStream($this->image) : null);
    }
}


<?php

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

namespace ItePHP\Core;

/**
 * Snippet for validator
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class ValidatorSnippet {

	/**
	 * Execute validator
	 *
	 * @param Container $container
	 * @param string $validatorName
	 * @param mixed $value
	 * @return string
	 */
	public function validate(Container $container,$validatorName,$value){
		$validator=new $validatorName();
		return $container->getService('validator')->validate($validator,$value);
	}
}


<?php
namespace Clusterpoint\Query;

use Clusterpoint\Contracts\ScopeInterface;
/**
 *
 * Holds data for query exectuion.
 *
 * @category   Clusterpoint 4.0 PHP Client API
 * @package    clusterpoint/php-client-api-v4
 * @copyright  Copyright (c) 2016 Clusterpoint (http://www.clusterpoint.com)
 * @author     Marks Gerasimovs <marks.gerasimovs@clusterpoint.com>
 * @license    http://opensource.org/licenses/MIT    MIT
 */
class Scope implements ScopeInterface
{
    /**
     * Holds WHERE clause statements.
     *
     * @var array
     */
    public $where;

    /**
     * Holds SELECT clause statement.
     *
     * @var string
     */
    public $select;

     /**
     * Holds LIMIT statement.
     *
     * @var integer
     */
    public $limit;

     /**
     * Holds LIMIT statement.
     *
     * @var integer
     */
    public $offset;

     /**
     * Holds ORDER BY statement.
     *
     * @var string
     */
    public $orderBy;

     /**
     * Holds GROUP BY BY statement.
     *
     * @var string
     */
    public $groupBy;

     /**
     * Holds prepend for query.
     *
     * @var string
     */
    public $prepend;

    public $join;

    public $listWordsField;
    public $alternativesField;

    /**
     * Set Initial settings.
     *
     * @return void
     */
    public function __construct()
    {
        $this->resetSelf();
    }

    /**
     * Reset to default scope values settings.
     *
     * @return void
     */
    public function resetSelf()
    {
        $this->where = '';
        $this->select = '*';
        $this->limit = 20;
        $this->offset = 0;
        $this->orderBy = array();
        $this->groupBy = array();
        $this->prepend = '';
        $this->listWordsField = null;
        $this->alternativesField = null;
        $this->join = null;
    }
}


<?php
namespace DasRed\Translation\Logger;

use Zend\Log\Formatter\Base;
use Zend\Log\Exception;

class Formatter extends Base
{

	const DEFAULT_FORMAT = '[%timestamp%] %priorityName% (%priority%): %message% %trace% %extra% %parameters%';

	/**
	 * Format specifier for log messages
	 *
	 * @var string
	 */
	protected $format;

	/**
	 * Class constructor
	 *
	 * @see http://php.net/manual/en/function.date.php
	 * @param null|string $format Format specifier for log messages
	 * @param null|string $dateTimeFormat Format specifier for DateTime objects in event data
	 * @throws Exception\InvalidArgumentException
	 */
	public function __construct($format = null, $dateTimeFormat = null)
	{
		if ($format instanceof \Traversable)
		{
			$format = iterator_to_array($format);
		}

		if (is_array($format))
		{
			$dateTimeFormat = isset($format['dateTimeFormat']) ? $format['dateTimeFormat'] : null;
			$format = isset($format['format']) ? $format['format'] : null;
		}

		if (isset($format) && ! is_string($format))
		{
			throw new Exception\InvalidArgumentException('Format must be a string');
		}

		$this->format = isset($format) ? $format : static::DEFAULT_FORMAT;

		parent::__construct($dateTimeFormat);
	}

	/**
	 * Formats data into a single line to be written by the writer.
	 *
	 * @param array $event event data
	 * @return string formatted line to write to the log
	 */
	public function format($event)
	{
		$output = $this->format;

		if (array_key_exists('extra', $event) === true)
		{
			$this->formatExtra($event, $event['extra']);
			$event['message'] = 'Missing Key:';
		}
		else
		{
			$event['extra'] = [];
		}

		foreach ($event as $name => $value)
		{
			if (is_array($value) === true && count($value) === 0)
			{
				$value = '';
			}
			else
			{
				$value = $this->normalize($value);
			}

			$output = str_replace('%' . $name . '%', $value, $output);
		}

		return trim($output);
	}

	/**
	 *
	 * @param array $event
	 * @param array $extra
	 * @return self
	 */
	protected function formatExtra(array &$event, array &$extra)
	{
		// trace
		if (array_key_exists('trace', $extra) === true)
		{
			$event['trace'] = $this->formatTrace($extra['trace']);
			unset($extra['trace']);
		}

		// parameters
		if (array_key_exists('parameters', $extra) === true)
		{
			$event['parameters'] = $extra['parameters'];
			unset($extra['parameters']);
		}

		return $this;
	}

	/**
	 *
	 * @param array $trace
	 * @return string
	 */
	protected function formatTrace(array $trace)
	{
		$trace = array_filter($trace, function ($trace)
		{
			if (array_key_exists('file', $trace) === false || array_key_exists('line', $trace) === false)
			{
				return false;
			}

			$file = str_replace([
				'\\',
				'/'
			], '/', $trace['file']);
			if (strpos($file, 'dasred/translation/src/') !== false)
			{
				return false;
			}
			if (strpos($file, 'vendor/') !== false)
			{
				return false;
			}

			return true;
		});

		if (count($trace) == 0)
		{
			return '';
		}

		$first = array_shift($trace);

		return $first['file'] . '#' . $first['line'];
	}
}


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

namespace cascade\models;

use cascade\components\db\ActiveRecordTrait;
use Yii;

/**
 * Audit is the model class for table "audit".
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Audit extends \canis\db\models\Audit
{
    use ActiveRecordTrait;

    /**
     * [[@doctodo method_description:activityDataProvider]].
     *
     * @param array $dataProvider [[@doctodo param_description:dataProvider]] [optional]
     *
     * @return [[@doctodo return_type:activityDataProvider]] [[@doctodo return_description:activityDataProvider]]
     */
    public static function activityDataProvider($dataProvider = [])
    {
        $default = [
        ];
        $dataProvider = array_merge_recursive($default, $dataProvider);
        if (!isset($dataProvider['class'])) {
            $dataProvider['class'] = 'cascade\components\db\behaviors\auditable\AuditDataProvider';
        }

        $dataProvider['query'] = static::find();

        return Yii::createObject($dataProvider);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return array_merge(parent::rules(), [
            [['data_interface_id'], 'string', 'max' => 36],
        ]);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return array_merge(parent::attributeLabels(), [
            'data_interface_id' => 'Data Interface',
        ]);
    }

    /**
     * Get data interface.
     *
     * @return [[@doctodo return_type:getDataInterface]] [[@doctodo return_description:getDataInterface]]
     */
    public function getDataInterface()
    {
        return $this->hasOne(Yii::$app->classes['DataInterface'], ['id' => 'data_interface_id']);
    }
}


<?php
namespace Wambo\Catalog\Mapper;

use Wambo\Catalog\Exception\ContentException;
use Wambo\Catalog\Model\Content;

/**
 * Class ContentMapper creates \Wambo\Model\Content models from data bags with product content data.
 *
 * @package Wambo\Mapper
 */
class ContentMapper
{
    const FIELD_TITLE = "title";
    const FIELD_SUMMARY = "summary";
    const FIELD_DESCRIPTION = "description";

    /**
     * @var array $mandatoryFields A list of all mandatory fields of a Content
     */
    private $mandatoryFields = [self::FIELD_TITLE, self::FIELD_SUMMARY];

    /**
     * Creates a new ContentMapper instance
     */
    public function __construct()
    {
    }

    /**
     * Get a Content model from an array of unstructured product content data
     *
     * @param array $contentData An array containing content attributes
     *
     * @return Content
     *
     * @throws ContentException If a mandatory field is missing
     * @throws ContentException If the no Content could be created from the given product data
     */
    public function getContent(array $contentData)
    {
        // check if all mandatory fields are present
        foreach ($this->mandatoryFields as $mandatoryField) {
            if (!array_key_exists($mandatoryField, $contentData)) {
                throw new ContentException("The field '$mandatoryField' is missing in the given content data");
            }
        }

        // try to create a content model from the available data
        try {

            // title
            $title = "";
            if (isset($contentData[self::FIELD_TITLE])) {
                $title = $contentData[self::FIELD_TITLE];
            }

            // summary
            $summary = "";
            if (isset($contentData[self::FIELD_SUMMARY])) {
                $summary = $contentData[self::FIELD_SUMMARY];
            }

            // description
            $description = "";
            if (isset($contentData[self::FIELD_DESCRIPTION])) {
                $description = $contentData[self::FIELD_DESCRIPTION];
            }

            $content = new Content($title, $summary, $description);
            return $content;

        } catch (\Exception $contentException) {
            throw new ContentException(sprintf("Failed to create a content model from the given data: %s",
                $contentException->getMessage()), $contentException);
        }
    }
}


<?php

class SDIS62_Service_Generic_Response
{
    /**
     * @var Zend_Http_Response
     */
    protected $httpResponse;

    /**
     * @var array|stdClass
     */
    protected $jsonBody;

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

    /**
     * Constructeur
     *
     * Affecte la réponse HTTP à une propriété, ainsi que le body.
     * Il tente ensuite de déchiffrer le corps en tant que JSON.
     *
     * @param  Zend_Http_Response $httpResponse
     * @throws SDIS62_Service_Generic_Exception
     */
    public function __construct(Zend_Http_Response $httpResponse)
    {
        $this->httpResponse = $httpResponse;
        $this->rawBody = $httpResponse->getBody();

        try
        {
            $jsonBody = Zend_Json::decode($this->rawBody, Zend_Json::TYPE_OBJECT);
            $this->jsonBody = $jsonBody;
        }
        catch(Zend_Json_Exception $e)
        {
            throw new SDIS62_Service_Generic_Exception('impossible de décoder la réponse: ' . $e->getMessage(), 0, $e);
        }
    }

    /**
     * Récupération des propriétés de la réponse JSON
     *
     * @param  string $name
     * @return mixed
     */
    public function __get($name)
    {
        if (null === $this->getResponse())
        {
            return null;
        }

        if(!isset($this->getResponse()->{$name}))
        {
            return null;
        }

        return $this->getResponse()->{$name};
    }

    /**
     * La requête s'est bien déroulée ?
     *
     * @return bool
     */
    public function isSuccess()
    {
        return $this->jsonBody->status == 'success';
    }

    /**
     * Y'a t'il eu une erreur ?
     *
     * @return bool
     */
    public function isError()
    {
        return $this->jsonBody->status == 'failed';
    }

    /**
     * Récupération des erreurs
     *
     * Si la réponse s'est bien déroulée, alors un tableau vide est renvoyé
     *
     * @return array
     * @throws Exception\DomainException
     */
    public function getErrors()
    {
        if (!$this->isError())
        {
            return array();
        }

        if (null === $this->jsonBody || !isset($this->jsonBody->response))
        {
            throw new Zend_Service_Twitter_Exception('Soit aucune réponse JSON n\'a été reçue, soit le reçu JSON est malformé, dans tous les cas on ne peut afficher un message d\'erreur');
        }

        return $this->getResponse();
    }

    /**
     * Récupération des données brut de la réponse
     *
     * @return string
     */
    public function getRawResponse()
    {
        return $this->rawBody;
    }

    /**
     * Retourne uniquement le resultat json décodée du body
     *
     * @return array|stdClass
     */
    public function getResponse()
    {
        return $this->jsonBody->response;
    }
}


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

namespace cascade\components\web\widgets\base;

use Yii;

/**
 * CellBehavior [[@doctodo class_description:cascade\components\web\widgets\base\CellBehavior]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class CellBehavior extends \yii\base\Behavior
{
    /**
     * @var [[@doctodo var_type:gridCellClass]] [[@doctodo var_description:gridCellClass]]
     */
    public $gridCellClass = 'canis\web\grid\Cell';
    /**
     * @var [[@doctodo var_type:_gridCell]] [[@doctodo var_description:_gridCell]]
     */
    protected $_gridCell;

    /**
     * Get grid cell settings.
     *
     * @return [[@doctodo return_type:getGridCellSettings]] [[@doctodo return_description:getGridCellSettings]]
     */
    public function getGridCellSettings()
    {
        return [
            'columns' => 12,
            'maxColumns' => 12,
            'tabletSize' => false,
        ];
    }

    /**
     * Get cell.
     *
     * @return [[@doctodo return_type:getCell]] [[@doctodo return_description:getCell]]
     */
    public function getCell()
    {
        if (is_null($this->_gridCell)) {
            $gridCellClass = $this->owner->gridCellClass;
            $objectSettings = $this->owner->gridCellSettings;
            $objectSettings['class'] = $gridCellClass;
            $objectSettings['content'] = $this->owner->cellContent;
            $this->_gridCell = Yii::createObject($objectSettings);
        }

        return $this->_gridCell;
    }

    /**
     * Get cell content.
     *
     * @return [[@doctodo return_type:getCellContent]] [[@doctodo return_description:getCellContent]]
     */
    public function getCellContent()
    {
        return $this->owner;
    }
}


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

namespace RedKiteCms\Action\Block;

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

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

        $blockManager = $this->app["red_kite_cms.blocks_manager_factory"]->create('restore');
        $blockManager->restore(
            $this->app["red_kite_cms.configuration_handler"]->siteDir(),
            $restoreOptions,
            $username,
            $data['archiveFile']
        );
    }
}


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

use DateTime,
    IntlDateFormatter,
    Locale,
    Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    Zend\Validator\GreaterThan,
    Zend\Validator\LessThan,
    Zend\Validator\ValidatorChain,
    Zend\Validator\ValidatorInterface;

class BirthdayValidatorFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return ValidatorInterface
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $validatorChain = new ValidatorChain();

        $intl = new IntlDateFormatter(
            Locale::getDefault(),
            IntlDateFormatter::LONG,
            IntlDateFormatter::NONE
        );

        $date = (new DateTime('now'))->modify('-100 years');
        $validatorChain->attachByName('GreaterThan', [
            'messages' => [
                GreaterThan::NOT_GREATER_INCLUSIVE => 'The date of birth '
                    . 'must be not earlier than %min% inclusive',
            ],
            'messageVariables' => [
                'min' => ['abstractOptions' => 'fmt'],
            ],
            'min' => $date->format('Y-m-d'),
            'fmt' => $intl->format($date),
            'inclusive' => true,
        ], true);

        $date = (new DateTime('now'))->modify('-18 years');
        $validatorChain->attachByName('LessThan', [
            'messages' => [
                LessThan::NOT_LESS_INCLUSIVE => 'The date of birth '
                    . 'must be not later than %max% inclusive',
            ],
            'messageVariables' => [
                'max' => ['abstractOptions' => 'fmt'],
            ],
            'max' => $date->format('Y-m-d'),
            'fmt' => $intl->format($date),
            'inclusive' => true,
        ], true);

        return $validatorChain;
    }
}


<?php

/*
 * This file is part of the Meta Reader package.
 *
 * (c) Stephan Wentz <stephan@wentz.it>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Temp\MetaReader\Value;

/**
 * Value bag.
 *
 * @author Stephan Wentz <stephan@wentz.it>
 */
class ValueBag implements \Countable
{
    /**
     * @var ValueInterface[]
     */
    private $values = [];

    /**
     * @param array $values
     */
    public function __construct(array $values = [])
    {
        foreach ($values as $key => $value) {
            if (!$value instanceof ValueInterface) {
                $value = new MetaValue($value);
            }
            $this->set($key, $value);
        }
    }

    /**
     * @param string $key
     * @param string $defaultValue
     *
     * @return ValueInterface
     */
    public function get($key, $defaultValue = null)
    {
        if ($this->has($key)) {
            return $this->values[$key];
        }

        if ($defaultValue !== null) {
            return new MetaValue($defaultValue);
        }
    }

    /**
     * @param string         $key
     * @param ValueInterface $value
     *
     * @return $this
     */
    public function set($key, ValueInterface $value)
    {
        $this->values[$key] = $value;

        return $this;
    }

    /**
     * @param string $key
     *
     * @return $this
     */
    public function remove($key)
    {
        if ($this->has($key)) {
            unset($this->values[$key]);
        }

        return $this;
    }

    /**
     * @param string $key
     *
     * @return bool
     */
    public function has($key)
    {
        return isset($this->values[$key]);
    }

    /**
     * @return array
     */
    public function all()
    {
        return $this->values;
    }

    public function toArray()
    {
        $values = [];
        foreach ($this->all() as $key => $value) {
            $values[$key] = (string) $value;
        }

        return $values;
    }

    /**
     * @param ValueBag $attributes
     * @param bool     $override
     *
     * @return $this
     */
    public function merge(ValueBag $attributes, $override = false)
    {
        foreach ($attributes->all() as $key => $value) {
            if (!$this->has($key) || $override) {
                $this->set($key, $value);
            }
        }

        return $this;
    }

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


<?php

class SDIS62_View_Helper_Navigation_BootstrapBreadcrumbs extends Zend_View_Helper_Navigation_Breadcrumbs
{
    /**
     * Breadcrumbs separator string
     *
     * @var string
     */
    protected $_separator = '/';

    /**
     * Call helper
     *
     * @return SDIS62_View_Helper_Navigation_BootstrapBreadcrumbs
     */
    public function bootstrapBreadcrumbs()
    {
        return $this;
    }

    /**
     * Renders breadcrumbs based on bootstrap breadcrumbs
     *
     * @param  Zend_Navigation_Container $container  [optional] container to
     *                                               render. Default is to
     *                                               render the container
     *                                               registered in the helper.
     * @return string                                helper output
     */
    public function renderStraight(Zend_Navigation_Container $container = null)
    {
        if ($container === null)
        {
            $container = $this->getContainer();
        }

        // find deepest active
        if (!$active = $this->findActive($container))
        {
            return '';
        }

        $active = $active['page'];

        // put the deepest active page last in breadcrumbs
        if ($this->getLinkLast())
        {
            $html = '
' . $this->htmlify($active) . '
';
        }
        else
        {
            $html = $active->getLabel();

            if ($this->getUseTranslator() && $t = $this->getTranslator())
            {
                $html = $t->translate($html);
            }

            $html = '
' . $this->view->escape($html) . '
';
        }

        // walk back to root
        while (($parent = $active->getParent()) != null)
        {
            if ($parent instanceof Zend_Navigation_Page)
            {
                // prepend crumb to html
                $html = '
' . $this->htmlify($parent) . ' ' .
                    $this->getSeparator() . '
' . PHP_EOL . $html;
            }

            if ($parent === $container)
            {
                // at the root of the given container
                break;
            }

            $active = $parent;
        }

        return strlen($html) ? $this->getIndent() . '
' . $html .  '
' : '';
    }
}


<?php
namespace eMacros\Runtime\Type;

use eMacros\Runtime\GenericFunction;

class IsA extends GenericFunction {
	/**
	 * Determines if a given value is an instance of a specified class
	 * Usage: (is-a "ArrayObject" _value)
	 * Returns: boolean
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
	public function execute(array $arguments) {
		if (empty($arguments)) throw new \BadFunctionCallException("IsA: No parameters found.");
		if (!array_key_exists(1, $arguments)) throw new \BadFunctionCallException("IsA: No classname has been specified.");
		if (!is_string($arguments[1]))
			throw new \InvalidArgumentException(sprintf("IsA: Expected a value of type string as second argument, %s found instead.", gettype($arguments[1])));
		if (!is_object($arguments[0])) return false;
		return is_a($arguments[0], $arguments[1]);
	}
}
?>


<?php

namespace cascade\controllers\admin;

use canis\web\Controller;
use Yii;
use yii\filters\AccessControl;

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

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

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

    /**
     * [[@doctodo method_description:actionTasks]].
     *
     * @return [[@doctodo return_type:actionTasks]] [[@doctodo return_description:actionTasks]]
     */
    public function actionTasks()
    {
        $tasks = $this->params['tasks'] = $this->getTasks();
        if (isset($_GET['task'])) {
            Yii::$app->response->task = 'message';
            if (isset($tasks[$_GET['task']])) {
                $tasks[$_GET['task']]['run']();
            } else {
                Yii::$app->response->content = 'Unknown task!';
                Yii::$app->response->taskOptions = ['state' => 'danger'];
            }

            return;
        }

        Yii::$app->response->view = 'tasks';
    }

    /**
     * Get tasks.
     *
     * @return [[@doctodo return_type:getTasks]] [[@doctodo return_description:getTasks]]
     */
    protected function getTasks()
    {
        $tasks = [];
        $tasks['flush-file-cache'] = [];
        $tasks['flush-file-cache']['title'] = 'Flush File Cache';
        $tasks['flush-file-cache']['description'] = 'Clear the file cache in Cascade';
        $tasks['flush-file-cache']['run'] = function () {
            Yii::$app->fileCache->flush();
            Yii::$app->response->content = 'File cache was flushed!';
            Yii::$app->response->taskOptions = ['state' => 'success', 'title' => 'Success'];
        };

        $tasks['flush-cache'] = [];
        $tasks['flush-cache']['title'] = 'Flush Memory Cache';
        $tasks['flush-cache']['description'] = 'Clear the memory cache in Cascade';
        $tasks['flush-cache']['run'] = function () {
            Yii::$app->cache->flush();
            Yii::$app->response->content = 'Memory cache was flushed!';
            Yii::$app->response->taskOptions = ['state' => 'success', 'title' => 'Success'];
        };

        return $tasks;
    }
}


<?php

namespace bariew\eventModule\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;

/**
 * ItemSearch represents the model behind the search form about `bariew\eventModule\models\Item`.
 */
class ItemSearch extends Item
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['trigger_class', 'trigger_event', 'handler_class', 'handler_method'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Item::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        $dataProvider->sort->defaultOrder = [
            'trigger_class'=>SORT_ASC, 'trigger_event'=>SORT_ASC, 'handler_class'=>SORT_ASC, 'handler_method'=>SORT_ASC
        ];
        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
        ]);

        $query->andFilterWhere(['like', 'trigger_class', $this->trigger_class])
            ->andFilterWhere(['like', 'trigger_event', $this->trigger_event])
            ->andFilterWhere(['like', 'handler_class', $this->handler_class])
            ->andFilterWhere(['like', 'handler_method', $this->handler_method]);

        return $dataProvider;
    }
}


<?php
	/**
	 * Created by IntelliJ IDEA.
	 * User: Gabriel Peleskei
	 * Date: 25.11.2018
	 */

	namespace GabrielPeleskei\InterruptHandler;

	use Closure;
	use function in_array;
	use InvalidArgumentException;
	use function pcntl_signal;
	use const SIG_DFL;
	use const SIGHUP;
	use const SIGINT;
	use const SIGUSR1;

	/**
	 * Class Handler
	 * @package GabrielPeleskei\InterruptHandler
	 *
	 * Singleton implementation
	 * @see Handler::getInstance()
	 * @example ../examples/basic.php
	 */
	class Handler {
		static public $signalNames = [
			'SIG_DFL',
			'SIGHUP',
			'SIGINT',
			'SIGQUIT',
			'SIGILL',
			'SIGTRAP',
			'SIGABRT',
			'SIGIOT',
			'SIGBUS',
			'SIGFPE',
			'SIGKILL',
			'SIGUSR1',
			'SIGSEGV',
			'SIGUSR2',
			'SIGPIPE',
			'SIGALRM',
			'SIGTERM',
			'SIGSTKFLT',
			'SIGCLD',
			'SIGCHLD',
			'SIGCONT',
			'SIGSTOP',
			'SIGTSTP',
			'SIGTTIN',
			'SIGTTOU',
			'SIGURG',
			'SIGXCPU',
			'SIGXFSZ',
			'SIGVTALRM',
			'SIGPROF',
			'SIGWINCH',
			'SIGPOLL',
			'SIGIO',
			'SIGPWR',
			'SIGSYS',
			'SIGBABY'
		];
		/**
		 * @var Handler
		 */
		protected static $_instance;

		/**
		 * @var array Listener class hash by signal
		 */
		protected $_bySignal = [];
		/**
		 * @var array Listener class hash bei register id
		 */
		protected $_byId = [];
		/**
		 * @var array list of signals registered to pcntl
		 */
		protected $_signals = [
			SIGINT,
			SIGHUP,
			SIGUSR1,
			SIGTERM
		];

		/**
		 * Handler constructor.
		 * starts the interrupt handler
		 * @uses Handler::_start()
		 */
		protected function __construct() {
			$this->_start();
			static::$_instance = $this;
		}

		/**
		 * @param array|null $supportedSignals
		 * @return static
		 */
		public static function getInstance(array $supportedSignals = null) {
			$instance = self::$_instance ?: new static();
			if (null !== $supportedSignals) {
				$instance->setSignalsArray($supportedSignals);
			}
			return $instance;
		}

		/**
		 * Resets interrupt handlers to default...
		 * @uses pcntl_signal()
		 */
		protected function _reset() {
			declare(ticks=1);
			foreach ($this->_signals as $signal) {
				pcntl_signal($signal,SIG_DFL);
			}
		}

		/**
		 * @param array ...$signals
		 * @uses Handler::setSignalsArray()
		 */
		public function setSignals(...$signals) {
			$this->setSignalsArray($signals);
		}

		/**
		 * @return array of usable signals
		 */
		public function listSignals() {
			return $this->_signals;
		}

		/**
		 * @param array $signals
		 * @uses Handler::_reset()
		 * @uses Handler::_start()
		 */
		public function setSignalsArray(array $signals) {
			$this->_reset();
			$this->_signals = $signals;
			$this->_start();
		}

		/**
		 * Signal handler for all registrations.
		 *
		 * @param $signal
		 * @return int
		 */
		public function handle($signal) {
			if (isset($this->_bySignal[$signal])) {
				/** @var Listener $reg */
				foreach ($this->_bySignal[$signal] as $reg) {
					$reg->interrupt = $signal;
				}
			} else {
				return SIG_DFL;
			}
		}

		/**
		 * registeres the interrupt handler
		 * @uses pcntl_signal()
		 */
		protected function _start() {
			declare(ticks=1);
			foreach ($this->_signals as $signal) {
				pcntl_signal($signal, [$this, 'handle']);
			}
		}

		/**
		 * @param int $sig
		 * @return string|int mixed the number if no string is found
		 */
		public static function getSignalName($sig) {
			return isset(static::$signalNames[$sig]) ? static::$signalNames[$sig] : $sig;
		}

		/**
		 * Registers a new Interrupt Listener
		 *
		 * @param array $signals
		 * @param null|Callable|Closure|array $callableArray
		 *
		 * @return Listener
		 *
		 * @uses Listener::setNotification()
		 *
		 * @throws \InvalidArgumentException if signal ist not supported by Handler, code is the requested signal
		 *
		 * @example ../examples/basic.php
		 */
		public function register(array $signals, $callableArray = null) {
			foreach ($signals as $signal) {
				if (!in_array($signal, $this->_signals, true)) {
					$signalName = static::getSignalName($signal);
					throw new InvalidArgumentException("Signal [{$signalName}] is not supported. Use setSignals() to add support.", $signal);
				}
			}
			$reg = new Listener($signals);
			$reg->setNotification($callableArray);
			$this->_byId[$reg->id] = $reg;
			foreach ($signals as $signal) {
				$this->_bySignal[$signal][$reg->id] = $reg;
			}
			return $reg;
		}

		/**
		 * Clears the hash list of Listener
		 * @param Listener $register
		 * @return bool true if removed
		 */
		public function unregister(Listener $register) {
			$id = $register->id;
			$success = false;
			if (isset($this->_byId[$id])) {
				unset($this->_byId[$id]);
				$success = true;
			}
			foreach ($this->_bySignal as $signal => $reg) {
				if (isset($reg[$id])) {
					unset($this->_bySignal[$signal][$id]);
				}
			}
			return $success;
		}

		/**
		 * Unsets static singleton holder
		 * @uses Handler::_reset()
		 */
		public function cleanup() {
			$this->_reset();
			static::$_instance = null;
		}

		/**
		 * @return string
		 */
		public function __toString() {
			$sigs = array_map(function($sig){
				return static::getSignalName($sig) . "-$sig";
			}, $this->_signals);
			$sigs = implode(', ',$sigs);
			$listeners = count($this->_byId);
			return __CLASS__ . " ($listeners) [$sigs]";
		}
	}


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

use CmsCommon\Form\Form,
    Zend\Form\ElementInterface;

class ResetPassword extends Form
{
    /**
     * @var ElementInterface
     */
    protected $identityElement;

    /**
     * __construct
     *
     * @property string $name
     * @property array $options
     */
    public function __construct($name = null, $options = [])
    {
        parent::__construct($name ?: 'reset-password', $options);

        // Setting some defaults
        if (null === $this->getLabel()) {
            $this->setLabel('Resetting Password');
        }
    }

    /**
     * {@inheritDoc}
     */
    public function init()
    {
        parent::init();

        $this->identityElement = $this->getFormFactory()->getFormElementManager()->get('CmsAuthenticationIdentity');

        $this->add(
            $this->identityElement,
            ['priority' => 20]
        );

        $this->add(
            ['type'  => 'CmsUserBirthdayVerify'],
            ['priority' => 10]
        );

        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this);
    }

    /**
     * {@inheritDoc}
     */
    public function has($elementOrFieldset)
    {
        if (parent::has($elementOrFieldset)) {
            return true;
        }

        if ($elementOrFieldset === 'identity' && $this->identityElement) {
            $elementOrFieldset = $this->identityElement->getName();
        } else {
            return false;
        }

        return parent::has($elementOrFieldset);
    }

    /**
     * {@inheritDoc}
     */
    public function get($elementOrFieldset)
    {
        if (!parent::has($elementOrFieldset)
            && $elementOrFieldset === 'identity'
            && $this->identityElement
        ) {
            $elementOrFieldset = $this->identityElement->getName();
        }

        return parent::get($elementOrFieldset);
    }

    /**
     * {@inheritDoc}
     */
    public function remove($elementOrFieldset)
    {
        if (!parent::has($elementOrFieldset)
            && $elementOrFieldset === 'identity'
            && $this->identityElement
        ) {
            $elementOrFieldset = $this->identityElement->getName();
        }

        return parent::remove($elementOrFieldset);
    }
}


<?php
namespace Lab123\Odin\Command;

use Illuminate\Console\Command;

class LumenRouteList extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'route:list';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Display all registered routes.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        global $app;

        $routeCollection = $app->getRoutes();
        $rows = array();
        foreach ($routeCollection as $route) {
            $rows[] = [
                'verb' => $route['method'],
                'path' => $route['uri'],
                'namedRoute' => $this->getNamedRoute($route['action']),
                'controller' => $this->getController($route['action']),
                'action' => $this->getAction($route['action']),
                'middleware' => $this->getMiddleware($route['action'])
            ];
        }

        $headers = array(
            'Verb',
            'Path',
            'NamedRoute',
            'Controller',
            'Action',
            'Middleware'
        );
        $this->table($headers, $rows);
    }

    /**
     *
     * @param array $action
     * @return string
     */
    protected function getNamedRoute(array $action)
    {
        return (! isset($action['as'])) ? "" : $action['as'];
    }

    /**
     *
     * @param array $action
     * @return mixed|string
     */
    protected function getController(array $action)
    {
        if (empty($action['uses'])) {
            return 'None';
        }

        return current(explode("@", $action['uses']));
    }

    /**
     *
     * @param array $action
     * @return string
     */
    protected function getAction(array $action)
    {
        if (! empty($action['uses'])) {
            $data = $action['uses'];
            if (($pos = strpos($data, "@")) !== false) {
                return substr($data, $pos + 1);
            } else {
                return "METHOD NOT FOUND";
            }
        } else {
            return 'Closure';
        }
    }

    /**
     *
     * @param array $action
     * @return string
     */
    protected function getMiddleware(array $action)
    {
        return (isset($action['middleware'])) ? (is_array($action['middleware'])) ? join(", ", $action['middleware']) : $action['middleware'] : '';
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Helper;

use OpenOrchestra\ModelInterface\Helper\SuppressSpecialCharacterHelperInterface;

/**
 * Class SuppressSpecialCharacterHelper
 */
class SuppressSpecialCharacterHelper implements SuppressSpecialCharacterHelperInterface
{
    /**
     * @param string $input
     * @param array  $authorizeSpecial
     *
     * @return string
     */
    public function transform($input, $authorizeSpecial = array())
    {
        $element = trim($input);
        $element = str_replace(' ', '_', $element);
        $element = htmlentities($element, ENT_NOQUOTES, 'UTF-8');
        $accents = '/&([A-Za-z]{1,2})(grave|acute|circ|cedil|uml|lig|tilde);/';
        $element = preg_replace($accents, '$1', $element);
        $authorizeSpecial = join('',$authorizeSpecial);
        $element = preg_replace('/[^-a-z_A-Z0-9'.$authorizeSpecial.']+/', '', $element);

        return strtolower($element);
    }
}


<?php namespace Versatile\Introspection;

use UnexpectedValueException;
use Illuminate\Translation\Translator;
use Versatile\Introspection\Contracts\TitleIntrospector;
use Versatile\Introspection\Contracts\PathIntrospector;
use Versatile\Query\Contracts\SyntaxParser;

class EloquentTitleIntrospector implements TitleIntrospector
{

    public $baseLangKey = 'models';

    protected $translator;

    protected $pathIntrospector;

    protected $syntaxParser;

    protected $manualKeyTitles = [];

    protected $manualObjectTitles = [];

    protected $namespaces = [];

    protected $modelToLangName = [];

    public function __construct(Translator $translator,
                                PathIntrospector $introspector,
                                SyntaxParser $parser)
    {
        $this->translator = $translator;
        $this->pathIntrospector = $introspector;
        $this->parser = $parser;
    }

    /**
     * {@inheritdoc}
     *
     * @param string|object $class The class or an object of it
     * @param string $key A key name. Can be dotted like address.street.name
     * @return string The readable title
     **/
    public function keyTitle($class, $path)
    {

        // Allows manual overwrites if titles
        if ($title = $this->getManualKeyTitle($this->getClassName($class),$path)) {
            return $title;
        }

        try{

            // First check if path is a related key (account.owner.id)
            if ($this->parser->isRelatedKey($path)) {

                list($join, $key) = $this->parser->toJoinAndKey($path);
                $className = $this->pathIntrospector->classOfPath($class, $join);

            } else { // No related key

                $className = $this->getClassName($class);
                $key = $path;

            }

            if ($title = $this->getManualKeyTitle($className, $key)) {
                return $title;
            }

            $langKey = $this->key2QualifiedLangKey($className, $key);
            $title = $this->translator->get($langKey);

            // If a translation was found return it
            if($title != $langKey){
                return $title;
            }

        }
        catch(UnexpectedValueException $e){
            return $path;
        }

        // If no translation was found try to return an object title
        // (e.g. $class=User, $key=address if address is an object
        try{
            return $this->objectTitle($this->pathIntrospector->classOfPath($class, $path));
        }
        catch(UnexpectedValueException $e){
            return $path;
        }

        return $title;
    }

    /**
     * {@inheritdoc}
     *
     * @param string|object $class The class or an object of it
     * @param int $quantity (optional) The quantity (for singular/plural)
     * @return string A readable title of this object
     **/
    public function objectTitle($class, $quantity=1)
    {
        return $this->translator->choice(
            $this->langKeyPrefix($this->getClassName($class)).".name",
            $quantity
        );
    }

    /**
     * {@inheritdoc}
     *
     * @param string|object $class The class or an object of it
     * @param string $path A key name. Can be dotted like address.street.name
     * @param string An enum value. Preferable strings to allow easy translations
     * @return string A readable title of this enum value
     **/
    public function enumTitle($class, $path, $value)
    {
        return $this->translator->get(
            $this->langKeyPrefix($class).".enums.$path.$value"
        );
    }

    /**
     * Returns the langClassName of $modelName
     *
     * @param string $modelName
     * @return string
     **/
    public function model2LangKey($modelName)
    {
        if (!is_string($modelName)) {
            $modelDisplay = is_object($modelName) ? get_class($modelName) : gettype($modelName);
            throw new \UnexpectedValueException("modelName has to be string not $modelDisplay");
        }

        if (isset($this->modelToLangName[$modelName])) {
            return $this->modelToLangName[$modelName];
        }

        $matches = [];

        if (preg_match('@\\\\([\w]+)$@', $modelName, $matches)) {
            $modelName = $matches[1];
        }

        return snake_case($modelName);
    }

    /**
     * Returns the translation key for the keyTitle translation
     *
     * @param string $className
     * @param string $key
     * @return string
     **/
    public function key2QualifiedLangKey($className, $key)
    {
        return $this->langKeyPrefix($className) . ".fields.$key";
    }

    /**
     * Returns the manually setted objectTitle
     * @see self::setObjectTitle
     *
     * @param string $class
     * @param int $quantity
     * @return string|null
     **/
    public function getManualObjectTitle($class, $quantity=1)
    {
        if(isset($this->manualObjectTitles[$class])) {
            return $this->manualObjectTitles[$class];
        }
    }

    /**
     * Set a manual object title. Bypasses all internal handling. You have to
     * handle translations yourself
     *
     * @param string $class
     * @param string $title
     * @param int $quantity (optional)
     * @return self
     **/
    public function setObjectTitle($class, $title, $quantity=1)
    {
        $this->manualObjectTitles[$class] = $title;
        return $this;
    }

    /**
     * Return a manually overwritten title for $class->$column
     *
     * @param string $class
     * @param string $column
     * @return string
     **/
    public function getManualKeyTitle($class, $column)
    {

        $class = ltrim($this->getClassName($class),'\\');
        if(isset($this->manualKeyTitles[$class.'|'.$column])){
            return $this->manualKeyTitles[$class.'|'.$column];
        }
    }

    /**
     * Set a manual key title. Overwrites the translated titles, so you have to
     * handle translation yourself
     *
     * @param string|object $class
     * @param string $column
     * @param string $title
     * @return self
     **/
    public function setKeyTitle($class, $column, $title)
    {

        $class = ltrim($this->getClassName($class),'\\');
        $this->manualKeyTitles[$class.'|'.$column] = $title;
        return $this;

    }

    /**
     * Return the namespace for class with $langClassName
     * @see self::setLangNameSpace
     *
     * @param string
     * @return string
     **/
    public function getLangNamespace($langClassName)
    {
        return isset($this->namespaces[$langClassName]) ? $this->namespaces[$langClassName] : '';
    }

    /**
     * Set a namespace for a _langClassName_. So you can prefix project with
     * your project package prefix. setLangNameSpace('project', 'projects')
     * The resulting key will be "projects::project.models"
     *
     * @param string $langClassName
     * @param string $namespace (Without colons)
     * @return self
     **/
    public function setLangNameSpace($langClassName, $namespace)
    {
        $this->namespaces[$langClassName] = $namespace;
        return $this;
    }

    /**
     * Manually map a class to a model name. This is needed if you overwrite
     * a class like User to ExtendedUser. So instead of copying your lang entry
     * for extended_user you can map App\ExtendedUser to user
     *
     * @param string $modelName The classname you want to map
     * @param string $langName The name of that class inside lang files
     * @return void
     **/
    public function mapModelToLangName($modelName, $langName)
    {
        $modelName = $this->getClassName($modelName);
        $this->modelToLangName[$modelName] = $langName;
    }

    /**
     * Return the complete prefix for $className ($namespace.$baseLangKey.$langClass)
     *
     * @param string $className
     * @return string
     **/
    protected function langKeyPrefix($className)
    {

        $langClass = $this->model2LangKey($className);

        if ($namespace = $this->getLangNamespace($langClass)) {
            return "$namespace::{$this->baseLangKey}.$langClass";
        }

        return "{$this->baseLangKey}.$langClass";
    }

    /**
     * Returns the passed value if it is not an object and the class if an
     * object was passed
     *
     * @param object|string $class
     * @return string The classname
     **/
    protected function getClassName($class)
    {
        if(is_object($class)){
            return get_class($class);
        }
        else{
            return $class;
        }
    }

}


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

namespace RedKiteCms\Content\Block;

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\Exclude;
use RedKiteCms\Exception\General\LogicException;
use RedKiteCms\Bridge\Translation\Translator;

/**
 * Class BaseBlock is the object assigned to define a base block class. Every time you need to create a new
 * Block you must derive it from this base class
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Block
 */
abstract class BaseBlock
{
    /**
     * @Type("string")
     */
    protected $slotName;

    /**
     * @Type("string")
     */
    protected $name = "";

    /**
     * @Type("string")
     */
    protected $type;

    /**
     * @Exclude
     */
    protected $translator;

    /**
     * @Type("string")
     */
    protected $customTag = null;

    /**
     * @Type("string")
     */
    protected $historyName = "";

    /**
     * @Type("array")
     */
    protected $history = array();

    /**
     * @Type("integer")
     */
    protected $revision = 0;

    /**
     * @Exclude
     */
    protected $internal = false;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->translate();
    }

    /**
     * Translates the block
     */
    protected function translate()
    {
        $translatorOptions = $this->getTranslatorOptions();
        if (empty($translatorOptions) && !array_key_exists("fields", $translatorOptions)) {
            return;
        }

        $params = array();
        if (array_key_exists("params", $translatorOptions)) {
            $params = $translatorOptions["params"];
        }

        $domain = "RedKiteCms";
        if (array_key_exists("domain", $translatorOptions)) {
            $domain = $translatorOptions["domain"];
        }

        foreach ($translatorOptions["fields"] as $field) {
            $field = ucfirst($field);
            $method = 'get' . $field;
            $value = Translator::translate($this->$method(), $params, $domain);
            $method = 'set' . $field;
            $this->$method($value);
        }
    }

    /**
     * Override this method to define the options to set up the translator.
     * Valid options can be domain and fields.
     *
     * The domain is the Symfony2 message domain where the block translation live
     * while fields is an array of fields which will be translated by the translator
     *
     * @return array
     * @codeCoverageIgnore
     */
    protected function getTranslatorOptions()
    {
        return array();
    }

    /**
     * @return mixed
     */
    public function getSlotName()
    {
        return $this->slotName;
    }

    /**
     * @param $slotName
     */
    public function setSlotName($slotName)
    {
        $this->slotName = $slotName;
    }

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

    /**
     * @param $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getType()
    {
        if (null === $this->type) {
            throw new LogicException(
                'A derived class must always define the block type. Please define a protected property $type to set up the block type.'
            );
        }

        return $this->type;
    }

    /**
     * @return null
     */
    public function getCustomTag()
    {
        if (null === $this->customTag) {
            throw new LogicException(
                'A derived class must always define the block custom tag property. Please define a protected property $customTag to set up the custom tag which will be used to render your block.'
            );
        }

        return $this->customTag;
    }

    /**
     * @return array
     */
    public function getHistory()
    {
        return $this->history;
    }

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

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

    /**
     * @param $historyName
     */
    public function setHistoryName($historyName)
    {
        $this->historyName = $historyName;
    }

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