Производит инициализацию инстанса справочника по имени его класса.

Алсо - производит проверку его наличия в кэше, валидируя его актуальность по его хэшу.

@param string      $references_class
@param Application $app

@throws Exception

@return mixed
544141
protected function bootUpReferenceInstance($references_class, Application $app)
    {
        $cache = $this->cacheFactory(null, $app);

        /** @var ReferenceInterface $references_class */
        $hash = $references_class::getVendorStaticReferenceInstance()->getHash();

        if ($cache->has($cache_key = $this->generateCacheKey($references_class, $hash))) {
            return $cache->get($cache_key);
        }

        $instance = new $references_class;

        // По умолчанию - храним справочник в кэше одни сутки до его пересоздания
        $cache->put($cache_key, $instance, Carbon::now()->addDays(1));

        return $instance;
    }
439584
public static function create(Application $app)
    {
        $conf = $app['conf']->get('xsendfile');

        $mapping = [];

        if (isset($conf['mapping'])) {
            $mapping = $conf['mapping'];
        }

        return new self($app['monolog'], $conf['enabled'], $conf['type'], $mapping);
    }
462504
public function connect(Application $app)
    {
        $ctrl = parent::connect($app);



        $this->auth = function () use ($app) {
            if (!$app['debug']) {
                $username = $app['request']->server->get('PHP_AUTH_USER', false);
                $password = $app['request']->server->get('PHP_AUTH_PW');

                if ((!$username || !$password) && preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_REMOTE_USER'], $matches)) {
                    list($username, $password) = explode(':', base64_decode($matches[1]));

                    $username = strip_tags($username);
                    $password = strip_tags($password);
                }

                if (($username != $app['config']['admin']['username']) || ($password != $app['config']['admin']['password'])) {
                    $response = new Response(null, Response::HTTP_UNAUTHORIZED);
                    $response->headers->set('WWW-Authenticate', 'Basic realm="Administration"');

                    return $response;
                }
            }
        };



        /**
         * List items
         */
        $ctrl
            ->get(
                '/list',
                function () use ($app) {
                    return $app['twig']->render(
                        'admin/'.$this->table.'/list.twig',
                        [$this->table.'s' => $app['redbean']->findAll(
                            $this->table,
                            'ORDER BY '.(array_key_exists('position', $app['redbean']->getColumns($this->table)) ? 'position' : 'id')
                        )]
                    );
                }
            )
            ->bind($this->table.'.list')
            ->before($this->auth);



        /**
         * Move item up or down
         */
        $ctrl
            ->get(
                '/move/{model}/{up}',
                function ($model, $up) use ($app) {
                    $model->move($up);
                    $app['redbean']->store($model);

                    return $app->redirect($app['url_generator']->generate($this->table.'.list'));
                }
            )
            ->bind($this->table.'.move')
            ->convert('model', $this->modelProvider)
            ->assert('up', '0|1')
            ->before($this->auth);



        /**
         * Clone item
         */
        $ctrl
            ->get(
                '/clone/{model}',
                function ($model) use ($app) {
                    $clone = $app['redbean']->dup($model->unbox());
                    $model->cloneFilesFor($clone);

                    $app['redbean']->store($clone);

                    $app['session']->getFlashBag()->clear();
                    $app['session']->getFlashBag()->add('success', $app['translator']->trans('success.cloning'));

                    return $app->redirect($app['url_generator']->generate($this->table.'.list'));
                }
            )
            ->bind($this->table.'.clone')
            ->convert('model', $this->modelProvider)
            ->before($this->auth);



        /**
         * Toggle item's visibility
         */
        $ctrl
            ->get(
                '/toggle/{model}',
                function ($model) use ($app) {
                    $model->toggle();
                    $app['redbean']->store($model);

                    return $app->redirect($app['url_generator']->generate($this->table.'.list'));
                }
            )
            ->bind($this->table.'.toggle')
            ->convert('model', $this->modelProvider)
            ->before($this->auth);



        /**
         * Delete item
         */
        $ctrl
            ->get(
                '/delete/{model}',
                function ($model) use ($app) {
                    $app['redbean']->trash($model);

                    $app['session']->getFlashBag()->clear();
                    $app['session']->getFlashBag()->add('success', $app['translator']->trans('success.deletion'));

                    return $app->redirect($app['url_generator']->generate($this->table.'.list'));
                }
            )
            ->bind($this->table.'.delete')
            ->convert('model', $this->modelProvider)
            ->before($this->auth);



        /**
         * Create/update item
         */
        $ctrl
            ->match(
                '/post/{model}',
                function ($model) use ($app) {
                    if ('POST' == $app['request']->getMethod()) {
                        $app['session']->getFlashBag()->clear();

                        $app['hydrator']->hydrate($model);
                        $errors = [];

                        // Format error array
                        foreach ($app['validator']->validate($model) as $error) {
                            $errors[] = [
                                $error->getPropertyPath() => $error->getMessage()
                            ];
                        }

                        if (!count($errors)) {
                            $app['redbean']->store($model);
                            $app['session']->getFlashBag()->add('success', $app['translator']->trans('success.save'));

                            return $app->redirect($app['url_generator']->generate($this->table.'.post', ['model' => $model->id]));
                        }

                        foreach ($errors as $error) {
                            $app['session']->getFlashBag()->add('error', $error);
                        }
                    }

                    return $app['twig']->render('admin/'.$this->table.'/post.twig', [$this->table => $model]);
                }
            )
            ->bind($this->table.'.post')
            ->convert('model', $this->modelProvider)
            ->value('model', 0)
            ->before($this->auth)
            ->method('GET|POST');



        /**
         * Delete item's attached file
         */
        $ctrl
            ->get(
                '/delete_file/{model}/{field}',
                function ($model, $field) use ($app) {
                    $app['session']->getFlashBag()->clear();

                    $file = $model->$field;
                    $model->$field = null;
                    $errors = [];

                    // Format error array
                    foreach ($app['validator']->validate($model) as $error) {
                        $errors[] = [
                            $error->getPropertyPath() => $error->getMessage()
                        ];
                    }

                    if (!count($errors)) {
                        is_file($file) && unlink($file);
                        $app['redbean']->store($model);
                        $app['session']->getFlashBag()->add('success', $app['translator']->trans('success.file_deletion'));
                    }

                    foreach ($errors as $error) {
                        $app['session']->getFlashBag()->add('error', $error);
                    }

                    return $app->redirect($app['url_generator']->generate($this->table.'.post', ['model' => $model->id]));
                }
            )
            ->bind($this->table.'.delete_file')
            ->convert('model', $this->modelProvider)
            ->before($this->auth);



        return $ctrl;
    }
