<?php

namespace Mouf\Doctrine\ORM\Admin\Controllers;

use Mouf\Composer\ClassNameMapper;
use Mouf\Console\ConsoleUtils;
use Mouf\Html\Widgets\MessageService\Service\UserMessageInterface;
use Mouf\MoufUtils;
use Mouf\InstanceProxy;
use Mouf\Actions\InstallUtils;
use Mouf\MoufManager;
use Mouf\Mvc\Splash\Controllers\Controller;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOException;
use Mouf\Database\Patcher\DatabasePatchInstaller;

/**
 * The controller managing the install process.
 * It will query the database details.
 */
class EntityManagerController extends Controller
{
    public $selfedit;

    /**
     * The active MoufManager to be edited/viewed.
     *
     * @var MoufManager
     */
    public $moufManager;

    /**
     * The template used by the main page for mouf.
     *
     * @Property
     * @Compulsory
     *
     * @var TemplateInterface
     */
    public $template;

    /**
     * The content block the template will be writting into.
     *
     * @Property
     * @Compulsory
     *
     * @var HtmlBlock
     */
    public $contentBlock;

    protected $entitiesNamespace;
    protected $proxyNamespace;
    protected $daoNamespace;
    protected $psrMode;
    protected $instanceName;
    protected $patchable;
    protected $nbAwaitingPatches;
    protected $generatePatch = true;

    protected $errors = array();

    /**
     * Displays the first install screen.
     *
     * @Action
     * @Logged
     *
     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
     */
    public function defaultAction($name = null, $selfedit = 'false', $installMode = null)
    {
        $this->selfedit = $selfedit;
        $this->installMode = $installMode;
        $name = $name ? $name : 'entityManager';

        $this->instanceName = $name;

        if ($selfedit == 'true') {
            $this->moufManager = MoufManager::getMoufManager();
        } else {
            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
        }

        $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../composer.json');
        $managedNamespaces = $classNameMapper->getManagedNamespaces();

        $this->autoloadDetected = true;
        if ($this->moufManager->instanceExists($name)) {
            $instance = $this->moufManager->getInstanceDescriptor($name);
            $this->entitiesNamespace = $instance->getSetterProperty('setEntitiesNamespace')->getValue();
            $this->proxyNamespace = $instance->getSetterProperty('setProxyNamespace')->getValue();
            $this->daoNamespace = $instance->getSetterProperty('setDaoNamespace')->getValue();
        } else {
            if ($managedNamespaces) {
                $rootNamespace = $classNameMapper->getManagedNamespaces()[0];
                $this->entitiesNamespace = $rootNamespace."Model\\Entities";
                $this->proxyNamespace = $rootNamespace."Model\\Proxies";
                $this->daoNamespace = $rootNamespace."Model\\DAOs";
            } else {
                $this->autoloadDetected = false;
                $this->entitiesPath = 'src/path_to_entities';
                $this->proxyDir = 'src/path_to_proxies';
                $this->proxyNamespace = "YOUR_APP_NAMESPACE\\PATH\\TO\\PROXIES";
            }
        }

        $this->contentBlock->addFile(__DIR__.'/../views/install.php', $this);
        $this->template->toHtml();
    }

