<commit_before><?php

namespace Eole\Silex;

use Silex\Application as BaseApplication;

class Application extends BaseApplication
{
    /**
     * {@InheritDoc}
     */
    public function __construct(array $values = array())
    {
        parent::__construct($values);

        $this->logErrors();
        $this->checkConstants();
        $this->loadEnvironmentParameters();
        $this->registerSilexProviders();
        $this->registerSecurity();
        $this->registerOAuth2Security();
        $this->registerServices();
        $this->registerListeners();
        $this->loadAllGames();
        $this->registerDoctrine();

        if ($this['debug']) {
            $this->enableProfiler();
        }
    }

    /**
     * Check whether application constants are well defined.
     */
    private function checkConstants()
    {
        if (!isset($this['project.root'])) {
            throw new \LogicException('project.root must be defined.');
        }

        if (!isset($this['env'])) {
            throw new \LogicException('env must be defined.');
        }

        $environments = array('dev', 'test', 'prod');

        if (!in_array($this['env'], $environments)) {
            throw new \DomainException('env must be one of: "'.implode('", "', $environments).'".');
        }
    }

    /**
     * Load config/environment.yml or config/environment.yml.dist.
     *
     * @throws Exception if file not found.
     */
    private function loadEnvironmentParameters()
    {
        $parser = new \Symfony\Component\Yaml\Parser();
        $environmentFile = $this['project.root'].'/config/environment.yml';
        $extEnvironmentFile = $this['project.root'].'/config/environment_'.$this['env'].'.yml';

        if (!file_exists($environmentFile)) {
            throw new \LogicException($environmentFile.' not found, unable to load environment parameters.');
        }

        $environment = $parser->parse(file_get_contents($environmentFile));

        if (file_exists($extEnvironmentFile)) {
            $extEnvironment = $parser->parse(file_get_contents($extEnvironmentFile));
            $environment = array_replace_recursive($environment, $extEnvironment);
        }

        $this['environment'] = $environment;
    }

    /**
     * Register default silex providers
     */
    private function registerSilexProviders()
    {
        $this->register(new \Silex\Provider\ServiceControllerServiceProvider());
        $this->register(new \Silex\Provider\MonologServiceProvider(), array(
            'monolog.name' => 'eole',
            'monolog.logfile' => $this['project.root'].'/var/logs/monolog_'.$this['env'].'.log',
        ));
    }

    /*
     * Register Symfony security
     */
    private function registerSecurity()
    {
        $userProvider = function () {
            return new \Alcalyn\UserApi\Security\UserProvider($this['eole.player_api']);
        };

        $this->register(new \Silex\Provider\SecurityServiceProvider(), array(
            'security.firewalls' => array(
                'api' => array(
                    'pattern' => '^/api',
                    'oauth' => true,
                    'stateless' => true,
                    'anonymous' => true,
                    'users' => $userProvider,
                ),
            ),
        ));

        $this['eole.player_api'] = function () {
            return new \Eole\Core\Service\PlayerApi(
                $this['eole.player_manager'],
                $this['orm.em']->getRepository('Eole:Player')
            );
        };

        $this['security.default_encoder'] = function () {
            return $this['security.encoder.digest'];
        };

        $this['eole.user_provider'] = $userProvider;
    }

    /*
     * Register OAuth2 Security
     */
    private function registerOAuth2Security()
    {
        $tokensDir = $this['project.root'].'/var/oauth-tokens';
        $clients = $this['environment']['oauth']['clients'];

        $this->register(new \Eole\OAuth2\Silex\OAuth2ServiceProvider('api', $tokensDir, $clients));
    }

    /**
     * Register doctrine DBAL and ORM
     */
    private function registerDoctrine()
    {
        $this->registerDoctrineDBAL();
        $this->registerDoctrineORM();
    }

    /**
     * Register doctrine DBAL
     */
    private function registerDoctrineDBAL()
    {
        $this->register(new \Silex\Provider\DoctrineServiceProvider(), array(
            'db.options' => $this['environment']['database']['connection'],
        ));
    }