900150
protected function renderReference($reference)
    {
        if (!isset($this->settings['references'][$reference])) {
            $this->outputLine('Reference "%s" is not configured', [$reference]);
            $this->quit(1);
        }
        $referenceConfiguration = $this->settings['references'][$reference];
        $affectedClassNames = $this->getAffectedClassNames($referenceConfiguration['affectedClasses']);
        $parserClassName = $referenceConfiguration['parser']['implementationClassName'];
        $parserOptions = isset($referenceConfiguration['parser']['options']) ? $referenceConfiguration['parser']['options'] : [];
        /** @var $classParser \Neos\DocTools\Domain\Service\AbstractClassParser */
        $classParser = new $parserClassName($parserOptions);
        $classReferences = [];
        foreach ($affectedClassNames as $className) {
            $classReferences[$className] = $classParser->parse($className);
        }
        usort($classReferences, function (ClassReference $a, ClassReference $b) {
            if ($a->getTitle() == $b->getTitle()) {
                return 0;
            }

            return ($a->getTitle() < $b->getTitle()) ? -1 : 1;
        });
        $standaloneView = new \Neos\FluidAdaptor\View\StandaloneView();
        $templatePathAndFilename = isset($referenceConfiguration['templatePathAndFilename']) ? $referenceConfiguration['templatePathAndFilename'] : 'resource://Neos.DocTools/Private/Templates/ClassReferenceTemplate.txt';
        $standaloneView->setTemplatePathAndFilename($templatePathAndFilename);
        $standaloneView->assign('title', isset($referenceConfiguration['title']) ? $referenceConfiguration['title'] : $reference);
        $standaloneView->assign('classReferences', $classReferences);
        file_put_contents($referenceConfiguration['savePathAndFilename'], $standaloneView->render());
        $this->outputLine('DONE.');
    }
1079499
public function register(Application $app)
    {
        Assertion::isInstanceOf($app, \Alchemy\Phrasea\Application::class);

        $app['setup.validate-config'] = $app->protect(function (Request $request) use ($app) {
            if (0 === strpos($request->getPathInfo(), '/setup')) {
                if (!$app['phraseanet.configuration-tester']->isInstalled()) {
                    if (!$app['phraseanet.configuration-tester']->isBlank()) {
                        if ('setup_upgrade_instructions' !== $app['request']->attributes->get('_route')) {
                            return $app->redirectPath('setup_upgrade_instructions');
                        }
                    }
                } elseif (!$app['phraseanet.configuration-tester']->isBlank()) {
                    return $app->redirectPath('homepage');
                }
            } else {
                if (false === strpos($request->getPathInfo(), '/include/minify')) {
                    $app['firewall']->requireSetup();
                }
            }
        });
    }