    /**
     * Displays the "schema generation screen".
     *
     * @Action
     * @Logged
     *
     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
     */
    public function do_generate_daos($entitiesNamespace, $proxyNamespace, $daoNamespace, $instanceName, $selfedit, $installMode = null)
    {
        $this->instanceName = $instanceName;
        $this->selfedit = $selfedit;
        $this->installMode = $installMode;

        if ($selfedit == 'true') {
            $this->moufManager = MoufManager::getMoufManager();
        } else {
            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
        }

        $dbalConnection = $this->moufManager->getInstanceDescriptor('dbalConnection');
        $eventManager = $dbalConnection->getProperty('eventManager')->getValue();

        if (!$this->moufManager->instanceExists($instanceName)) {
            $em = $this->moufManager->createInstance("Mouf\\Doctrine\\ORM\\MoufResetableEntityManager");
            $em->setName($instanceName);

            $quoteStrategy = $this->moufManager->createInstance("Mouf\\Doctrine\\ORM\\Mapping\\EscapingQuoteStrategy");
            $quoteStrategy->setName('escapingQuoteStrategy');

            $namingStrategy = $this->moufManager->createInstance("Doctrine\\ORM\\Mapping\\UnderscoreNamingStrategy");
            $namingStrategy->setName('underscoreNamingStrategy');

            $doctrineApc = $this->moufManager->getInstanceDescriptor('defaultDoctrineCache');

            $config = $this->moufManager->createInstance("Doctrine\\ORM\\Configuration");
            $config->setName('doctrineConfiguration');

            $configQuoteProperty = $config->getSetterProperty('setQuoteStrategy');
            $configQuoteProperty->setValue($quoteStrategy);

            $configNamingProperty = $config->getSetterProperty('setNamingStrategy');
            $configNamingProperty->setValue($namingStrategy);

            $configQueryCacheProperty = $config->getSetterProperty('setQueryCacheImpl');
            $configQueryCacheProperty->setValue($doctrineApc);

            $configMetadataCacheProperty = $config->getSetterProperty('setMetadataCacheImpl');
            $configMetadataCacheProperty->setValue($doctrineApc);

            $configResultCacheProperty = $config->getSetterProperty('setResultCacheImpl');
            $configResultCacheProperty->setValue($doctrineApc);
        } else {
            $em = $this->moufManager->getInstanceDescriptor($instanceName);
            $config = $em->getProperty('config')->getValue();

            $configQuoteProperty = $config->getSetterProperty('setQuoteStrategy');
            if (!$configQuoteProperty->isValueSet()) {
                $quoteStrategy = $this->moufManager->createInstance("Mouf\\Doctrine\\ORM\\Mapping\\EscapingQuoteStrategy");
                $quoteStrategy->setName('escapingQuoteStrategy');
                $configQuoteProperty->setValue($quoteStrategy);
            }

            $configNamingProperty = $config->getSetterProperty('setNamingStrategy');
            if(!$configNamingProperty) {
                $namingStrategy = $this->moufManager->createInstance("Mouf\\Doctrine\\ORM\\Mapping\\UnderscoreNamingStrategy");
                $namingStrategy->setName('underscoreNamingStrategy');
                $configNamingProperty->setValue($namingStrategy);
            }

            $configMetadataCacheProperty = $config->getSetterProperty('setMetadataCacheImpl');
            $configQueryCacheProperty = $config->getSetterProperty('setQueryCacheImpl');
            $configResultCacheProperty = $config->getSetterProperty('setResultCacheImpl');
            if(!$configMetadataCacheProperty || !$configQueryCacheProperty || !$configResultCacheProperty){
                $doctrineApc = $this->moufManager->getInstanceDescriptor('defaultDoctrineCache');

                if(!$configQueryCacheProperty){
                    $configQueryCacheProperty->setValue($doctrineApc);
                }

                if(!$configMetadataCacheProperty){
                    $configMetadataCacheProperty->setValue($doctrineApc);
                }

                if(!$configResultCacheProperty){
                    $configResultCacheProperty->setValue($doctrineApc);
                }
            }
        }

        $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../composer.json');

        $entitiesNamespace = rtrim($entitiesNamespace, '\\');
        $proxyNamespace = rtrim($proxyNamespace, '\\');
        $daoNamespace = rtrim($daoNamespace, '\\');

        // Let's locate the path by locating a fake class in the namespace.
        $entitiesPath = substr($classNameMapper->getPossibleFileNames($entitiesNamespace.'\\ZZZ')[0], 0, -7);
        $proxyPath = substr($classNameMapper->getPossibleFileNames($proxyNamespace.'\\ZZZ')[0], 0, -7);
        $daoPath = substr($classNameMapper->getPossibleFileNames($daoNamespace.'\\ZZZ')[0], 0, -7);

        $fileSystem = new Filesystem();
        $oldMask = umask(0);
        // Note: for some reason, the mode of mkdir is not accounted for. We need to call chmod on it
        // Not perfect: only the last dir takes the mode, not the intermediate directories.
        $fileSystem->mkdir(array(ROOT_PATH.'../../../'.$entitiesPath, ROOT_PATH.'../../../'.$proxyPath, ROOT_PATH.'../../../'.$daoPath), 0775);
        try {
            $fileSystem->chmod(array(ROOT_PATH.'../../../'.$entitiesPath, ROOT_PATH.'../../../'.$proxyPath, ROOT_PATH.'../../../'.$daoPath), 0775);
        } catch (IOException $e) {
            // Do nothing because the change mode can send an error if the folder is associated to another user (in the same group)
        }
        umask($oldMask);

        $defaultMappingDriver = InstallUtils::getOrCreateInstance('defaultMappingDriver', null, $this->moufManager);
        $defaultMappingDriver->setCode('return new Doctrine\\ORM\\Mapping\\Driver\\AnnotationDriver($container->get(\'annotationReader\'), [ROOT_PATH . "'.$entitiesPath.'"]);');

        if (!$this->moufManager->has('mappingDriverChain')) {
            $mappingDriverChain = $this->moufManager->createInstance("Mouf\\Doctrine\\ORM\\Mapping\\Driver\\MappingDriverChain");
            $mappingDriverChain->setName('mappingDriverChain');
            $mappingDriverChain->getProperty('defaultDriver')->setValue($defaultMappingDriver);
        } else {
            $mappingDriverChain = $this->moufManager->getInstanceDescriptor('mappingDriverChain');
        }

        $config->getProperty('metadataDriverImpl')->setValue($mappingDriverChain);
        $config->getProperty('proxyDir')->setOrigin('php')->setValue('return ROOT_PATH."'.addslashes($proxyPath).'";');
        $config->getProperty('proxyNamespace')->setValue($proxyNamespace);
        // Proxy classes are generated in development mode only.
        $config->getProperty('autoGenerateProxyClasses')->setOrigin('config')->setValue('DEBUG');
        // Ignore table "patches" because it is managed by our patch system.
        $config->getProperty('filterSchemaAssetsExpression')->setValue('/^(?!patches$).*/');

        // On the dbalConnection, we register a mapping type "enum"=>"string"
        $em->getProperty('entityManagerClassName')->setValue("Mouf\\Doctrine\\ORM\\EntityManager");
        $em->getProperty('conn')->setOrigin('php')->setValue('$dbalConnection = $container->get("dbalConnection");
$dbalConnection->getDatabasePlatform()->registerDoctrineTypeMapping("enum", "string");
return $dbalConnection;');
        $em->getProperty('config')->setValue($config);
        $em->getProperty('eventManager')->setValue($eventManager);

        $em->getSetterProperty('setEntitiesNamespace')->setValue($entitiesNamespace);
        $em->getSetterProperty('setProxyNamespace')->setValue($proxyNamespace);
        $em->getSetterProperty('setDaoNamespace')->setValue($daoNamespace);

        //Update connection to get the same configuration instance
        $dbalConnection->getProperty('config')->setValue($config);

        // Now, let's write the commands
        $consoleUtils = new ConsoleUtils($this->moufManager);

        // Let's configure the console
        if (!$this->moufManager->instanceExists("ormConnectionHelper")){
            $ormConnectionHelper = InstallUtils::getOrCreateInstance('ormConnectionHelper', 'Doctrine\\ORM\\Tools\\Console\\Helper\\EntityManagerHelper', $this->moufManager);
            $ormConnectionHelper->getConstructorArgumentProperty("em")->setValue($em);
            $consoleUtils->registerHelper($ormConnectionHelper, 'em');
        }

        $commands = [
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\ClearCache\\MetadataCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\ClearCache\\ResultCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\ClearCache\\QueryCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\SchemaTool\\CreateCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\SchemaTool\\UpdateCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\SchemaTool\\DropCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\EnsureProductionSettingsCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\ConvertDoctrine1SchemaCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\GenerateRepositoriesCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\GenerateEntitiesCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\GenerateProxiesCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\ConvertMappingCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\RunDqlCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\ValidateSchemaCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\InfoCommand',
            '\\Doctrine\\ORM\\Tools\\Console\\Command\\MappingDescribeCommand',
        ];

        foreach ($commands as $command) {
            $consoleUtils->registerCommand($this->moufManager->createInstance($command));
        }

        $this->moufManager->rewriteMouf();

        //Todo: If we generate Dao's we might create all the instances
        $proxy = new InstanceProxy($instanceName);
        $daoData = $proxy->generateDAOs();

        header('Location: generate_schema?name='.urlencode($instanceName).'&selfedit='.urlencode($selfedit).'&installMode='.urlencode($installMode));
    }

    /**
     * Displays the "schema generation screen".
     *
     * @Action
     * @Logged
     *
     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
     */
    public function generate_schema($name, $selfedit = 'false', $installMode = null)
    {
        $this->instanceName = $name;
        $this->selfedit = $selfedit;
        $this->installMode = $installMode;
        $this->patchable = class_exists("Mouf\\Database\\Patcher\\DatabasePatchInstaller");
        if ($this->patchable) {
            // Let's check if there are awaiting patches. If so, let's display a warning.
            $patchService = new InstanceProxy('patchService');
            /* @var $patchService PatchService */
            $this->nbAwaitingPatches = $patchService->getNbAwaitingPatchs();
        }

        if ($selfedit == 'true') {
            $this->moufManager = MoufManager::getMoufManager();
        } else {
            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
        }

        $constants = $this->moufManager->getConfigManager()->getDefinedConstants();
        $this->debugMode = $constants['DEBUG'];

        $proxy = new InstanceProxy($name);
        $this->sql = $proxy->getSchemaUpdateSQL();
        if (empty($this->sql) && $installMode == 1) {
            InstallUtils::continueInstall($selfedit == 'true');

            return;
        }
        if($this->moufManager->issetVariable("doctrine_".$name."_generatePatch")) {

            $this->generatePatch = $this->moufManager->getVariable("doctrine_" . $name . "_generatePatch");
        }
        $this->contentBlock->addFile(__DIR__.'/../views/install2.php', $this);
        $this->template->toHtml();
    }
    /**
     * Displays the "schema generation screen".
     *
     * @Action
     * @Logged
     *
     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
     */
    public function install($instanceName, $selfedit, $installMode = null, $generateDaos = null, $generatePatch = false)
    {
        if ($selfedit == 'true') {
            $this->moufManager = MoufManager::getMoufManager();
        } else {
            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
        }

        $proxy = new InstanceProxy($instanceName);

        $this->moufManager->setVariable("doctrine_".$instanceName."_generatePatch", $generatePatch);

        $fileName = $proxy->updateSchema();
        if ($generatePatch) {
            DatabasePatchInstaller::generatePatch($this->moufManager,'Doctrine patch to match DB schema with defined entities.', $instanceName, $selfedit);
        }
        if ($generateDaos) {
            $daoData = $proxy->generateDAOs();

            $em = $this->moufManager->getInstanceDescriptor($instanceName);

            foreach ($daoData as $fullClassName => $className) {
                if (!$this->moufManager->instanceExists(lcfirst($className))) {
                    $daoInstance = $this->moufManager->createInstance($fullClassName);
                    $daoInstance->setName(lcfirst($className));
                } else {
                    $daoInstance = $this->moufManager->getInstanceDescriptor(lcfirst($className));
                }
                $daoInstance->getProperty('entityManager')->setValue($em);
            }
        }

        $this->moufManager->rewriteMouf();

        if ($installMode) {
            InstallUtils::continueInstall($selfedit == 'true');
        } else {
            set_user_message("Schema and DAOs have been successfully updated.

			A backup dump has been generated in $fileName", UserMessageInterface::SUCCESS);
            header('Location:'.ROOT_URL."ajaxinstance/?name=$instanceName&selfedit=".$selfedit);
        }
    }
}


<?php namespace Impleri\Toolbox\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Event;

class BuildCommand extends Command
{
    /**
     * The console command name.
     * @var string
     */
    protected $name = 'toolbox:build';

    /**
     * The console command description.
     * @var string
     */
    protected $description = 'Executes all toolbox builders.';

    /**
     * Execute the console command.
     */
    public function fire()
    {
        $this->line('');

        $message = 'This will execute indiscriminately all methods which '
            . 'subscribe to the `toolbox.build` event.';
        $this->comment($message);
        $this->line('');
        Event::fire('toolbox.build', [$this]);

        // Done!
        $this->line('');
        $this->info('Compilation completed!');
        $this->line('');
    }
}


<?php
namespace Zf2FileUploader\Controller;

use Doctrine\ORM\EntityRepository;
use Zend\Mvc\Controller\AbstractController;
use Zend\Mvc\MvcEvent;
use Zend\Stdlib\RequestInterface as Request;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\Http\PhpEnvironment\Response as HttpResponse;
use Zf2FileUploader\Entity\ResourceInterface as EntityResourceInterface;
use Zf2FileUploader\View\Model\UploaderModel;

abstract class AbstractRemoveController extends AbstractController
{
    const REMOVE_ROUTE_PARAM = 'token';

    /**
     * @var EntityResourceInterface
     */
    protected $resourceEntity = null;

    /**
     * @return EntityResourceInterface
     */
    protected function getResource()
    {
        return $this->resourceEntity;
    }

    /**
     * @return EntityRepository
     */
    abstract protected function getRepository();

    /**
     * Dispatch a request
     *
     * @events dispatch.pre, dispatch.post
     * @param  Request $request
     * @param  null|Response $response
     * @return Response|mixed
     */
    public function dispatch(Request $request, Response $response = null)
    {
        $this->resourceEntity = $this->getRepository()->findOneByToken($this->params()
                                                                            ->fromRoute(static::REMOVE_ROUTE_PARAM));

        if (is_null($this->resourceEntity)) {
            $response = $response ?: new HttpResponse();
            $this->getEventManager()->clearListeners(MvcEvent::EVENT_DISPATCH);
            $response->setStatusCode(404);
        }

        parent::dispatch($request, $response);
    }
}


<?php
namespace Zf2FileUploader\Controller;

use Zend\Mvc\Controller\AbstractController;
use Zend\Mvc\MvcEvent;
use Zend\Stdlib\RequestInterface as Request;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\Http\PhpEnvironment\Response as HttpResponse;
use Zf2FileUploader\View\Model\UploaderModelInterface;
use Zf2Libs\Data\DataInterface;

abstract class AbstractCreateController extends AbstractController
{
    /**
     * @var boolean
     */
    protected $disableDefaultErrorHandler = false;

    /**
     * @var UploaderModelInterface
     */
    protected $uploaderModel;

    /**
     * @return DataInterface
     */
    abstract protected function getDataResourceCreator();

    /**
     * @param bool $flag
     * @return $this
     */
    public function setDisableDefaultErrorHandler($flag = false)
    {
        $this->disableDefaultErrorHandler = $flag;
        return $this;
    }

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

    /**
     * Dispatch a request
     *
     * @events dispatch.pre, dispatch.post
     * @param  Request $request
     * @param  null|Response $response
     * @return Response|mixed
     */
    public function dispatch(Request $request, Response $response = null)
    {
        $this->request = $request;
        $this->getDataResourceCreator()->setData(array_merge_recursive($this->params()->fromPost(),
                                                                       $request->getFiles()->toArray()));

        if (!$this->getDataResourceCreator()->isValid()) {
            if ($this->disableDefaultErrorHandler) {
                $response = $response ?: new HttpResponse();
                $this->getEventManager()->clearListeners(MvcEvent::EVENT_DISPATCH);
                $this->getEvent()->setResult(false);
                $response->setStatusCode(400);
            } else {
                $this->getEventManager()->clearListeners(MvcEvent::EVENT_DISPATCH);
                $this->uploaderModel->setMessages($this->getDataResourceCreator());

                $this->getEvent()->setResult($this->uploaderModel);
            }
        }

        parent::dispatch($request, $response);
    }
}


<?php
/**
 * Container class.
 *
 * @package metis
 */

namespace Metis;

use Pimple\ServiceProviderInterface;
use Pimple\Container as PimpleContainer;

/**
 * Defines the container class.
 */
class Container extends PimpleContainer {
	/**
	 * List of registered providers.
	 *
	 * @var ServiceProviderInterface[]
	 */
	protected $providers = array();

	/**
	 * Loop through all registered providers and call the activate method.
	 *
	 * @return void
	 */
	public function activate() {
		$this->invoke_on_providers( 'activate' );
	}

	/**
	 * Loop through all registered providers and call the boot method.
	 *
	 * @return void
	 */
	public function boot() {
		$this->invoke_on_providers( 'boot' );
	}

	/**
	 * Loop through all registered providers and call the deactivate method.
	 *
	 * @return void
	 */
	public function deactivate() {
		$this->invoke_on_providers( 'deactivate' );
	}

	/**
	 * Register a service provider.
	 *
	 * @param  ServiceProviderInterface $provider Provider instance.
	 * @param  array                    $values   Values to customize the provider.
	 *
	 * @return static
	 */
	public function register( ServiceProviderInterface $provider, array $values = array() ) {
		parent::register( $provider, $values );

		$this->providers[] = $provider;

		return $this;
	}

	/**
	 * Invoke a method (if it exists) on all registered providers.
	 *
	 * @param  string $method Method name.
	 *
	 * @return void
	 */
	protected function invoke_on_providers( $method ) {
		foreach ( $this->providers as $provider ) {
			if ( method_exists( $provider, $method ) ) {
				$provider->{$method}( $this );
			}
		}
	}
}


<?php

namespace Simples\Model\Resource;

use Simples\Data\Record;
use Simples\Error\SimplesRunTimeError;
use Simples\Kernel\Container;
use Simples\Model\Action;
use function count;

/**
 * Class ModelHook
 * @package Simples\Model\Resource
 */
trait ModelHook
{
    /**
     * @param string $collection
     * @param string $method
     * @param bool $strict
     * @return array
     */
    final public function filterFields(string $collection, string $method, bool $strict)
    {
        return array_filter($this->fields, function ($field) use ($collection, $method, $strict) {
            if ($strict && $field->getCollection() !== $collection) {
                return null;
            }
            if (!$method) {
                return $field;
            }
            if ($method && $field->$method()) {
                return $field;
            }
            return null;
        });
    }

    /**
     * @param string $action
     * @param Record $record
     * @throws SimplesRunTimeError
     */
    final public function configureFields(string $action, Record $record)
    {
        foreach ($this->maps as $source => $target) {
            $record->set($target, $record->get($source));
        }
        $action = ucfirst($action);
        if (method_exists($this, "configureFields{$action}")) {
            call_user_func_array([$this, "configureFields{$action}"], [$record]);
        }
    }

    /**
     * @param string $action
     * @param Record $record
     * @return array
     */
    final public function getDefaults(string $action, Record $record = null): array
    {
        $action = ucfirst($action);
        if (method_exists($this, "getDefaults{$action}")) {
            return call_user_func_array([$this, "getDefaults{$action}"], [$record]);
        }
        return [];
    }

    /**
     * This method is called before the operation be executed, the changes made in Record will be save
     * @param string $action
     * @param Record $record
     * @param Record $previous
     * @return bool
     * @throws SimplesRunTimeError
     */
    final public function before(string $action, Record $record, Record $previous = null): bool
    {
        $action = ucfirst($action);
        $method = "before{$action}";
        $container = Container::instance();
        if ($container->exists($this, $method)) {
            return $container->invoke($this, $method, ['record' => $record, 'previous' => $previous]);
        }
        return true;
    }

    /**
     * Triggered after operation be executed, the changes made in Record has no effect in storage
     * @param string $action
     * @param Record $record
     * @param mixed $extra
     * @return bool|array
     * @throws SimplesRunTimeError
     */
    final public function after(string $action, Record $record, $extra = true)
    {
        $data = is_array($extra) ? $extra : [];

        $data = $this->afterDefault($action, $record, $data);

        $name = ucfirst($action);
        $method = "after{$name}";
        $container = Container::instance();
        if ($container->exists($this, $method)) {
            return $container->invoke($this, $method, ['record' => $record, 'data' => $data]);
        }

        if ($action === Action::READ) {
            return $data;
        }

        return $extra;
    }

    /**
     * @param string $action
     * @param Record $record
     * @param array $data
     * @return array|bool
     */
    final protected function afterDefault(string $action, Record $record, array $data = [])
    {
        $action = ucfirst($action);
        $method = "afterDefault{$action}";
        if (!method_exists($this, $method)) {
            return $data;
        }
        return call_user_func_array([$this, $method], [$record, $data]);
    }

    /**
     * @param Record $record
     * @return boolean
     * @SuppressWarnings("Unused")
     */
    final protected function afterDefaultCreate(Record $record)
    {
        $this->pivotSolver('create', $record);

        return true;
    }

    /**
     * @param Record $record
     * @param array $data
     * @return mixed
     * @SuppressWarnings("Unused")
     */
    final protected function afterDefaultRead(Record $record, array $data)
    {
        if (count($data) === 1) {
            return $this->pivotSolver('read', $record, $data);
        }
        return $data;
    }

    /**
     * @param Record $record
     * @return boolean
     * @SuppressWarnings("Unused")
     */
    final protected function afterDefaultUpdate(Record $record)
    {
        $this->pivotSolver('update', $record);

        return true;
    }

    /**
     * @param Record $record
     * @return boolean
     * @SuppressWarnings("Unused")
     */
    final protected function afterDefaultDestroy(Record $record)
    {
        $this->pivotSolver('destroy', $record);

        return true;
    }
}


<?php namespace Clean\Data;

use Closure;
use InvalidArgumentException;
use LogicException;
use RuntimeException;

class Collection extends \ArrayIterator
{
    /**
     * Constructs Collection object
     *
     * @param mixed $data data
     */
    public function __construct($data = null)
    {
        parent::__construct([]);
        if ($data) {
            $this->append($data);
        }
    }

    /**
     * Returns new instance of collection of the same type
     *
     * @return static
     */
    public function getNewCollection()
    {
        $class = get_called_class();
        return new $class;
    }

    /**
     * Extend collection with entities from another one
     *
     * @param Collection $data
     * @access public
     *
     * @return static
     */
    public function extend(Collection $collection)
    {
        foreach ($collection as $entity) {
            $this->append($entity);
        }
        return $this;
    }

    /**
     * Append entities to collection
     *
     * @param Entity|Collection|Traversable|array $data entity or list of entities to append
     * @access public
     *
     * @return static
     */
    public function append($data)
    {
        if (is_array($data) || $data instanceof \Traversable) {
            foreach ($data as $entity) {
                if (!$entity instanceof Entity) {
                    throw new InvalidArgumentException('Collection can contain only Entities class');
                }
                parent::append($entity);
            }
        } else {
            parent::append($data);
        }
        return $this;
    }

    /**
     * Prepand entity to the begining of collection
     *
     * @param Entity $entity
     *
     * @return static
     */
    public function prepend($entity)
    {
        $collection = $this->getNewCollection();
        $collection->append($entity);
        foreach ($this as $entity) {
            $collection->append($entity);
        }
        $this->clear();
        $this->append($collection);
        return $this;
    }

    public function __call($name, $args)
    {
        switch ($this->count()) {
            case 0:
                throw new LogicException('Cannot operate on empty collection');
            case 1:
                $entity = $this->first();
                if (!method_exists($entity, $name)) {
                    throw new RuntimeException(
                        sprintf("Class %s does not have a method '%s'", get_class($entity), $name)
                    );
                }
                return call_user_func_array([$entity, $name], $args);
            default:
                throw new LogicException(
                    'Collection has more then one element, you cannot call entity method directly'
                );
        }
    }

    /**
     * Returns direct value from entity when collection has only one element
     *
     * @param string $name property name
     *
     * @throws LogicException when collection has more then one element
     *
     * @return mixed
     */
    public function __get($name)
    {
        if (!$this->__isset($name)) {
            return null;
        }
        return $this->first()->$name;
    }

    /**
     * Returns isset on entity property when collection has only one element
     *
     * @param string $name property name
     *
     * @throws LogicException when collection has more then one element
     *
     * @return mixed
     */
    public function __isset($name)
    {
        if ($this->count() > 1) {
            throw new LogicException(
                'Collection has more then one element, you cannot get entity property directly'
            );
        }
        $current = $this->first();
        if (!$current) {
            return false;
        }
        return isset($current->$name);
    }

    /**
     * Returns first entity from collection
     *
     * @return Entity
     */
    public function first()
    {
        $this->rewind();
        return $this->current();
    }

    /**
     * Returns last entity from collection
     *
     * @return Entity
     */
    public function last()
    {
        $this->seek($this->count() - 1);
        $entity = $this->current();
        $this->rewind();
        return $entity;
    }

    /**
     * Returns element moved by offset from the current key
     *
     * @param integer $offset offset
     *
     * @return Entity
     */
    private function getElementMovedByOffset($offset)
    {
        if (!is_int($this->key())) {
            throw new LogicException(sprintf("Can't get element moved by %s as current key is not numeric", $offset));
        }
        $oldPosition = $this->key();
        $newPosition = $oldPosition + $offset;
        $this->seek($newPosition);
        if (!is_int($this->key())) {
            throw new LogicException(sprintf("Can't get element moved by %s as next key is not numeric", $offset));
        }
        $value = $this->current();
        $this->seek($oldPosition);
        return $value;
    }

    /**
     * Returns next entity from collection
     *
     * @return Entity
     */
    public function getNext()
    {
        return $this->getElementMovedByOffset(1);
    }

    /**
     * Returns previous entity from collection
     *
     * @return Entity
     */
    public function getPrevious()
    {
        return $this->getElementMovedByOffset(-1);
    }

    /**
     * returns random entity from collection
     *
     * @return Entity
     */
    public function getRandom()
    {
        $randomKey = array_rand($this->getArrayCopy());
        return $this[$randomKey];
    }

    /**
     * Returns true if collection is not empty
     *
     * @return bool
     */
    public function isNotEmpty()
    {
        return !$this->isEmpty();
    }

    /**
     * Returns true if collection is empty
     *
     * @return bool
     */
    public function isEmpty()
    {
        return (0 === $this->count());
    }

    /**
     * Checks if collection has entity with field equals to given value
     *
     * @param string $field field
     * @param mixed $value value
     *
     * @return bool
     */
    public function has($field, $value, $strict = false)
    {
        return !(false === $this->search($field, $value, $strict));
    }

    /**
     * Search for an element with given property and value
     *
     * @param string $field name of property
     * @param mixed $value value to compare
     * @param bool $strict compare value and type of property
     *
     * @return integer|string|false
     */
    public function search($field, $value, $strict = false)
    {
        $value = is_array($value) ? $value : array($value);
        foreach ($this as $key => $entity) {
            if (isset($entity->$field) && in_array($entity->$field, $value, $strict)) {
                return $key;
            }
        }

        return false;
    }

    /**
     * Shift an entity off the begining of collection
     *
     * @return Entity
     */
    public function shift()
    {
        $slice = $this->slice(0, 1);
        $offset = $slice->getKeys();
        $this->offsetUnset($offset[0]);
        return $slice->first();
    }

    /**
     * Filter collection from entities not matching criteria given in callback
     *
     * @param \Closure $callback callback
     *
     * @return static
     */
    public function filter(\Closure $callback)
    {
        $offsetToRemove = [];
        foreach ($this as $offset => $entity) {
            if (!$callback($entity)) {
                $offsetToRemove[] = $offset;
            }
        }
        $this->offsetUnset($offsetToRemove);
        return $this;
    }

    /**
     * Get collection of entities matching criteria given in callback
     *
     * Usage example:
     *
     * $colleciton->getBy(function($entity) {
     *    return $entity->name == 'John';
     * });
     *
     * @param Closure $callback
     * @return static
     */
    public function getBy(\Closure $callback)
    {
        $instanceCopy = $this->getNewCollection();
        foreach ($this as $offset => $entity) {
            if ($callback($entity)) {
                $instanceCopy->append($entity);
            }
        }

        return $instanceCopy;
    }

    /**
     * Returns collection keys
     *
     * @return array
     */
    public function getKeys()
    {
        $keys = array();
        foreach ($this as $key => $entity) {
            $keys[] = $key;
        }
        return $keys;
    }

    /**
     * Splits collection into chunks
     *
     * @param integer $size
     *
     * @return static
     */
    public function chunk($size)
    {
        $collection = $this->getNewCollection();

        foreach (array_chunk($this->getKeys(), $size) as $chunkIndex => $keys) {
            $collection[$chunkIndex] = $this->getNewCollection();

            foreach ($keys as $key) {
                $collection[$chunkIndex]->append($this[$key]);
            }
        }

        return $collection;
    }

    /**
     * Extract a slice of the collection
     *
     * @param integer $offset
     * @param integer|null $length
     *
     * @return static
     */
    public function slice($offset, $length = null)
    {
        $keys = $this->getKeys();

        $keys = array_slice($keys, $offset, $length);

        $collection = $this->getNewCollection();

        foreach ($this as $key => $entity) {
            if (in_array($key, $keys)) {
                $collection[$key] = $entity;
            }
        }

        return $collection;
    }

    /**
     * Returns collection of collections created by spliting first Collection to a parts
     *
     * Example:
     *
     * When collection has 10 element and we would like to split to 3 separate collections:
     *
     * $splitted = $collection->split(3);
     * $splitted->count(); // = 3
     * $splitted[0]->count(); // = 4
     * $splitted[1]->count(); // = 4
     * $splitted[3]->count(); // = 2
     *
     * @param integer $parts
     *
     * @return static
     */
    public function split($parts)
    {
        $elementsPerChunk = ceil($this->count() / $parts);

        return $this->chunk($elementsPerChunk);
    }

    /**
     * Remove all entities form collection
     *
     * @return static
     */
    public function clear()
    {
        $this->offsetUnset($this->getKeys());
        return $this;
    }

    /**
     * Unset values from an offset or offsets
     *
     * @param string|array $index Offsets to remove
     *
     * @return static
     */
    public function offsetUnset($index)
    {
        $index = is_array($index) ? $index : (array)$index;
        foreach ($index as $key) {
            parent::offsetUnset($key);
        }
        return $this;
    }

    /**
     * Tranform collection to array
     *
     * @return array
     */
    public function toArray()
    {
        $result = [];
        foreach ($this as $entity) {
            $result[] = (array)$entity;
        }
        return $result;
    }

    /**
     * Renumber collection keys (from zero to n), keeping values in the same place
     * @return static
     */
    public function reindex()
    {
        $data = $this->getArrayCopy();
        $this->clear();

        $index = 0;
        foreach ($data as $value) {
            $this[$index++] = $value;
        }
        $this->rewind();

        return $this;
    }

    /**
     * Eliminates entities that contains the same value in given property
     *
     * @param string $propertyName Name of the property
     *
     * @return static
     */
    public function distinctOn($propertyName)
    {
        $values = [];
        $keys = [];
        foreach ($this as $key => $entity) {
            if (in_array($entity->$propertyName, $values)) {
                $keys[] = $key;
            } else {
                $values[] = $entity->$propertyName;
            }
        }
        $this->offsetUnset($keys);
        return $this;
    }

    /**
     * Return an collection with elements in reverse order
     *
     * @return static
     */
    public function reverse()
    {
        $positions = array_flip($this->getKeys());
        $this->uksort(
            function ($a, $b) use ($positions) {
                return ($positions[$a] < $positions[$b] ? 1 : -1);
            }
        );

        return $this;
    }

    /**
     * Apply a user supplied function to every member of an Collection
     *
     * @param Closure $callback user supplied function
     *
     * @return static
     */
    public function walk(Closure $callback)
    {
        foreach ($this as $entity) {
            $callback($entity);
        }

        return $this;
    }

    /**
     * Return values from all entities from given property
     *
     * @param string $name name
     *
     * @return array
     */
    public function getAllValuesForProperty($name)
    {
        $values = [];
        foreach ($this as $entity) {
            if (isset($entity->$name)) {
                $value = $entity->$name;
                if (!($value === null || $value instanceof Collection && $value->isEmpty())) {
                    if (is_scalar($value)) {
                        $values[$value] = $value;
                    } else {
                        $values[] = $value;
                    }
                }
            }
        }

        return array_values($values);
    }

    /**
     * Bind two collections
     *
     * @param Collection $collection collection
     * @param array $compareKeys The name of the key to compare with from target Collection
     * @param string $propertyName The nae of new property that will be created in source Collection
     *
     * @return static
     */
    public function bindCollection(Collection $collection, array $compareKeys, $propertyName)
    {
        $reflection = new \ReflectionClass($collection);

        $fromKey = key($compareKeys);
        $toKey = $compareKeys[$fromKey];

        $collection = $collection->groupByField($fromKey);

        foreach ($this as $entity) {
            if (!isset($entity->$propertyName)) {
                $entity->$propertyName = new $reflection->name;
            }

            if (!isset($entity->$toKey) || ($value = $entity->$toKey) === null) {
                continue; //do not try to bind to null or non existing property
            }

            if (isset($collection[$value])) {
                $entity->$propertyName->append($collection[$value]);
            }
        }
        return $this;
    }

    /**
     * Group entities inside collection to sepearate Collections
     *
     * @param string $name Property name to group by
     *
     * @return static
     */
    private function groupByField($name)
    {
        $collection = $this->getNewCollection();
        foreach ($this as $entity) {
            if (!isset($entity->$name) || $entity->$name === null) {
                continue; //when entity dosen't have set property it will be omitted
            }

            $value = $entity->$name;

            if (!isset($collection[$value])) {
                $collection[$value] = $this->getNewCollection();
            }
            $collection[$value]->append($entity);
        }
        return $collection;
    }
}


<?php namespace Mobileka\ScopeApplicator;

use Mobileka\MosaicArray\MosaicArray;
use Mobileka\ScopeApplicator\Contracts\InputManagerInterface;

class Configurator
{
    /**
     * @var array
     */
    protected $scopes;

    /**
     * @var InputManagerInterface
     */
    protected $inputManager;

    /**
     * @param InputManagerInterface $inputManager
     * @param array                 $scopes
     */
    public function __construct(InputManagerInterface $inputManager, array $scopes = [])
    {
        $this->inputManager = $inputManager;
        $this->scopes = $scopes;
    }

    /**
     * @return \Mobileka\ScopeApplicator\Contracts\InputManagerInterface
     */
    public function getInputManager()
    {
        return $this->inputManager;
    }

    /**
     * Parse scope configuration passed as a second argument for applyScopes method
     *
     * @return array
     */
    public function prepareScopes()
    {
        $result = [];

        foreach ($this->scopes as $key => $scope) {
            // If no scope configuration has been provided, just make scope's name to be its alias
            if (!is_array($scope)) {
                $result[$scope] = ['alias' => $scope];
                continue;
            }

            $result[$key] = $scope;

            // If no alias has been provided, make it to be scope's name
            if (!isset($scope['alias'])) {
                $result[$key]['alias'] = $key;
            }
        }

        return $result;
    }

    /**
     * Parse scope arguments from request parameters
     *
     * @param  array $scope
     * @return array
     */
    public function parseScopeArguments(array $scope)
    {
        $scope = new MosaicArray($scope);
        $result = [];

        // If "type" key has been provided, we have to typecast the result
        $type = $scope->getItem('type');

        // Get default scope argument value
        $default = $scope->getItem('default');

        // Get request parameter value
        $value = $this->getInputManager()->get($scope['alias'], null);

        // If there are no parameters with the scope name:
        // 1) in a case when no default value is set, return null to ignore this scope
        // 2) if default value is set, return it
        if (is_null($value)) {
            return !is_null($default) ? [$default] : null;
        }

        // If "keys" configuration key has been provided, we are dealing with an array parameter (e.g. <input name="somename[somekey]">)
        $keys = $scope->getItem('keys');

        // If "keys" are empty, we have to perform some DRY actions
        if (is_null($keys)) {
            $keys = ['default'];
            $value = ['default' => $value];
        }

        foreach ((array) $keys as $key) {
            $arg = $this->setType($value[$key], $type);

            // Empty arguments are not allowed by default in order to allow default scope argument values
            // Set allowEmpty option to `true` if you want to change this behavior
            if ($arg !== '' or $scope->getItem('allowEmpty')) {
                $result[] = $arg;
            }
        }

        return $result;
    }

    /**
     * Typecast a variable
     *
     * @param  mixed       $variable
     * @param  string|null $type
     * @return mixed
     */
    protected function setType($variable, $type)
    {
        // Do nothing if $type is not a string
        if (is_string($type)) {
            if (in_array($type, ['bool', 'boolean'])) {
                // Only 1, '1', true and 'true' values will be converted to boolean true
                // Any other value will be converted to boolean false
                $variable = in_array($variable, [1, '1', true, 'true'], true);
            } else {
                settype($variable, $type);
            }
        }

        return $variable;
    }
}


<?php namespace Potter\Utils\Form\Fields;

use HtmlObject\Element;
use HtmlObject\Traits\Tag;
use Illuminate\Support\Collection;

class Checkable extends Tag
{

    /**
     * @var null|string|array
     */
    protected $selected;

    /**
     * @var string
     */
    protected $type = 'checkbox';

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

    /**
     * @var
     */
    protected $id;

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

    /**
     * @var bool
     */
    protected $isMultiple = true;

    /**
     * @var Collection
     */
    protected $choices;

    public function __construct($type, $name = null, $selected = null, $attributes = array())
    {
        $this->choices  = new Collection();
        $this->selected = $selected;
        $this->name     = ($this->isMultiple) ? $name . '[]' : $name;
        $this->id       = (isset($attributes['id'])) ? $attributes['id'] : uniqid('checkable-');

        if (isset($attributes['choices'])) $this->parseChoices($attributes['choices']);
        if (isset($attributes['label'])) $this->label = $attributes['label'];

        array_forget($attributes, ['value', 'type', 'name', 'choices', 'label']);

        $this->setTag('p', null, $attributes);

        $this->removeClass('widefat');
    }

    /**
     * @param $value
     *
     * @return $this
     */
    public function setSelected($value)
    {
        $this->selected = $value;

        return $this;
    }

    /**
     * @param array $choices
     *
     * @return $this
     */
    public function parseChoices(array $choices)
    {
        foreach ($choices as $value => $choice):
            $this->addChoice($choice, $value);
        endforeach;

        return $this;
    }

    /**
     * @param string|array $_choice
     * @param string       $_value
     *
     * @return $this
     */
    public function addChoice($_choice, $_value = null)
    {
        if (is_array($_choice)):
            $text  = array_get($_choice, 'label');
            $value = array_get($_choice, 'value');
            $atts  = array_except($_choice, ['label']);
        else:
            $text  = $_choice;
            $value = (is_null($_value)) ? $_choice : $_value;
            $atts  = ['value' => $value];
        endif;

        if (!isset($atts['id'])) $atts['id'] = $this->id . '-' . $this->choices->count();

        $choice                 = new Input($this->type, $this->name, $value, $atts);
        $choice->inputCheckable = true;

        $choice->setAttribute('type', $this->type);

        if ($this->isSelected($value)) $choice->setAttribute('checked', 'checked');

        $choice->addClass($this->type);
        $choice->setLabel($text);
        $choice->setContainer(null);

        $this->choices->push($choice);

        return $this;
    }

    /**
     * @param $value
     *
     * @return bool
     */
    protected function isSelected($value)
    {
        if (is_array($this->selected)):
            return in_array($value, $this->selected);
        endif;

        return $this->selected == $value;
    }

    /**
     * @return string
     */
    public function render()
    {
        $value = $this->choices->all();

        if (!empty($this->label)):
            $label = Element::create('label', $this->label);
            $this->nest($label, 'label');
            $this->nest('<br>');
        endif;

        $this->nest($value, 'choices');

        return parent::render();
    }

}


<?php
namespace Mouf\Doctrine\ORM\Admin;

use Mouf\Actions\InstallUtils;
use Mouf\MoufInstanceDescriptor;
use Mouf\MoufManager;

class DoctrineInstallUtils {

    private $moufManager;

    public function __construct(MoufManager $moufManager)
    {
        $this->moufManager = $moufManager;
    }

    /**
     * Registers a set of annotation-based entities.
     *
     * @param string $namespace
     * @param string $directory Directory where the annotations are stored, relative to ROOT_PATH.
     */
    public function registerAnnotationBasedEntities($namespace, $directory) {
        $mappingDriver = InstallUtils::getOrCreateInstance('mappingDriver.'.$namespace, null, $this->moufManager);
        $mappingDriver->setCode('return new Doctrine\\ORM\\Mapping\\Driver\\AnnotationDriver($container->get(\'annotationReader\'), [ROOT_PATH . "'.$directory.'"]);');

        $this->addDriverToChain($namespace, $mappingDriver);
    }

    /**
     * Registers a set of XML-based entities using Symfony's simplified XML driver:
     * http://doctrine-orm.readthedocs.org/en/latest/reference/xml-mapping.html
     *
     * Note: you can use a global.orm.xml file to define all files.
     *
     * @param string $namespace
     * @param string $directory Directory where the annotations are stored, relative to ROOT_PATH.
     */
    public function registerXmlBasedEntities($namespace, $directory) {
        $mappingDriver = InstallUtils::getOrCreateInstance('mappingDriver.'.$namespace, null, $this->moufManager);

        $code = '
        $namespaces = array(
            ROOT_PATH.'.var_export($directory, true).' => '.var_export($namespace, true).'
        );
        $driver = new \Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver($namespaces);
        $driver->setGlobalBasename("global"); // global.orm.xml
        return $driver;
        ';

        $mappingDriver->setCode($code);

        $this->addDriverToChain($namespace, $mappingDriver);
    }

    /**
     * Registers a set of YAML-based entities using Symfony's simplified YAML driver:
     * http://doctrine-orm.readthedocs.org/en/latest/reference/xml-mapping.html
     *
     * Note: you can use a global.orm.xml file to define all files.
     *
     * @param string $namespace
     * @param string $directory Directory where the annotations are stored, relative to ROOT_PATH.
     */
    public function registerYamlBasedEntities($namespace, $directory) {
        $mappingDriver = InstallUtils::getOrCreateInstance('mappingDriver.'.$namespace, null, $this->moufManager);

        $code = '
        $namespaces = array(
            ROOT_PATH.'.var_export($directory, true).' => '.var_export($namespace, true).'
        );
        $driver = new \Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver($namespaces);
        $driver->setGlobalBasename("global"); // global.orm.xml
        return $driver;
        ';

        $mappingDriver->setCode($code);

        $this->addDriverToChain($namespace, $mappingDriver);
    }

    private function addDriverToChain($namespace, MoufInstanceDescriptor $driverDescriptor) {
        $defaultMappingDriver = $this->moufManager->getInstanceDescriptor('mappingDriverChain');
        $drivers = $defaultMappingDriver->getSetterProperty('setDrivers')->getValue();
        $drivers[$namespace] = $driverDescriptor;
        $defaultMappingDriver->getSetterProperty('setDrivers')->setValue($drivers);
    }
}


<?php
namespace elnebuloso\Flex\Converter;

/**
 * Class PathToNamespaceClassname
 *
 * @author Jeff Tunessen <jeff.tunessen@gmail.com>
 */
class PathToNamespaceClassname
{
    /**
     * convert path to namespaced classname
     *
     * @param string $string
     * @return string
     */
    public function convert($string)
    {
        $stringToCamelCase = new StringToCamelCase();
        $parts = [];

        foreach (explode('/', trim($string, '/')) as $part) {
            $parts[] = ucfirst($stringToCamelCase->convert($part, '-'));
        }

        return implode('\\', $parts);
    }
}


<?php
/*
 * Copyright (c) 2012 David Negrier
 *
 * See the file LICENSE.txt for copying permission.
 */
namespace Mouf\Html\Widgets\Menu;

/**
 * This class represent a menu item style icon to add an icon for the renderer.
 * It is important to note that a menu item does not render directly in HTML (it has no toHtml method).
 * Instead, you must use another class (a Menu renderer class) to display the menu.
 *
 *
 * @Component
 */
class MenuItemStyleIcon implements MenuItemStyleInterface {

	/**
	 * The link for the icon (relative to the root url), unless it starts with / or http:// or https://.
	 *
	 * @var string
	 */
	private $url;

	/**
	 * Returns the URL for this menu (or null if this menu is not a link).
	 * @return string
	 */
	public function getUrl() {
		if (strpos($this->url, "/") === 0
			|| strpos($this->url, "javascript:") === 0
			|| strpos($this->url, "http://") === 0
			|| strpos($this->url, "https://") === 0) {
			return $this->url;
		}
		return ROOT_URL.$this->url;
	}

	/**
	 * The link for the menu (relative to the root url), unless it starts with / or http:// or https://.
	 *
	 * @Property
	 * @param string $url
	 */
	public function setUrl($url) {
		$this->url = $url;
	}
}
?>


<?php
namespace Triadev\Es;

use Elasticsearch\Client;
use Elasticsearch\ClientBuilder;
use Triadev\Es\Contract\ElasticsearchContract;

class Elasticsearch implements ElasticsearchContract
{
    /** @var Client */
    private $client;

    /**
     * Get client
     *
     * @return Client
     */
    public function getClient(): Client
    {
        if (!$this->client) {
            $this->client = $this->buildElasticsearchClient();
        }

        return $this->client;
    }

    private function buildElasticsearchClient() : Client
    {
        $config = config('triadev-elasticsearch');

        $clientBuilder = ClientBuilder::create();

        $clientBuilder->setHosts(explode('|', array_get($config, 'hosts')));
        $clientBuilder->setRetries(array_get($config, 'retries'));

        if ($logger = array_get($config, 'logger')) {
            $clientBuilder->setLogger($logger);
        }

        if ($connectionPool = array_get($config, 'connection.pool')) {
            $clientBuilder->setConnectionPool($connectionPool);
        }

        if ($connectionSelector = array_get($config, 'connection.selector')) {
            $clientBuilder->setSelector($connectionSelector);
        }

        if ($serializer = array_get($config, 'serializer')) {
            $clientBuilder->setSerializer($serializer);
        }

        return $clientBuilder->build();
    }
}


<?php namespace Mobileka\ScopeApplicator;

use ErrorException;
use Mobileka\ScopeApplicator\Contracts\InputManagerInterface;
use Mobileka\ScopeApplicator\Contracts\LoggerInterface;

/**
 * Easily filter data based on named scopes in models
 */
trait ScopeApplicator
{
    /**
     * Provide a way to get request parameters
     *
     * @return InputManagerInterface
     */
    abstract public function getInputManager();

    /**
     * @return LoggerInterface
     */
    abstract public function getLogger();

    /**
     * @param array $scopes
     * @return \Mobileka\ScopeApplicator\Configurator
     */
    public function getConfigurator($scopes)
    {
        return new Configurator($this->getInputManager(), $scopes);
    }

    /**
     * Apply scopes
     *
     * @param  mixed $dataProvider
     * @param  array $allowedScopes
     * @throws \ErrorException
     * @throws \Mobileka\ScopeApplicator\BadInputManagerException
     * @return mixed
     */
    public function applyScopes($dataProvider, array $allowedScopes = [])
    {
        // Validate getInputManager() implementation
        if (!$this->validateInputManager()) {
            throw new BadInputManagerException;
        }

        // If there are no allowed scopes, just return the $dataProvider
        if ($allowedScopes) {
            $configurator = $this->getConfigurator($allowedScopes);
            $scopes = $configurator->prepareScopes();

            foreach ($scopes as $scope => $config) {
                $scopeArguments = $configurator->parseScopeArguments($config);

                // If null, we have to ignore this scope
                if (!is_null($scopeArguments)) {
                    try {
                        $dataProvider = call_user_func_array([$dataProvider, $scope], $scopeArguments);
                    } catch (ErrorException $e) {
                        $this->getLogger()->log($e);
                        throw $e;
                    }
                }
            }
        }

        return $dataProvider;
    }

    /**
     * Make sure that getInputManger returns an instance of InputManagerInterface
     *
     * @return bool
     */
    protected function validateInputManager()
    {
        return $this->getInputManager() instanceof InputManagerInterface;
    }
}


<?php

/**
 * @link https://github.com/rkit/settings-yii2
 * @copyright Copyright (c) 2015 Igor Romanov
 * @license [MIT](http://opensource.org/licenses/MIT)
 */

namespace rkit\settings;

use Yii;
use yii\helpers\ArrayHelper;
use yii\db\Query;

/**
 * Component for storage settings in db
 */
class Settings extends \yii\base\Component
{
    /**
     * @var string $tableName Table name
     */
    public $tableName = 'settings';
    /**
     * @var string $cacheName A key identifying the values to be cached
     */
    public $cacheName = 'settings';
    /**
     * @var string $cache Cache component name
     */
    public $cache = 'cache';
    /**
     * @var array $data
     */
    private $data = [];

    public function __set($key, $value)
    {
        return $this->set($key, $value);
    }

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

    public function init()
    {
        parent::init();

        $data = Yii::$app->{$this->cache}->get($this->cacheName);

        if ($data) {
            $this->data = unserialize($data);
            return;
        }
        $data = (new Query())->select('*')->from($this->tableName)->all();
        $data = ArrayHelper::map($data, 'key', 'value');
        $this->updateData($data);
    }

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

    /**
     * Get value by key
     *
     * @param string $key
     * @return string
     */
    public function get($key)
    {
        return ArrayHelper::getValue($this->data, $key, null);
    }

    /**
     * Set value
     *
     * @param string $key
     * @param string $value
     * @SuppressWarnings(PHPMD.ElseExpression)
     */
    public function set($key, $value)
    {
        if (array_key_exists($key, $this->data)) {
            $this->update($key, $value);
        } else {
            $this->add($key, $value);
        }

        $this->data[$key] = $value;
        $this->updateData($this->data);
    }

    /**
     * Add setting
     *
     * @param string $key
     * @param string $value
     */
    private function add($key, $value)
    {
        Yii::$app->db
            ->createCommand()
            ->insert($this->tableName, ['key' => $key, 'value' => $value])->execute();
    }

    /**
     * Update setting
     *
     * @param string $key
     * @param string $value
     */
    private function update($key, $value)
    {
        Yii::$app->db
            ->createCommand()
            ->update($this->tableName, ['value' => $value], '`key` = :key', [':key' => $key])->execute();
    }

    /**
     * Load data
     *
     * @param array $data
     */
    public function load($data)
    {
        $db = Yii::$app->db->createCommand();
        $db->truncateTable($this->tableName)->execute();

        if (is_array($data) && count($data)) {
            $db->batchInsert($this->tableName, ['key', 'value'], $this->prepareDataForInsert($data))->execute();
        }
        $this->updateData($data);
    }

    /**
     * Prepare data for insert
     *
     * @param array $data
     * @return array
     */
    private function prepareDataForInsert($data)
    {
        $items = [];
        foreach ($data as $key => $value) {
            $items[] = ['key' => $key, 'value' => $value];
        }

        return $items;
    }

    /**
     * Update data and cache
     *
     * @param array $data
     */
    private function updateData($data)
    {
        $this->data = $data;

        $cache = Yii::$app->{$this->cache};
        $cache->delete($this->cacheName);

        if (is_array($this->data) && count($this->data)) {
            $cache->set($this->cacheName, serialize($this->data));
        }
    }
}


<?php

namespace Simples\Model\Resource;

use Exception;
use Simples\Data\Record;
use Simples\Error\SimplesRunTimeError;
use Simples\Helper\JSON;
use Simples\Kernel\Container;
use Simples\Model\DataMapper;
use Simples\Persistence\Field;
use Simples\Persistence\Filter;
use Simples\Persistence\Fusion;

/**
 * Class ModelParser
 * @package Simples\Model\Resources
 */
trait ModelParser
{
    /**
     * Parse the filters of fields
     *
     * @param array $data
     * @return array
     * @throws Exception
     */
    protected function parseFilterFields(array $data = []): array
    {
        $filters = [];
        foreach ($data as $name => $value) {
            if (is_array($value) && $name === '__filter__') {
                $filters = $this->parseFilterRules($filters, $value);
                continue;
            }
            if (!$this->has($name)) {
                $class = static::class;
                $json = JSON::encode($data);
                throw new SimplesRunTimeError(
                    "There is no property `{$name}` in `{$class}` parsing {$json}"
                );
            }
            $filters[] = Filter::create($this->get($name), $value);
        }
        return $filters;
    }

    /**
     * @param array $filters
     * @param array $rules
     * @return array
     * @throws Exception
     */
    protected function parseFilterRules(array $filters, array $rules): array
    {
        foreach ($rules as $rule) {
            if (!isset($rule['filter']) && !is_array($rule['filter'])) {
                continue;
            }
            $rule['filter'] = $this->parseFilterFields($rule['filter']);
            $filters[] = $rule;
        }
        return $filters;
    }

    /**
     * Parse the values of the fields
     *
     * @param array $filters
     * @return array
     */
    protected function parseFilterValues(array $filters = []): array
    {
        $values = [];
        foreach ($filters as $filter) {
            if (is_array($filter)) {
                $values = array_merge($values, $this->parseFilterValues($filter['filter']));
                continue;
            }
            /** @var Filter $filter */
            $value = $filter->getParsedValue($this->getDriver());
            if (!is_array($value)) {
                $values[] = $value;
                continue;
            }
            $values = array_merge($values, $value);
        }
        return $values;
    }

    /**
     * @param array $fields
     * @return array
     * @throws SimplesRunTimeError
     */
    protected function parseReadRelations(array $fields = []): array
    {
        $join = [];
        /** @var DataMapper $parent */
        foreach ($this->getParents() as $references => $parent) {
            $collection = $parent->getCollection();
            $referenced = $parent->getPrimaryKey();
            $source = $this->getCollection();
            $join[] = Fusion::create($collection, $referenced, $source, $references, false, false);
        }
        foreach ($fields as $field) {
            /** @var Field $field */
            $reference = $field->getReferences();
            if (off($reference, 'fusion')) {
                /** @var DataMapper $instance */
                $instance = Container::instance()->make($reference->class);
                $collection = $instance->getCollection();
                $referenced = $reference->referenced;
                $source = $reference->collection;
                $references = $field->getName();
                $join[] = Fusion::create($collection, $referenced, $source, $references);
            }
        }
        return $join;
    }

    /**
     * @param Record $record
     * @param string $hashKey
     * @param bool $trash (false)
     * @return Record
     * @throws SimplesRunTimeError
     */
    protected function previous(Record $record, string $hashKey, bool $trash = false): Record
    {
        $primaryKey = $this->getPrimaryKey();

        $filter = [$hashKey => $record->get($hashKey)];
        if (!$record->get($hashKey)) {
            $filter = [$primaryKey => $record->get($primaryKey)];
        }

        $read = $this->fields(null)->read($filter, null, $trash)->current();
        $previous = Record::make($read->all(), false);
        if (!$previous->isEmpty()) {
            $record->set($primaryKey, $previous->get($primaryKey));
            $record->set($hashKey, $previous->get($hashKey));
        }

        return $previous;
    }

    /**
     * @param string $at
     * @param bool $trash
     * @return Filter
     */
    protected function getDestroyFilter(string $at, bool $trash = false): Filter
    {
        $field = new Field($this->getCollection(), $at, $this->getTimestampValue('at'));

        return Filter::create($field, null, Filter::RULE_BLANK, $trash);
    }

    /**
     * @param string $action
     * @param Record $record
     * @param Record $previous (null)
     * @param bool $calculate (false)
     * @return Record
     * @throws SimplesRunTimeError
     */
    public function configureRecord(
        string $action,
        Record $record,
        Record $previous = null,
        bool $calculate = true
    ): Record {
        // $avoid = $this->getAvoid();
        $values = Record::make([]);
        $fields = $this->getActionFields($action);
        foreach ($fields as $field) {
            /** @var Field $field */
            $name = $field->getName();
            /*
            if (in_array($name, $avoid)) {
                continue;
            }
             */
            if ($record->has($name)) {
                $value = $record->get($name);
            }
            if ($calculate && $field->isCalculated()) {
                $value = $this->resolveCalculated($field, $record, $previous);
            }
            if ($calculate && $field->isMutable()) {
                $value = $this->resolveMutation($field, $record);
            }
            if (isset($value)) {
                $values->set($name, $this->resolveValue($value));
                unset($value);
            }
        }
        return $values;
    }

    /**
     * @param Field $field
     * @param Record $record
     * @param Record $previous (null)
     * @return mixed
     */
    protected function resolveCalculated(Field $field, Record $record, Record $previous = null)
    {
        $immutable = $record;
        if ($previous) {
            $immutable = $previous;
        }
        return $field->calculate($immutable);
    }

    /**
     * @param Field $field
     * @param Record $record
     * @return mixed
     */
    protected function resolveMutation(Field $field, Record $record)
    {
        $callable = $field->option('mutator');
        return $callable($record->get($field->getName()));
    }

    /**
     * @param mixed $value
     * @return mixed
     */
    protected function resolveValue($value)
    {
        if ($value === __NULL__) {
            $value = null;
        }
        return $value;
    }

    /**
     * @return array
     */
    protected function getAvoid(): array
    {
        $avoid = [];
        foreach ([$this->destroyKeys, $this->createKeys, $this->updateKeys] as $keys) {
            foreach ($keys as $name) {
                $avoid[] = $name;
            }
        }
        return $avoid;
    }

    /**
     * @param int $options
     * @return string
     * @throws SimplesRunTimeError
     */
    public function getJSON(int $options = 0)
    {
        $fields = [];
        /** @var Field $field */
        foreach ($this->fields as $field) {
            $fields[] = [
                'field' => $field->getName(),
                'type' => $field->getType(),
                'label' => $field->option('label'),
                'grid' => false,
                'form' => ['create', 'show', 'edit'],
                'search' => false,
                'grids' => [
                    'width' => ''
                ],
                'forms' => [
                    'component' => '',
                    'options' => array_map(function ($value) {
                        return [
                            'label' => '',
                            'value' => $value
                        ];
                    }, $field->getEnum()),
                    'width' => '',
                    'disabled' => false,
                    'order' => 0
                ]
            ];
        }

        return JSON::encode($fields, $options);
    }
}


<?php

namespace Mouf\Doctrine\ORM;

use Doctrine\Common\Cache\CacheProvider;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Configuration;
use Doctrine\Common\EventManager;
use Doctrine\ORM\ORMException;
use Mouf\Composer\ClassNameMapper;
use Mouf\Validator\MoufValidatorInterface;
use Mouf\Validator\MoufValidatorResult;
use Mouf\MoufManager;

/**
 * This is a very simple wrapper around Doctrine's EntityManager that exposes its contructor as "public".
 * This allows calling the constructor directly using Mouf.
 *
 * @author David Négrier <david@mouf-php.com>
 * @ExtendedAction {"name":"Generate DAOs", "url":"entityManagerInstall/", "default":false}
 * @ExtendedAction {"name":"Update DB schema", "url":"entityManagerInstall/generate_schema", "default":false}
 */
class EntityManager extends \Doctrine\ORM\EntityManager implements MoufValidatorInterface,MoufEntityManagerInterface
{
    private $entitiesNamespace;
    private $proxyNamespace;
    private $daoNamespace;

    /**
     * Creates a new EntityManager that operates on the given database connection
     * and uses the given Configuration and EventManager implementations.
     *
     * @param \Doctrine\DBAL\Connection     $conn
     * @param \Doctrine\ORM\Configuration   $config
     * @param \Doctrine\Common\EventManager $eventManager
     */
    public function __construct(Connection $conn, Configuration $config, EventManager $eventManager)
    {
        // Those security checks are usually performed in EntityManager::create
        if (! $config->getMetadataDriverImpl()) {
            throw ORMException::missingMappingDriverImpl();
        }
        if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
            throw ORMException::mismatchedEventManager();
        }

        parent::__construct($conn, $config, $eventManager);
    }

    public function updateSchema()
    {
        $metadata = $this->getMetadataFactory()->getAllMetadata();
        if (! empty($metadata)) {
            $tool = new SchemaTool($this);
            $fileName = ROOT_PATH.'dump.sql';
            $sqls = $tool->getCreateSchemaSql($metadata);
            $dump = '';
            foreach ($sqls as $sql) {
                $dump .= $sql.";\n";
            }
            file_put_contents($fileName, $dump);

            $tool->updateSchema($metadata);
        }

        return $fileName;
    }

    public function getSchemaUpdateSQL()
    {
        $doctrineCache = $this->getConfiguration()->getMetadataCacheImpl();
        if ($doctrineCache instanceof CacheProvider) {
            $doctrineCache->deleteAll();
        } else {
            $doctrineCache->delete("*");
        }

        $metadata = $this->getMetadataFactory()->getAllMetadata();
        $sql = array();
        if (! empty($metadata)) {
            $tool = new SchemaTool($this);
            $sql = $tool->getUpdateSchemaSql($metadata);
        }
        return $sql;
    }

    public function generateDAOs()
    {
        //Get Bean / Table list
        $metadata = $this->getMetadataFactory()->getAllMetadata();

        $daos = array();
        foreach ($metadata as $data) {
            // we should check that we generate DAOs only for the root package (not the other entities of other packages)
            $refClass = new \ReflectionClass($data->name);
            $vendorDir = realpath(__DIR__.'/../../../');
            $classFile = $refClass->getFileName();
            if (strpos($classFile, $vendorDir) === 0) {
                continue;
            }

            list($fullClassName, $className) = $this->generateDAO($data);
            $daos[$fullClassName] = $className;
        }

        return  $daos;
    }

    private function generateDAO($data)
    {
        //Get Path where to generate dao files
        $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../composer.json');

        /* @var $data ClassMetaData */
        $entityClass = $data->name;

        $entityName = basename(str_replace("\\", '/', $data->name));
        $tableName = $data->table['name'];
        $daoClassName =  $entityName.'Dao';
        $daoBaseClassName =  $entityName.'BaseDao';

        $daoPath = ROOT_PATH.'/'.$classNameMapper->getPossibleFileNames(rtrim($this->daoNamespace, '\\').'\\'.$daoClassName)[0];
        $daoBasePath = ROOT_PATH.'/'.$classNameMapper->getPossibleFileNames(rtrim($this->daoNamespace, '\\').'\\'.$daoBaseClassName)[0];

        $daoDir = dirname($daoPath);
        if (!is_dir($daoDir)) {
            $oldUmask = umask();
            umask(0);
            $dirCreate = mkdir($daoDir, 0775, true);
            umask($oldUmask);
        }

        //generate magic _call functions : findOne & find By field
        $magicCallsStr = '';
        $magicCallMethodAnnotation = '';
        foreach ($data->fieldNames as $fieldName) {
            if (array_search($fieldName, $data->identifier) === false) {
                $field = \Doctrine\Common\Util\Inflector::classify(str_replace('.', ' ', $fieldName));
                $magicCallMethodAnnotation .=" * @method $entityName findBy$field(\$fieldValue, \$orderBy = null, \$limit = null, \$offset = null)
 * @method $entityName findOneBy$field(\$fieldValue, \$orderBy = null)
";

                $magicCallsStr .= "    /**
     * Finds only one entity by $field.
     * Throw an exception if more than one entity was found.
     *
     * @param mixed \$fieldValue the value of the filtered field
     *
     * @return $entityName
     */
    public function findUniqueBy$field(\$fieldValue)
    {
        return \$this->findUniqueBy(array(".var_export($fieldName, true)." => \$fieldValue));
    }
";
            }
        }

        $str = "<?php

/*
* This file has been automatically generated by Mouf/ORM.
* DO NOT edit this file, as it might be overwritten.
* If you need to perform changes, edit the $daoClassName class instead!
*/

namespace $this->daoNamespace;

use Doctrine\\ORM\\EntityManagerInterface;
use Doctrine\\ORM\\EntityRepository;
use Doctrine\\ORM\\NonUniqueResultException;
use Mouf\\Doctrine\\ORM\\Event\\SaveListenerInterface;
use $entityClass;

/**
 * The $daoBaseClassName class will maintain the persistence of $entityName class into the $tableName table.
 *
$magicCallMethodAnnotation
 */
class $daoBaseClassName extends EntityRepository
{

    /**
     * @var SaveListenerInterface[]
     */
    private \$saveListenerCollection;

    /**
     * @param EntityManagerInterface \$entityManager
     * @param SaveListenerInterface[] \$saveListenerCollection
     */
    public function __construct(EntityManagerInterface \$entityManager, array \$saveListenerCollection = [])
    {
        parent::__construct(\$entityManager, \$entityManager->getClassMetadata('$entityClass'));
        \$this->saveListenerCollection = \$saveListenerCollection;
    }

    /**
     * Get a new persistent entity
     * @param ...\$params
     * @return $entityName
     */
    public function create(...\$params) : $entityName
    {
        \$entity = new $entityName(...\$params);
        \$this->getEntityManager()->persist(\$entity);
        return \$entity;
    }

    /**
     * Peforms a flush on the entity.
     *
     * @param $entityName
     * @throws \\Exception
     */
    public function save($entityName \$entity)
    {
        foreach (\$this->saveListenerCollection as \$saveListener) {
            \$saveListener->preSave(\$entity);
        }

        \$this->getEntityManager()->flush(\$entity);

        foreach (\$this->saveListenerCollection as \$saveListener) {
            \$saveListener->postSave(\$entity);
        }

    }

    /**
     * Peforms remove on the entity.
     *
     * @param $entityName \$entity
     */
    public function remove($entityName \$entity)
    {
        \$this->getEntityManager()->remove(\$entity);
    }

    /**
     * Finds only one entity. The criteria must contain all the elements needed to find a unique entity.
     * Throw an exception if more than one entity was found.
     *
     * @param array \$criteria
     *
     * @return $entityName|null
     */
    public function findUniqueBy(array \$criteria) : ?$entityName
    {
        \$result = \$this->findBy(\$criteria);

        if (count(\$result) === 1) {
            return \$result[0];
        } elseif (count(\$result) > 1) {
            throw new NonUniqueResultException('More than one $entityName was found');
        } else {
            return null;
        }
    }

$magicCallsStr}
";
        file_put_contents($daoBasePath, $str);
        @chmod($daoBasePath, 0664);

        $str = "<?php
namespace $this->daoNamespace;

/**
* The $daoClassName class will maintain the persistence of $entityName class into the $tableName table.
*/
class $daoClassName extends $daoBaseClassName {

	/*** PUT YOUR SPECIFIC QUERIES HERE !! ***/

}";
        if (!file_exists($daoPath)) {
            file_put_contents($daoPath, $str);
            chmod($daoPath, 0664);
        }

        return array($this->daoNamespace."\\".$daoClassName , $daoClassName);
    }

    public function setEntitiesNamespace($entitiesNamespace)
    {
        $this->entitiesNamespace = $entitiesNamespace;
    }
    public function setProxyNamespace($proxyNamespace)
    {
        $this->proxyNamespace = $proxyNamespace;
    }
    public function setDaoNamespace($daoNamespace)
    {
        $this->daoNamespace = $daoNamespace;
    }

    /**
     * (non-PHPdoc).
     *
     * @see \Mouf\Validator\MoufValidatorInterface::validateInstance()
     */
    public function validateInstance()
    {
        $instanceName = MoufManager::getMoufManager()->findInstanceName($this);

        $sql = $this->getSchemaUpdateSQL();
        // Let's validate that the schema and the entities do match
        if (! empty($sql)) {
            return new MoufValidatorResult(MoufValidatorResult::ERROR, "Doctrine ORM: Your database schema does not match the Doctrine entities in your code.  Fix database schema to match entities");
        }

        return new MoufValidatorResult(MoufValidatorResult::SUCCESS, 'Doctrine ORM: Your database schema matches your entities.');
    }
}


<?php
namespace Zf2FileUploader\Validator;

use Doctrine\ORM\EntityRepository;
use Zend\Validator\AbstractValidator;
use Zend\Validator\Exception;

class ResourceTokenValidator extends AbstractValidator
{
    const INVALID        = 'tokenInvalid';