    /**
     * Register and configure doctrine ORM
     */
    private function registerDoctrineORM()
    {
        $this->register(new \Dflydev\Provider\DoctrineOrm\DoctrineOrmServiceProvider(), array(
            'orm.proxies_dir' => $this['project.root'].'/var/cache/doctrine/proxies',
            'orm.auto_generate_proxies' => $this['environment']['database']['orm']['auto_generate_proxies'],
            'orm.em.options' => array(
                'mappings' => $this['eole.mappings'],
            ),
        ));
    }

    /**
     * Enable profiler interface for debugging.
     *
     * @throws \LogicException If composer dev dependencies are not loaded.
     */
    private function enableProfiler()
    {
        if (!class_exists('\Silex\Provider\HttpFragmentServiceProvider', true)) {
            throw new \LogicException('You must load composer dev dependencies in order to use profiler.');
        }

        $this->register(new \Silex\Provider\HttpFragmentServiceProvider());
        $this->register(new \Silex\Provider\TwigServiceProvider());

        $this->register(new \Silex\Provider\WebProfilerServiceProvider(), array(
            'profiler.cache_dir' => $this['project.root'].'/var/cache/profiler',
            'profiler.mount_prefix' => '/_profiler',
        ));

        $this->register(new \Sorien\Provider\DoctrineProfilerServiceProvider());
    }