1259184
public function register(Application $app)
    {
        $app['install.generate-proxy'] = $app->share(function ($app) {
            $command = new GenerateInstallCommandProxy('install:generate');
            $command->setFactory($app->raw('install.generate'))
                ->setApp($app);
            return $command;
        });

        $app['install.generate'] = $app->share(function ($app) {
            $command = new GenerateInstallCommand();

            $command->setDbConfig($app['config']->load('db'));
            $command->setInstallConfig($app['config']->load('install'));

            return $command;
        });

        $app['install.run-proxy'] = $app->share(function ($app) {
            $command = new RunInstallCommandProxy('install:run');
            $command->setFactory($app->raw('install.run'))
                ->setApp($app);
            return $command;
        });

        $app['install.run'] = $app->share(function ($app) {
            $command = new RunInstallCommand();

            $command->setDatabaseAdapter($app['db']);
            $command->setAppEnv($app['environment']);
            $command->setRunMigrationsCommand($app['migrations.run-proxy']);
            $command->setGenerateInstallCommand($app['install.generate-proxy']);

            return $command;
        });
    }
52430
protected function registerMapperInitializer(Application $app)
    {
        $initializer = function ($mapper, $app) {
            $mapper->setSqlFactory(new SqlFactory);
        };

        $app->initializer('Synapse\Mapper\AbstractMapper', $initializer);
    }
160645
public static function castApplication($app)
    {
        $results = [];

        foreach (self::$appProperties as $property) {
            try {
                $val = $app->$property();

                if (! is_null($val)) {
                    $results[Caster::PREFIX_VIRTUAL.$property] = $val;
                }
            } catch (Exception $e) {
                //
            }
        }

        return $results;
    }
131930
final protected function resolveApplicationProviders($app): array
    {
        $providers = new Collection($this->getApplicationProviders($app));
        $overrides = $this->overrideApplicationProviders($app);

        if (! empty($overrides)) {
            $providers->transform(function ($provider) use ($overrides) {
                return $overrides[$provider] ?? $provider;
            });
        }

        return $providers->merge($this->getPackageProviders($app))->all();
    }
1302027
static public function setApplicationEntityManager(Application $application)
    {
        $app = $application->getApp();
        $em = $app['em'];
        $helperSet = $application->getHelperSet();
        $helperSet->set(new ConnectionHelper($em->getConnection()), 'db');
        $helperSet->set(new EntityManagerHelper($em), 'em');
    }
1354122
protected function registerServiceProviders(Application $app)
    {
        $app->register(new \Synapse\Command\CommandServiceProvider);
        $app->register(new \Synapse\Db\DbServiceProvider);
        $app->register(new \Synapse\OAuth2\ServerServiceProvider);
        $app->register(new \Synapse\OAuth2\SecurityServiceProvider);
        $app->register(new \Synapse\Resque\ResqueServiceProvider);
        $app->register(new \Synapse\Controller\ControllerServiceProvider);
        $app->register(new \Synapse\Email\EmailServiceProvider);
        $app->register(new \Synapse\User\UserServiceProvider);
        $app->register(new \Synapse\Migration\MigrationServiceProvider);
        $app->register(new \Synapse\Install\InstallServiceProvider);
        $app->register(new \Synapse\Security\SecurityServiceProvider);
        $app->register(new \Synapse\Session\SessionServiceProvider);
        $app->register(new \Synapse\SocialLogin\SocialLoginServiceProvider);
        $app->register(new \Synapse\Time\TimeServiceProvider);
        $app->register(new \Synapse\Template\TemplateServiceProvider);
        $app->register(new \Synapse\Validator\ValidatorServiceProvider);

        $app->register(new \Synapse\View\ViewServiceProvider, [
            'mustache.paths' => array(
                APPDIR.'/templates'
            ),
            'mustache.options' => [
                'cache' => TMPDIR,
            ],
        ]);

        $app->register(new \Silex\Provider\ValidatorServiceProvider);
        $app->register(new \Silex\Provider\UrlGeneratorServiceProvider);

        // Register the CORS middleware
        $app->register(new \JDesrosiers\Silex\Provider\CorsServiceProvider);
        $app->after($app['cors']);
    }