    /**
     * Validation failure message template definitions
     *
     * @var array
     */
    protected $messageTemplates = array(
        self::INVALID        => "Invalid token given."
    );

    /**
     * @var EntityRepository
     */
    protected $repository;

    public function __construct(EntityRepository $repository, $options = null)
    {
        $this->repository = $repository;
        $this->tokenFormatValidator = new TokenFormatValidator();
        parent::__construct($options);
    }

    /**
     * Returns true if and only if $value meets the validation requirements
     *
     * If $value fails validation, then this method returns false, and
     * getMessages() will return an array of messages that explain why the
     * validation failed.
     *
     * @param mixed $tokens
     * @return bool
     */
    public function isValid($tokens)
    {
        if (is_array($tokens)) {
            foreach ($tokens as $token) {
                if (!$this->validate($token)) {
                    return false;
                }
            }
        } else {
            return $this->validate($tokens);
        }
        return true;
    }

    /**
     * @return array
     */
    public function getMessages()
    {
        $messages = parent::getMessages();
        return array_unique(array_merge($messages, $this->tokenFormatValidator->getMessages()));
    }

    /**
     * @param string $token
     * @return bool
     */
    protected function validate($token)
    {
        if (!$this->tokenFormatValidator->isValid($token)) {
            return false;
        }

        $qb = $this->repository->createQueryBuilder('r');
        $qb->select('1')
           ->where('r.token = :t');

        $qb->setParameter('t', $token);

        if (!count($qb->getQuery()->getResult())) {
            $this->error(self::INVALID);
            return false;
        }

        return true;
    }
}


<?php
namespace elnebuloso\Flex\Converter;

use stdClass;

/**
 * Class ArrayToObject
 *
 * @author Jeff Tunessen <jeff.tunessen@gmail.com>
 */
class ArrayToObject
{
    /**
     * convert array to object
     *
     * @param array $data
     * @return stdClass
     */
    public function convert($data)
    {
        if (is_array($data)) {
            if (!is_numeric(key($data))) {
                return (object) array_map(__METHOD__, $data);
            }

            /** @var stdClass $data */
            return $data;
        } else {
            /** @var stdClass $data */
            return $data;
        }
    }
}


<?php
/*
 * Copyright (c) 2012 David Negrier
 *
 * See the file LICENSE.txt for copying permission.
 */
namespace Mouf\Html\Widgets\Menu;

use Mouf\Utils\Common\ConditionInterface\ConditionInterface;
use Mouf\Utils\I18n\Fine\Translate\LanguageTranslationInterface;
use Mouf\Html\HtmlElement\HtmlElementInterface;
use Mouf\Html\Renderer\Renderable;

/**
 * This class represent a menu item.
 * It is important to note that a menu item does not render directly in HTML (it has no toHtml method).
 * Instead, you must use another class (a Menu renderer class) to display the menu.
 * Usually, menu renderers are embedded into templates.
 *
 */
class MenuItem implements MenuItemInterface, HtmlElementInterface {
	use Renderable;