    /**
     * Register Eole services
     */
    private function registerServices()
    {
        $this['serializer.builder'] = function () {
            $serializationContextFactory = function () {
                return \JMS\Serializer\SerializationContext::create()
                    ->setSerializeNull(true)
                ;
            };

            $namingStrategy = new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
                new \JMS\Serializer\Naming\CamelCaseNamingStrategy()
            );

            return
                \JMS\Serializer\SerializerBuilder::create()
                ->setDefaultSerializationContextFactory($serializationContextFactory)<commit_msg>Add group Default in default serialization context<commit_after><?php

namespace Eole\Silex;

use Silex\Application as BaseApplication;

class Application extends BaseApplication
{
    /**
     * {@InheritDoc}
     */
    public function __construct(array $values = array())
    {
        parent::__construct($values);

        $this->logErrors();
        $this->checkConstants();
        $this->loadEnvironmentParameters();
        $this->registerSilexProviders();
        $this->registerSecurity();
        $this->registerOAuth2Security();
        $this->registerServices();
        $this->registerListeners();
        $this->loadAllGames();
        $this->registerDoctrine();

        if ($this['debug']) {
            $this->enableProfiler();
        }
    }

    /**
     * Check whether application constants are well defined.
     */
    private function checkConstants()
    {
        if (!isset($this['project.root'])) {
            throw new \LogicException('project.root must be defined.');
        }

        if (!isset($this['env'])) {
            throw new \LogicException('env must be defined.');
        }

        $environments = array('dev', 'test', 'prod');

        if (!in_array($this['env'], $environments)) {
            throw new \DomainException('env must be one of: "'.implode('", "', $environments).'".');
        }
    }

    /**
     * Load config/environment.yml or config/environment.yml.dist.
     *
     * @throws Exception if file not found.
     */
    private function loadEnvironmentParameters()
    {
        $parser = new \Symfony\Component\Yaml\Parser();
        $environmentFile = $this['project.root'].'/config/environment.yml';
        $extEnvironmentFile = $this['project.root'].'/config/environment_'.$this['env'].'.yml';

        if (!file_exists($environmentFile)) {
            throw new \LogicException($environmentFile.' not found, unable to load environment parameters.');
        }

        $environment = $parser->parse(file_get_contents($environmentFile));

        if (file_exists($extEnvironmentFile)) {
            $extEnvironment = $parser->parse(file_get_contents($extEnvironmentFile));
            $environment = array_replace_recursive($environment, $extEnvironment);
        }

        $this['environment'] = $environment;
    }

    /**
     * Register default silex providers
     */
    private function registerSilexProviders()
    {
        $this->register(new \Silex\Provider\ServiceControllerServiceProvider());
        $this->register(new \Silex\Provider\MonologServiceProvider(), array(
            'monolog.name' => 'eole',
            'monolog.logfile' => $this['project.root'].'/var/logs/monolog_'.$this['env'].'.log',
        ));
    }

    /*
     * Register Symfony security
     */
    private function registerSecurity()
    {
        $userProvider = function () {
            return new \Alcalyn\UserApi\Security\UserProvider($this['eole.player_api']);
        };

        $this->register(new \Silex\Provider\SecurityServiceProvider(), array(
            'security.firewalls' => array(
                'api' => array(
                    'pattern' => '^/api',
                    'oauth' => true,
                    'stateless' => true,
                    'anonymous' => true,
                    'users' => $userProvider,
                ),
            ),
        ));

        $this['eole.player_api'] = function () {
            return new \Eole\Core\Service\PlayerApi(
                $this['eole.player_manager'],
                $this['orm.em']->getRepository('Eole:Player')
            );
        };

        $this['security.default_encoder'] = function () {
            return $this['security.encoder.digest'];
        };

        $this['eole.user_provider'] = $userProvider;
    }

    /*
     * Register OAuth2 Security
     */
    private function registerOAuth2Security()
    {
        $tokensDir = $this['project.root'].'/var/oauth-tokens';
        $clients = $this['environment']['oauth']['clients'];

        $this->register(new \Eole\OAuth2\Silex\OAuth2ServiceProvider('api', $tokensDir, $clients));
    }

    /**
     * Register doctrine DBAL and ORM
     */
    private function registerDoctrine()
    {
        $this->registerDoctrineDBAL();
        $this->registerDoctrineORM();
    }

    /**
     * Register doctrine DBAL
     */
    private function registerDoctrineDBAL()
    {
        $this->register(new \Silex\Provider\DoctrineServiceProvider(), array(
            'db.options' => $this['environment']['database']['connection'],
        ));
    }

    /**
     * Register and configure doctrine ORM
     */
    private function registerDoctrineORM()
    {
        $this->register(new \Dflydev\Provider\DoctrineOrm\DoctrineOrmServiceProvider(), array(
            'orm.proxies_dir' => $this['project.root'].'/var/cache/doctrine/proxies',
            'orm.auto_generate_proxies' => $this['environment']['database']['orm']['auto_generate_proxies'],
            'orm.em.options' => array(
                'mappings' => $this['eole.mappings'],
            ),
        ));
    }

    /**
     * Enable profiler interface for debugging.
     *
     * @throws \LogicException If composer dev dependencies are not loaded.
     */
    private function enableProfiler()
    {
        if (!class_exists('\Silex\Provider\HttpFragmentServiceProvider', true)) {
            throw new \LogicException('You must load composer dev dependencies in order to use profiler.');
        }

        $this->register(new \Silex\Provider\HttpFragmentServiceProvider());
        $this->register(new \Silex\Provider\TwigServiceProvider());

        $this->register(new \Silex\Provider\WebProfilerServiceProvider(), array(
            'profiler.cache_dir' => $this['project.root'].'/var/cache/profiler',
            'profiler.mount_prefix' => '/_profiler',
        ));

        $this->register(new \Sorien\Provider\DoctrineProfilerServiceProvider());
    }

    /**
     * Register Eole services
     */
    private function registerServices()
    {
        $this['serializer.builder'] = function () {
            $serializationContextFactory = function () {
                return \JMS\Serializer\SerializationContext::create()
                    ->setSerializeNull(true)
                    ->setGroups(array('Default'))
                ;
            };

            $namingStrategy = new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
                new \JMS\Serializer\Naming\CamelCaseNamingStrategy()
            );

            return
                \JMS\Serializer\SerializerBuilder::create()
                ->setDefaultSerializationContextFactory($serializationContextFactory)
{'fraction_non_alphanumeric': 0.1441604463545201, 'fraction_numerical': 0.0007539772298876574, 'mean_word_length': 2.2327565196197905, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 92, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2465546', 'n_tokens_mistral': 3629, 'n_tokens_neox': 3544, 'n_words': 594}