284762
public function register(Application $app)
    {
        parent::register($app);

        $app->register(
            new \Silex\Provider\DoctrineServiceProvider(),
            ['db.options' => $app['config']['db.options']]
        );
        $app->register(
            new DoctrineOrmServiceProvider(),
            $app['config']['orm.options']
        );

        if (getenv('MIGRATION_COMMANDS')) {
            $app->register(new MigrationServiceProvider(), [
                'db.migrations.path' =>$app['config']['migrations.directory'],
            ]);
        }

        $app['orm.em'] = $app->extend('orm.em', function(EntityManagerInterface $em) use($app) {
            if (file_exists(APP_PATH.'/vendor/apitude/apitude/src/Annotations/APIAnnotations.php')) {
                AnnotationRegistry::registerFile(APP_PATH.'/vendor/apitude/apitude/src/Annotations/APIAnnotations.php');
            }
            /** @var Configuration $config */
            $config = $em->getConfiguration();
            $config->setMetadataCacheImpl($app['cache']);
            $config->addCustomHydrationMode('simple', SimpleHydrator::class);

            /** @var MappingDriverChain $driver */
            $driver = $config->getMetadataDriverImpl();

            // gedmo initialization
            $reader = new AnnotationReader();
            $cache = new CachedReader($reader, $app['cache']);
            DoctrineExtensions::registerAbstractMappingIntoDriverChainORM(
                $driver,
                $cache
            );

            return $em;
        });
    }
440310
public function createCache(Application $app)
    {
        $cache = new Pimple;

        foreach ($app['ems.options'] as $name => $options) {
            $cache[$name] = $cache->share(
                function () use ($app, $cache, $options) {
                    $class = 'Doctrine\Common\Cache\\' . $options['caching_driver'];

                    switch ($options['caching_driver']) {
                        case 'ApcCache':
                        case 'ArrayCache':
                        case 'XcacheCache':
                            return new $class();
                        case 'MemcacheCache':
                            $cache = new $class();

                            if ((false === isset($app['memcache']))
                                    && (false === isset($options['memcache']))) {
                                throw new RuntimeException (
                                    'No Memcache client available as a service.'
                                );
                            }

                            $cache->setMemcache(
                                isset($options['memcache'])
                                    ? $options['memcache']
                                    : $app['memcache']
                            );

                            return $cache;
                        case 'MemcachedCache':
                            $cache = new $class();

                            if ((false === isset($app['memcached']))
                                    && (false === isset($options['memcached']))) {
                                throw new RuntimeException (
                                    'No Memcached client available as a service.'
                                );
                            }

                            $cache->setMemcached(
                                isset($options['memcached'])
                                    ? $options['memcached']
                                    : $app['memcached']
                            );

                            return $cache;
                        default:
                            throw new InvalidArgumentException (
                                "Unsupported cache class: $class"
                            );
                    }
                }
            );
        }

        return $cache;
    }
235495
public function setApplication(Application $application = null)
    {
        parent::setApplication($application);

        if (!$this->getHelperSet()) {
            throw new \Exception('Helper set is not set.');
        }
        $this->getHelperSet()->set(new SimpleQuestionHelper());
    }
449935
public function bootstrap(Application $app)
	{
		$this->configureHandlers($app, $this->registerLogger($app));

		// Next, we will bind a Closure that resolves the PSR logger implementation
		// as this will grant us the ability to be interoperable with many other
		// libraries which are able to utilize the PSR standardized interface.
		$app->bind('Psr\Log\LoggerInterface', function($app)
		{
			return $app['log']->getMonolog();
		});
	}
1247932
protected function setEnvironment(Application $app)
    {
        // Define acceptable environments
        $environments = array(
            'production',
            'staging',
            'qa',
            'testing',
            'development',
            'beta',
        );

        if (! isset($_SERVER['APP_ENV'])) {
            throw new \Exception('Missing \'APP_ENV\' environment variable');
        }

        if (! in_array($_SERVER['APP_ENV'], $environments)) {
            throw new \Exception('Invalid \'APP_ENV\' environment variable: \'' + $_SERVER['APP_ENV'] +'\'');
        }

        $app['environment'] = $_SERVER['APP_ENV'];
    }
184657
public function registerInterfaceBindings(Application $app)
    {
        $app->bind(ClientInterface::class, FluentClient::class);
        $app->bind(ScopeInterface::class, FluentScope::class);
        $app->bind(SessionInterface::class, FluentSession::class);
        $app->bind(AuthCodeInterface::class, FluentAuthCode::class);
        $app->bind(AccessTokenInterface::class, FluentAccessToken::class);
        $app->bind(RefreshTokenInterface::class, FluentRefreshToken::class);
    }