	/**
	 * The text for the menu item
	 *
	 * @var string
	 */
	private $label;

	/**
	 * The link for the menu (relative to the root url), unless it starts with / or http:// or https:// or # or ?.
	 *
	 * @var string
	 */
	private $url;

	/**
	 * The children menu item of this menu (if any).
	 *
	 * @var array<MenuItemInterface>
	 */
	private $children;

	/**
	 * The CSS class for the menu, if any.
	 * Use of this property depends on the menu implementation.
	 *
	 * @var string
	 */
	private $cssClass;

	/**
	 * A list of parameters that are propagated by the link.
	 * For instance, if the parameter "mode" is set to 42 on the page (because the URL is http://mywebsite/myurl?mode=42),
	 * then if you choose to propagate the "mode" parameter, the menu link will have "mode=42" as a parameter.
	 *
 	 * @var array<string>
	 */
	private $propagatedUrlParameters;

	/**
	 * This condition must be matched to display the menu.
	 * Otherwise, the menu is not displayed.
	 * The displayCondition is optional. If no condition is set, the menu will always be displayed.
	 *
	 * @var ConditionInterface
	 */
	private $displayCondition;

	/**
	 * The translation service to use (if any) to translate the label text.
	 *
	 * @var LanguageTranslationInterface
	 */
	private $translationService;

	/**
	 * Whether the menu is in an active state or not.
	 *
	 * @var bool
	 */
	private $isActive;

	/**
	 * Whether the menu is extended or not.
	 * This should not have an effect if the menu has no child.
	 *
	 * @var bool
	 */
	private $isExtended;

	/**
	 * Level of priority used to order the menu items.
	 *
	 * @var float
	 */
	private $priority;

	/**
	 * If the URL of the current page matches the URL of the link, the link will be considered as "active".
	 *
	 * @var bool
	 */
	private $activateBasedOnUrl = true;

	/**
	 * @var array<MenuItemStyleInterface>
	 */
	private $additionalStyles = array();

	/**
	 * Constructor.
	 *
	 * @Important
	 * @param string $label The text for the menu item
	 * @param string $url The link for the menu (relative to the root url), unless it starts with / or http:// or https:// or # or ?.
	 * @param array<MenuItemInterface> $children
	 */
	public function __construct($label=null, $url=null, $children=array()) {
		$this->label = $label;
		$this->url = $url;
		$this->children = $children;
	}

	/**
	 * Returns the label for the menu item.
	 * @return string
	 */
	public function getLabel() {
		if ($this->translationService) {
			return $this->translationService->getTranslation($this->label);
		} else {
			return $this->label;
		}
	}

	/**
	 * The label for this menu item.
	 *
	 * @param string $label
	 */
	public function setLabel($label) {
		$this->label = $label;
	}

	/**
	 * Returns the URL for this menu (or null if this menu is not a link).
	 * @return string
	 */
	public function getUrl() {
		return $this->url;
	}

	/**
	 * The link for the menu (relative to the root url), unless it starts with / or http:// or https://.
	 *
	 * @param string $url
	 */
	public function setUrl($url) {
		$this->url = $url;
		return $this;
	}

	/**
	 * Returns a list of children elements for the menu (if there are some).
	 *
	 * @see MenuItemInterface::getChildren()
	 * @return array<MenuItemInterface>
	 */
	public function getChildren() {
		if ($this->sorted == false && $this->children) {
			// First, let's make 2 arrays: the array of children with a priority, and the array without.
			$childrenWithPriorities = array();
			$childrenWithoutPriorities = array();
			foreach ($this->children as $child) {
				/* @var $child MenuItemInterface */
				$priority = $child->getPriority();
				if ($priority === null || $priority === "") {
					$childrenWithoutPriorities[] = $child;
				} else {
					$childrenWithPriorities[] = $child;
				}
			}

			usort($childrenWithPriorities, array($this, "compareMenuItems"));
			$this->children = array_merge($childrenWithPriorities, $childrenWithoutPriorities);
			$this->sorted = true;
		}
		return $this->children;
	}

	private $sorted = false;

	public function compareMenuItems(MenuItem $item1, MenuItem $item2) {
		$priority1 = $item1->getPriority();
		$priority2 = $item2->getPriority();
		/*if ($priority1 === null && $priority2 === null) {
			// If no priority is set, let's keep the default ordering (which happens is usort by always returning positive numbers...)
			return 1;
		}*/
		return $priority1 - $priority2;
	}

	/**
	 * The children menu item of this menu (if any).
	 *
	 * @param array<MenuItemInterface> $children
	 */
	public function setChildren(array $children) {
		$this->sorted = false;
		$this->children = $children;
		return $this;
	}

	/**
	 * Adds a menu item as a child of this menu item.
	 *
	 * @param MenuItemInterface $menuItem
	 */
	public function addMenuItem(MenuItemInterface $menuItem) {
		$this->sorted = false;
		$this->children[] = $menuItem;
	}

	/**
	 * Returns true if the menu is in active state (if we are on the page for this menu).
	 * @return bool
	 */
	public function isActive() {
		if ($this->isActive) {
			return true;
		}
		// TODO: really compare URLs instead of performin a strpos.
		// We can do this using the parse_url function
		//var_dump(parse_url(ROOT_URL.$this->url));

		//$requestUrl = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));

		//error_log($_SERVER['REQUEST_URI'].' - '.$requestUrl.' - '.ROOT_URL.$this->url);
		if($this->activateBasedOnUrl && $this->url !== null) {
			$urlParts = parse_url($_SERVER['REQUEST_URI']);
			$menuUrlParts = parse_url($this->getLinkWithoutParams());

			if (isset($menuUrlParts['path'])) {
				$menuUrl = $menuUrlParts['path'];
			} else {
				$menuUrl = '/';
			}

			if (isset($urlParts['path'])) {
				$requestUrl = $urlParts['path'];
			} else {
				$requestUrl = '/';
			}

			if($requestUrl == $menuUrl) {
				return true;
			}
		}
		/*
		if ($this->activateBasedOnUrl && $this->url && strpos($_SERVER['REQUEST_URI'], ROOT_URL.$this->url) !== false) {
			return true;
		}
		*/
		return false;
	}

	/**
	 * Set the active state of the menu.
	 *
	 * @param bool $isActive
	 */
	public function setIsActive($isActive) {
		$this->isActive = $isActive;
		return $this;
	}

	/**
	 * Enables the menu item (activates it).
	 *
	 */
	public function enable() {
		$this->isActive = true;
		return $this;
	}

	/**
	 * Returns true if the menu should be in extended state (if we can see the children directly).
	 * @return bool
	 */
	public function isExtended() {
		return $this->isExtended;
	}

	/**
	 * Whether the menu is extended or not.
	 * This should not have an effect if the menu has no child.
	 *
	 * @param bool $isExtended
	 */
	public function setIsExtended($isExtended = true) {
		$this->isExtended = $isExtended;
		return $this;
	}

	/**
	 * Returns an optional CSS class to apply to the menu item.
	 * @return string
	 */
	public function getCssClass() {
		return $this->cssClass;
	}

	/**
	 * An optional CSS class to apply to the menu item.
	 * Use of this property depends on the menu implementation.
	 *
	 * @param string $cssClass
	 */
	public function setCssClass($cssClass) {
		$this->cssClass = $cssClass;
		return $this;
	}

	/**
	 * Level of priority used to order the menu items.
	 *
	 * @param float $priority
	 */
	public function setPriority($priority) {
		$this->priority = $priority;
		return $this;
	}

	/**
	 * Returns the level of priority. It is used to order the menu items.
	 * @return float
	 */
	public function getPriority() {
		return $this->priority;
	}

	/**
	 * Returns the list of additionnal style
	 * @return array<MenuItemStyleInterface>
	 */
	public function getAdditionalStyles() {
		return $this->additionalStyles;
	}

	/**
	 * Returns the one of additionnal style
	 * @return array<MenuItemStyleInterface>
	 */
	public function getAdditionalStyleByType($type) {
		$return = null;
		if($this->additionalStyles) {
			foreach ($this->additionalStyles as $additionalStyle) {
				if($additionalStyle instanceof $type) {
					if($return === null)
						$return = $additionalStyle;
					else
						throw new \Exception("MenuItem: There are many instance of $type, please use getAdditionalStylesByType function to get all instance");
				}
			}
		}
		return $return;
	}

	/**
	 * Returns the list of additionnal style
	 * @return array<MenuItemStyleInterface>
	 */
	public function getAdditionalStylesByType($type) {
		$return = array();
		if($this->additionalStyles) {
			foreach ($this->additionalStyles as $additionalStyle) {
				if($additionalStyle instanceof $type) {
					$return[] = $additionalStyle;
				}
			}
		}
		return $return;
	}

	/**
	 * Add menu item style.
	 *
	 * @param array<MenuItemStyleInterface> $menuItemStyleInterface
	 */
	public function setAdditionalStyles($menuItemStyleInterface) {
		$this->additionalStyles = $menuItemStyleInterface;
		return $this;
	}

	/**
	 * Returns true if this menu item is a separator.
	 * A separator is a special case of menu item that is juste here to separate menu items with a bar.
	 * It has no label, no URL, etc...
	 *
	 * @return bool
	 */
	public function isSeparator() {
		return false;
	}

	/**
	 * If this function returns true, the menu item should not be displayed.
	 *
	 * @return bool
	 */
	public function isHidden() {
		if ($this->displayCondition == null) {
			return false;
		}
		return !$this->displayCondition->isOk();
	}

	/**
	 * If any translation service is set, it will be used to translate the label.
	 * Otherwise, the label is displayed "as-is".
	 *
	 * @param LanguageTranslationInterface $translationService
	 */
	public function setTranslationService(LanguageTranslationInterface $translationService) {
		$this->translationService = $translationService;
		return $this;
	}

	/**
	 * If set, this display condition is tested. If it returns false, the menu will be hidden.
	 *
	 * @param ConditionInterface $displayCondition
	 */
	public function setDisplayCondition(ConditionInterface $displayCondition) {
		$this->displayCondition = $displayCondition;
		return $this;
	}

	/**
	 * A list of parameters that are propagated by the link.
	 * For instance, if the parameter "mode" is set to 42 on the page (because the URL is http://mywebsite/myurl?mode=42),
	 * then if you choose to propagate the "mode" parameter, the menu link will have "mode=42" as a parameter.
	 *
	 * @param array<string> $propagatedUrlParameters
	 */
	public function setPropagatedUrlParameters($propagatedUrlParameters) {
		$this->propagatedUrlParameters = $propagatedUrlParameters;
		return $this;
	}

	/**
	 * Returns the absolute URL, with parameters if required.
	 * @return string
	 */
	public function getLink() {
		if ($this->url === null) {
			return null;
		}
		$link = $this->getLinkWithoutParams();

		$params = array();
		// First, get the list of all parameters to be propagated
		if (is_array($this->propagatedUrlParameters)) {
			foreach ($this->propagatedUrlParameters as $parameter) {
				if (isset($_REQUEST[$parameter])) {
					$params[$parameter] = \get($parameter);
				}
			}
		}

		if (!empty($params)) {
			if (strpos($link, "?") === FALSE) {
				$link .= "?";
			} else {
				$link .= "&";
			}
			$paramsAsStrArray = array();
			foreach ($params as $key=>$value) {
				$paramsAsStrArray[] = urlencode($key).'='.urlencode($value);
			}
			$link .= implode("&", $paramsAsStrArray);
		}

		return $link;
	}

	private function getLinkWithoutParams() {
		if (strpos($this->url, "/") === 0
			|| strpos($this->url, "javascript:") === 0
			|| strpos($this->url, "http://") === 0
			|| strpos($this->url, "https://") === 0
			|| strpos($this->url, "?") === 0
			|| strpos($this->url, "#") === 0) {
			return $this->url;
		}

		return ROOT_URL.$this->url;
	}

	/**
	 * If the URL of the current page matches the URL of the link, the link will be considered as "active".
	 *
	 * @param bool $activateBasedOnUrl
	 */
	public function setActivateBasedOnUrl($activateBasedOnUrl = true) {
		$this->activateBasedOnUrl = $activateBasedOnUrl;
		return $this;
	}
}
?>


<?php
namespace elnebuloso\Flex\Converter;

/**
 * Class ObjectToArray
 *
 * @author Jeff Tunessen <jeff.tunessen@gmail.com>
 */
class ObjectToArray
{
    /**
     * convert object to array
     *
     * @param mixed $data
     * @return array
     */
    public function convert($data)
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }

        if (is_array($data)) {
            return array_map(__METHOD__, $data);
        } else {
            return $data;
        }
    }
}