Initial commit

This commit is contained in:
2020-10-07 10:37:15 +02:00
commit ce5f440392
28157 changed files with 4429172 additions and 0 deletions

View File

@@ -0,0 +1,480 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\DistributionBundle\Composer;
use Symfony\Component\ClassLoader\ClassCollectionLoader;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\PhpExecutableFinder;
use Composer\Script\Event;
use Composer\Util\ProcessExecutor;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ScriptHandler
{
/**
* Composer variables are declared static so that an event could update
* a composer.json and set new options, making them immediately available
* to forthcoming listeners.
*/
protected static $options = array(
'symfony-app-dir' => 'app',
'symfony-web-dir' => 'web',
'symfony-assets-install' => 'hard',
'symfony-cache-warmup' => false,
);
/**
* Asks if the new directory structure should be used, installs the structure if needed.
*
* @param Event $event
*/
public static function defineDirectoryStructure(Event $event)
{
$options = static::getOptions($event);
if (!getenv('SENSIOLABS_ENABLE_NEW_DIRECTORY_STRUCTURE') || !$event->getIO()->askConfirmation('Would you like to use Symfony 3 directory structure? [y/N] ', false)) {
return;
}
$rootDir = getcwd();
$appDir = $options['symfony-app-dir'];
$webDir = $options['symfony-web-dir'];
$binDir = static::$options['symfony-bin-dir'] = 'bin';
$varDir = static::$options['symfony-var-dir'] = 'var';
static::updateDirectoryStructure($event, $rootDir, $appDir, $binDir, $varDir, $webDir);
}
/**
* Builds the bootstrap file.
*
* The bootstrap file contains PHP file that are always needed by the application.
* It speeds up the application bootstrapping.
*
* @param Event $event
*/
public static function buildBootstrap(Event $event)
{
$options = static::getOptions($event);
$bootstrapDir = $autoloadDir = $options['symfony-app-dir'];
if (static::useNewDirectoryStructure($options)) {
$bootstrapDir = $options['symfony-var-dir'];
if (!static::hasDirectory($event, 'symfony-var-dir', $bootstrapDir, 'build bootstrap file')) {
return;
}
}
if (!static::useSymfonyAutoloader($options)) {
$autoloadDir = $options['vendor-dir'];
}
if (!static::hasDirectory($event, 'symfony-app-dir', $autoloadDir, 'build bootstrap file')) {
return;
}
static::executeBuildBootstrap($event, $bootstrapDir, $autoloadDir, $options['process-timeout']);
}
protected static function hasDirectory(Event $event, $configName, $path, $actionName)
{
if (!is_dir($path)) {
$event->getIO()->write(sprintf('The %s (%s) specified in composer.json was not found in %s, can not %s.', $configName, $path, getcwd(), $actionName));
return false;
}
return true;
}
/**
* Sets up deployment target specific features.
* Could be custom web server configs, boot command files etc.
*
* @param Event $event
*/
public static function prepareDeploymentTarget(Event $event)
{
static::prepareDeploymentTargetHeroku($event);
}
protected static function prepareDeploymentTargetHeroku(Event $event)
{
$options = static::getOptions($event);
if (($stack = getenv('STACK')) && ('cedar-14' == $stack || 'heroku-16' == $stack)) {
$fs = new Filesystem();
if (!$fs->exists('Procfile')) {
$event->getIO()->write('Heroku deploy detected; creating default Procfile for "web" dyno');
$fs->dumpFile('Procfile', sprintf('web: heroku-php-apache2 %s/', $options['symfony-web-dir']));
}
}
}
/**
* Clears the Symfony cache.
*
* @param Event $event
*/
public static function clearCache(Event $event)
{
$options = static::getOptions($event);
$consoleDir = static::getConsoleDir($event, 'clear the cache');
if (null === $consoleDir) {
return;
}
$warmup = '';
if (!$options['symfony-cache-warmup']) {
$warmup = ' --no-warmup';
}
static::executeCommand($event, $consoleDir, 'cache:clear'.$warmup, $options['process-timeout']);
}
/**
* Installs the assets under the web root directory.
*
* For better interoperability, assets are copied instead of symlinked by default.
*
* Even if symlinks work on Windows, this is only true on Windows Vista and later,
* but then, only when running the console with admin rights or when disabling the
* strict user permission checks (which can be done on Windows 7 but not on Windows
* Vista).
*
* @param Event $event
*/
public static function installAssets(Event $event)
{
$options = static::getOptions($event);
$consoleDir = static::getConsoleDir($event, 'install assets');
if (null === $consoleDir) {
return;
}
$webDir = $options['symfony-web-dir'];
$symlink = '';
if ('symlink' == $options['symfony-assets-install']) {
$symlink = '--symlink ';
} elseif ('relative' == $options['symfony-assets-install']) {
$symlink = '--symlink --relative ';
}
if (!static::hasDirectory($event, 'symfony-web-dir', $webDir, 'install assets')) {
return;
}
static::executeCommand($event, $consoleDir, 'assets:install '.$symlink.ProcessExecutor::escape($webDir), $options['process-timeout']);
}
/**
* Updated the requirements file.
*
* @param Event $event
*/
public static function installRequirementsFile(Event $event)
{
$options = static::getOptions($event);
$appDir = $options['symfony-app-dir'];
$fs = new Filesystem();
$newDirectoryStructure = static::useNewDirectoryStructure($options);
if (!$newDirectoryStructure) {
if (!static::hasDirectory($event, 'symfony-app-dir', $appDir, 'install the requirements files')) {
return;
}
$fs->copy(__DIR__.'/../Resources/skeleton/app/SymfonyRequirements.php', $appDir.'/SymfonyRequirements.php', true);
$fs->copy(__DIR__.'/../Resources/skeleton/app/check.php', $appDir.'/check.php', true);
} else {
$binDir = $options['symfony-bin-dir'];
$varDir = $options['symfony-var-dir'];
if (!static::hasDirectory($event, 'symfony-var-dir', $varDir, 'install the requirements files')) {
return;
}
if (!static::hasDirectory($event, 'symfony-bin-dir', $binDir, 'install the requirements files')) {
return;
}
$fs->copy(__DIR__.'/../Resources/skeleton/app/SymfonyRequirements.php', $varDir.'/SymfonyRequirements.php', true);
$fs->copy(__DIR__.'/../Resources/skeleton/app/check.php', $binDir.'/symfony_requirements', true);
$fs->remove(array($appDir.'/check.php', $appDir.'/SymfonyRequirements.php', true));
$fs->dumpFile($binDir.'/symfony_requirements', '#!/usr/bin/env php'."\n".str_replace(".'/SymfonyRequirements.php'", ".'/".$fs->makePathRelative(realpath($varDir), realpath($binDir))."SymfonyRequirements.php'", file_get_contents($binDir.'/symfony_requirements')));
$fs->chmod($binDir.'/symfony_requirements', 0755);
}
$webDir = $options['symfony-web-dir'];
// if the user has already removed the config.php file, do nothing
// as the file must be removed for production use
if ($fs->exists($webDir.'/config.php')) {
$requiredDir = $newDirectoryStructure ? $varDir : $appDir;
$fs->dumpFile($webDir.'/config.php', str_replace('/../app/SymfonyRequirements.php', '/'.$fs->makePathRelative(realpath($requiredDir), realpath($webDir)).'SymfonyRequirements.php', file_get_contents(__DIR__.'/../Resources/skeleton/web/config.php')));
}
}
public static function removeSymfonyStandardFiles(Event $event)
{
$options = static::getOptions($event);
$appDir = $options['symfony-app-dir'];
if (!is_dir($appDir)) {
return;
}
if (!is_dir($appDir.'/SymfonyStandard')) {
return;
}
$fs = new Filesystem();
$fs->remove($appDir.'/SymfonyStandard');
}
public static function doBuildBootstrap($bootstrapDir)
{
$file = $bootstrapDir.'/bootstrap.php.cache';
if (file_exists($file)) {
unlink($file);
}
$classes = array(
'Symfony\\Component\\HttpFoundation\\ParameterBag',
'Symfony\\Component\\HttpFoundation\\HeaderBag',
'Symfony\\Component\\HttpFoundation\\FileBag',
'Symfony\\Component\\HttpFoundation\\ServerBag',
'Symfony\\Component\\HttpFoundation\\Request',
'Symfony\\Component\\ClassLoader\\ClassCollectionLoader',
);
if (method_exists('Symfony\Component\ClassLoader\ClassCollectionLoader', 'inline')) {
ClassCollectionLoader::inline($classes, $file, array());
} else {
ClassCollectionLoader::load($classes, dirname($file), basename($file, '.php.cache'), false, false, '.php.cache');
}
$bootstrapContent = substr(file_get_contents($file), 5);
file_put_contents($file, sprintf(<<<'EOF'
<?php
%s
EOF
, $bootstrapContent));
}
protected static function executeCommand(Event $event, $consoleDir, $cmd, $timeout = 300)
{
$php = ProcessExecutor::escape(static::getPhp(false));
$phpArgs = implode(' ', array_map(array('Composer\Util\ProcessExecutor', 'escape'), static::getPhpArguments()));
$console = ProcessExecutor::escape($consoleDir.'/console');
if ($event->getIO()->isDecorated()) {
$console .= ' --ansi';
}
$process = new Process($php.($phpArgs ? ' '.$phpArgs : '').' '.$console.' '.$cmd, null, null, null, $timeout);
$process->run(function ($type, $buffer) use ($event) { $event->getIO()->write($buffer, false); });
if (!$process->isSuccessful()) {
throw new \RuntimeException(sprintf("An error occurred when executing the \"%s\" command:\n\n%s\n\n%s", ProcessExecutor::escape($cmd), self::removeDecoration($process->getOutput()), self::removeDecoration($process->getErrorOutput())));
}
}
protected static function executeBuildBootstrap(Event $event, $bootstrapDir, $autoloadDir, $timeout = 300)
{
$php = ProcessExecutor::escape(static::getPhp(false));
$phpArgs = implode(' ', array_map(array('Composer\Util\ProcessExecutor', 'escape'), static::getPhpArguments()));
$cmd = ProcessExecutor::escape(__DIR__.'/../Resources/bin/build_bootstrap.php');
$bootstrapDir = ProcessExecutor::escape($bootstrapDir);
$autoloadDir = ProcessExecutor::escape($autoloadDir);
$useNewDirectoryStructure = '';
if (static::useNewDirectoryStructure(static::getOptions($event))) {
$useNewDirectoryStructure = ProcessExecutor::escape('--use-new-directory-structure');
}
$process = new Process($php.($phpArgs ? ' '.$phpArgs : '').' '.$cmd.' '.$bootstrapDir.' '.$autoloadDir.' '.$useNewDirectoryStructure, getcwd(), null, null, $timeout);
$process->run(function ($type, $buffer) use ($event) { $event->getIO()->write($buffer, false); });
if (!$process->isSuccessful()) {
throw new \RuntimeException('An error occurred when generating the bootstrap file.');
}
}
protected static function updateDirectoryStructure(Event $event, $rootDir, $appDir, $binDir, $varDir, $webDir)
{
$event->getIO()->write('Updating Symfony directory structure...');
$fs = new Filesystem();
$fs->mkdir(array($binDir, $varDir));
foreach (array(
$appDir.'/console' => $binDir.'/console',
$appDir.'/phpunit.xml.dist' => $rootDir.'/phpunit.xml.dist',
) as $source => $target) {
$fs->rename($source, $target, true);
}
foreach (array('/logs', '/cache') as $dir) {
$fs->rename($appDir.$dir, $varDir.$dir);
}
$gitignore = <<<EOF
/web/bundles/
/app/config/parameters.yml
/var/bootstrap.php.cache
/var/SymfonyRequirements.php
/var/cache/*
/var/logs/*
!var/cache/.gitkeep
!var/logs/.gitkeep
/build/
/vendor/
/bin/*
!bin/console
!bin/symfony_requirements
/composer.phar
EOF;
$phpunitKernelBefore = <<<EOF
<!--
<php>
<server name="KERNEL_DIR" value="/path/to/your/app/" />
</php>
-->
EOF;
$phpunitKernelAfter = <<<EOF
<php>
<server name="KERNEL_DIR" value="$appDir/" />
</php>
EOF;
$phpunit = str_replace(array('<directory>../src', '"bootstrap.php.cache"', $phpunitKernelBefore), array('<directory>src', '"'.$varDir.'/bootstrap.php.cache"', $phpunitKernelAfter), file_get_contents($rootDir.'/phpunit.xml.dist'));
$composer = str_replace('"symfony-app-dir": "app",', "\"symfony-app-dir\": \"app\",\n \"symfony-bin-dir\": \"bin\",\n \"symfony-var-dir\": \"var\",", file_get_contents($rootDir.'/composer.json'));
$fs->dumpFile($webDir.'/app.php', str_replace($appDir.'/bootstrap.php.cache', $varDir.'/bootstrap.php.cache', file_get_contents($webDir.'/app.php')));
$fs->dumpFile($webDir.'/app_dev.php', str_replace($appDir.'/bootstrap.php.cache', $varDir.'/bootstrap.php.cache', file_get_contents($webDir.'/app_dev.php')));
$fs->dumpFile($binDir.'/console', str_replace(array(".'/bootstrap.php.cache'", ".'/AppKernel.php'"), array(".'/".$fs->makePathRelative(realpath($varDir), realpath($binDir))."bootstrap.php.cache'", ".'/".$fs->makePathRelative(realpath($appDir), realpath($binDir))."AppKernel.php'"), file_get_contents($binDir.'/console')));
$fs->dumpFile($rootDir.'/phpunit.xml.dist', $phpunit);
$fs->dumpFile($rootDir.'/composer.json', $composer);
$fs->dumpFile($rootDir.'/.gitignore', $gitignore);
$fs->chmod($binDir.'/console', 0755);
}
protected static function getOptions(Event $event)
{
$options = array_merge(static::$options, $event->getComposer()->getPackage()->getExtra());
$options['symfony-assets-install'] = getenv('SYMFONY_ASSETS_INSTALL') ?: $options['symfony-assets-install'];
$options['symfony-cache-warmup'] = getenv('SYMFONY_CACHE_WARMUP') ?: $options['symfony-cache-warmup'];
$options['process-timeout'] = $event->getComposer()->getConfig()->get('process-timeout');
$options['vendor-dir'] = $event->getComposer()->getConfig()->get('vendor-dir');
return $options;
}
protected static function getPhp($includeArgs = true)
{
$phpFinder = new PhpExecutableFinder();
if (!$phpPath = $phpFinder->find($includeArgs)) {
throw new \RuntimeException('The php executable could not be found, add it to your PATH environment variable and try again');
}
return $phpPath;
}
protected static function getPhpArguments()
{
$ini = null;
$arguments = array();
$phpFinder = new PhpExecutableFinder();
if (method_exists($phpFinder, 'findArguments')) {
$arguments = $phpFinder->findArguments();
}
if ($env = getenv('COMPOSER_ORIGINAL_INIS')) {
$paths = explode(PATH_SEPARATOR, $env);
$ini = array_shift($paths);
} else {
$ini = php_ini_loaded_file();
}
if ($ini) {
$arguments[] = '--php-ini='.$ini;
}
return $arguments;
}
/**
* Returns a relative path to the directory that contains the `console` command.
*
* @param Event $event The command event
* @param string $actionName The name of the action
*
* @return string|null The path to the console directory, null if not found
*/
protected static function getConsoleDir(Event $event, $actionName)
{
$options = static::getOptions($event);
if (static::useNewDirectoryStructure($options)) {
if (!static::hasDirectory($event, 'symfony-bin-dir', $options['symfony-bin-dir'], $actionName)) {
return;
}
return $options['symfony-bin-dir'];
}
if (!static::hasDirectory($event, 'symfony-app-dir', $options['symfony-app-dir'], 'execute command')) {
return;
}
return $options['symfony-app-dir'];
}
/**
* Returns true if the new directory structure is used.
*
* @param array $options Composer options
*
* @return bool
*/
protected static function useNewDirectoryStructure(array $options)
{
return isset($options['symfony-var-dir']) && is_dir($options['symfony-var-dir']);
}
/**
* Returns true if the application bespoke autoloader is used.
*
* @param array $options Composer options
*
* @return bool
*/
protected static function useSymfonyAutoloader(array $options)
{
return isset($options['symfony-app-dir']) && is_file($options['symfony-app-dir'].'/autoload.php');
}
private static function removeDecoration($string)
{
return preg_replace("/\033\[[^m]*m/", '', $string);
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Sensio\Bundle\DistributionBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Config\FileLocator;
/**
* SensioDistributionExtension.
*
* @author Marc Weistroff <marc.weistroff@sensio.com>
*/
class SensioDistributionExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('security.xml');
}
public function getNamespace()
{
return 'http://symfony.com/schema/dic/symfony/sensiodistribution';
}
public function getAlias()
{
return 'sensio_distribution';
}
}

View File

@@ -0,0 +1,19 @@
Copyright (c) 2010-2017 Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,140 @@
#!/bin/bash
# This file is part of the Symfony Standard Edition.
#
# (c) Fabien Potencier <fabien@symfony.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
if [ ! $1 ]; then
echo "\033[37;41mYou must pass the build dir as an absolute path\033[0m"
exit 1
fi
if [ ! $2 ]; then
echo "\033[37;41mYou must pass the version to build\033[0m"
exit 1
fi
DIR=$1
CURRENT=`php -r "echo realpath(dirname(\\$_SERVER['argv'][0]));"`
if [[ ! "$DIR" = /* ]]; then
DIR="$CURRENT/$DIR"
fi
if [ ! -d $DIR ]; then
echo "\033[37;41mThe build dir does not exist\033[0m"
exit 1
fi
# avoid the creation of ._* files
export COPY_EXTENDED_ATTRIBUTES_DISABLE=true
export COPYFILE_DISABLE=true
# Temp dir
rm -rf /tmp/Symfony
mkdir /tmp/Symfony
# Create project
composer create-project --prefer-dist --no-interaction symfony/framework-standard-edition /tmp/Symfony $2
if [ 0 -ne $? ]; then
echo "\033[37;41mVersion $2 does not exist\033[0m"
exit 1
fi
cd /tmp/Symfony
# cleanup
rm -rf app/cache/* app/logs/* var/cache/* var/logs/*
chmod 777 app/cache app/logs var/cache var/logs
find . -name .DS_Store | xargs rm -rf -
VERSION=`grep ' VERSION ' vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php | sed -E "s/.*'(.+)'.*/\1/g"`
# With vendors
cd /tmp/Symfony
TARGET=/tmp/Symfony/vendor
# Doctrine
cd $TARGET/doctrine/orm && rm -rf UPGRADE* build* tests tools lib/vendor
cd $TARGET/doctrine/dbal && rm -rf build* tests lib/vendor
cd $TARGET/doctrine/common && rm -rf build* tests lib/vendor
if [ -d $TARGET/doctrine/doctrine-bundle/Doctrine/Bundle/DoctrineBundle ]; then
cd $TARGET/doctrine/doctrine-bundle/Doctrine/Bundle/DoctrineBundle && rm -rf Tests Resources/doc
else
cd $TARGET/doctrine/doctrine-bundle && rm -rf Tests Resources/doc
fi
# kriswallsmith
if [ -d $TARGET/kriswallsmith/assetic ]; then
cd $TARGET/kriswallsmith/assetic && rm -rf CHANGELOG* phpunit.xml* tests docs
fi
# Monolog
cd $TARGET/monolog/monolog && rm -rf README.markdown phpunit.xml* tests
# Sensio
if [ -d $TARGET/sensio/distribution-bundle/Sensio/Bundle/DistributionBundle ]; then
cd $TARGET/sensio/distribution-bundle/Sensio/Bundle/DistributionBundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc
else
cd $TARGET/sensio/distribution-bundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc
fi
if [ -d $TARGET/sensio/framework-extra-bundle/Sensio/Bundle/FrameworkExtraBundle ]; then
cd $TARGET/sensio/framework-extra-bundle/Sensio/Bundle/FrameworkExtraBundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc
else
cd $TARGET/sensio/framework-extra-bundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc
fi
if [ -d $TARGET/sensio/generator-bundle/Sensio/Bundle/GeneratorBundle ]; then
cd $TARGET/sensio/generator-bundle/Sensio/Bundle/GeneratorBundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc
else
cd $TARGET/sensio/generator-bundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc
fi
# Swiftmailer
cd $TARGET/swiftmailer/swiftmailer && rm -rf CHANGES README* build* docs notes test-suite tests create_pear_package.php package*
# Symfony
cd $TARGET/symfony/symfony && rm -rf README.md phpunit.xml* tests *.sh vendor
if [ -d $TARGET/symfony/assetic-bundle/Symfony/Bundle/AsseticBundle ]; then
cd $TARGET/symfony/assetic-bundle/Symfony/Bundle/AsseticBundle && rm -rf Tests Resources/doc
elif [ -d $TARGET/symfony/assetic-bundle ]; then
cd $TARGET/symfony/assetic-bundle && rm -rf Tests Resources/doc
fi
if [ -d $TARGET/symfony/swiftmailer-bundle/Symfony/Bundle/SwiftmailerBundle ]; then
cd $TARGET/symfony/swiftmailer-bundle/Symfony/Bundle/SwiftmailerBundle && rm -rf Tests Resources/doc
else
cd $TARGET/symfony/swiftmailer-bundle && rm -rf Tests Resources/doc
fi
if [ -d $TARGET/symfony/monolog-bundle/Symfony/Bundle/MonologBundle ]; then
cd $TARGET/symfony/monolog-bundle/Symfony/Bundle/MonologBundle && rm -rf Tests Resources/doc
else
cd $TARGET/symfony/monolog-bundle && rm -rf Tests Resources/doc
fi
# Twig
cd $TARGET/twig/twig && rm -rf AUTHORS CHANGELOG README.markdown bin doc package.xml.tpl phpunit.xml* test
# cleanup
find $TARGET -name .git | xargs rm -rf -
find $TARGET -name .gitignore | xargs rm -rf -
find $TARGET -name .gitmodules | xargs rm -rf -
find $TARGET -name .svn | xargs rm -rf -
# With vendors
cd /tmp
tar zcpf $DIR/Symfony_Standard_Vendors_$VERSION.tgz Symfony
rm -f $DIR/Symfony_Standard_Vendors_$VERSION.zip
zip -rq $DIR/Symfony_Standard_Vendors_$VERSION.zip Symfony
# Without vendors
cd /tmp
rm -rf Symfony/vendor
tar zcpf $DIR/Symfony_Standard_$VERSION.tgz Symfony
rm -f $DIR/Symfony_Standard_$VERSION.zip
zip -rq $DIR/Symfony_Standard_$VERSION.zip Symfony

View File

@@ -0,0 +1,59 @@
#!/usr/bin/env php
<?php
/*
* This file is part of the Symfony Standard Edition.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Sensio\Bundle\DistributionBundle\Composer\ScriptHandler;
if (PHP_SAPI !== 'cli') {
echo 'Warning: '.__FILE__.' should be invoked via the CLI version of PHP, not the '.PHP_SAPI.' SAPI'.PHP_EOL;
}
function getRealpath($path, $message = 'Directory %s does not seem to be valid.')
{
if (!$path = realpath($path)) {
exit(sprintf($message, $path));
}
return $path;
}
$argv = $_SERVER['argv'];
$autoloadDir = $bootstrapDir = null;
$useNewDirectoryStructure = false;
// allow the base path to be passed as the first argument, or default
if (!empty($argv[1])) {
$bootstrapDir = getRealpath($argv[1]);
}
if (!empty($argv[2])) {
$autoloadDir = getRealpath($argv[2]);
}
if (!empty($argv[3])) {
$useNewDirectoryStructure = true;
}
$rootDir = __DIR__.'/../../../../..';
if (null === $autoloadDir) {
$autoloadDir = getRealpath($rootDir.'/app', 'Looks like you don\'t have a standard layout.');
}
if (null === $bootstrapDir) {
$bootstrapDir = $autoloadDir;
if ($useNewDirectoryStructure) {
$bootstrapDir = getRealpath($rootDir.'/var');
}
}
require_once $autoloadDir.'/autoload.php';
// here we pass realpaths as resolution between absolute and relative path can be wrong
ScriptHandler::doBuildBootstrap($bootstrapDir);

View File

@@ -0,0 +1,112 @@
#!/bin/bash
# This file is part of the Symfony Standard Edition.
#
# (c) Fabien Potencier <fabien@symfony.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
if [ ! $1 ]; then
echo "\033[37;41mYou must pass the build dir as an absolute path\033[0m"
exit 1
fi
DIR=$1
CURRENT=`php -r "echo realpath(dirname(\\$_SERVER['argv'][0]));"`
if [[ ! "$DIR" = /* ]]; then
DIR="$CURRENT/$DIR"
fi
if [ ! -d $DIR ]; then
echo "\033[37;41mThe build dir does not exist\033[0m"
exit 1
fi
# avoid the creation of ._* files
export COPY_EXTENDED_ATTRIBUTES_DISABLE=true
export COPYFILE_DISABLE=true
# Prepare temp. dir
rm -rf /tmp/Symfony
mkdir /tmp/Symfony
# Clone demo application and install its dependencies
git clone https://github.com/symfony/symfony-demo /tmp/Symfony
cd /tmp/Symfony
composer install --prefer-dist --no-interaction --ignore-platform-reqs --no-plugins --optimize-autoloader
# cleanup
cd /tmp/Symfony
rm -f UPGRADE*
mv .gitignore keep.gitignore
rm -rf app/cache/* app/logs/* .git*
mv keep.gitignore .gitignore
chmod 777 app/cache app/logs
find . -name .DS_Store | xargs rm -rf -
# remove unneded dependencies files
cd /tmp/Symfony
TARGET=/tmp/Symfony/vendor
# Doctrine
cd $TARGET/doctrine/orm && rm -rf UPGRADE* build* bin tests tools lib/vendor
cd $TARGET/doctrine/dbal && rm -rf bin build* tests lib/vendor
cd $TARGET/doctrine/common && rm -rf build* tests lib/vendor
if [ -d $TARGET/doctrine/doctrine-bundle/Doctrine/Bundle/DoctrineBundle ]; then
cd $TARGET/doctrine/doctrine-bundle/Doctrine/Bundle/DoctrineBundle && rm -rf Tests Resources/doc
else
cd $TARGET/doctrine/doctrine-bundle && rm -rf Tests Resources/doc
fi
# kriswallsmith
cd $TARGET/kriswallsmith/assetic && rm -rf CHANGELOG* phpunit.xml* tests docs
# Monolog
cd $TARGET/monolog/monolog && rm -rf README.markdown phpunit.xml* tests
# Sensio
cd $TARGET/sensio/distribution-bundle/Sensio/Bundle/DistributionBundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc
cd $TARGET/sensio/framework-extra-bundle/Sensio/Bundle/FrameworkExtraBundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc
cd $TARGET/sensio/generator-bundle/Sensio/Bundle/GeneratorBundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc
# Swiftmailer
cd $TARGET/swiftmailer/swiftmailer && rm -rf CHANGES README* build* docs notes test-suite tests create_pear_package.php package*
# Symfony
cd $TARGET/symfony/symfony && rm -rf README.md phpunit.xml* tests *.sh vendor
if [ -d $TARGET/symfony/assetic-bundle/Symfony/Bundle/AsseticBundle ]; then
cd $TARGET/symfony/assetic-bundle/Symfony/Bundle/AsseticBundle && rm -rf Tests Resources/doc
else
cd $TARGET/symfony/assetic-bundle && rm -rf Tests Resources/doc
fi
if [ -d $TARGET/symfony/swiftmailer-bundle/Symfony/Bundle/SwiftmailerBundle ]; then
cd $TARGET/symfony/swiftmailer-bundle/Symfony/Bundle/SwiftmailerBundle && rm -rf Tests Resources/doc
else
cd $TARGET/symfony/swiftmailer-bundle && rm -rf Tests Resources/doc
fi
if [ -d $TARGET/symfony/monolog-bundle/Symfony/Bundle/MonologBundle ]; then
cd $TARGET/symfony/monolog-bundle/Symfony/Bundle/MonologBundle && rm -rf Tests Resources/doc
else
cd $TARGET/symfony/monolog-bundle && rm -rf Tests Resources/doc
fi
# Twig
cd $TARGET/twig/twig && rm -rf AUTHORS CHANGELOG README.markdown bin doc package.xml.tpl phpunit.xml* test
cd $TARGET/twig/extensions && rm -rf README doc phpunit.xml* test
# final cleanup
find $TARGET -name .git | xargs rm -rf -
find $TARGET -name .gitignore | xargs rm -rf -
find $TARGET -name .gitmodules | xargs rm -rf -
find $TARGET -name .svn | xargs rm -rf -
# build ZIP and TGZ packages
cd /tmp
tar zcpf $DIR/Symfony_Demo.tgz Symfony
rm -f $DIR/Symfony_Demo.zip
zip -rq $DIR/Symfony_Demo.zip Symfony

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="sensio_distribution.security_checker" class="SensioLabs\Security\SecurityChecker" />
<service id="sensio_distribution.security_checker.command" class="SensioLabs\Security\Command\SecurityCheckerCommand">
<argument type="service" id="sensio_distribution.security_checker" />
<tag name="console.command" />
</service>
</services>
</container>

View File

@@ -0,0 +1,810 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/*
* Users of PHP 5.2 should be able to run the requirements checks.
* This is why the file and all classes must be compatible with PHP 5.2+
* (e.g. not using namespaces and closures).
*
* ************** CAUTION **************
*
* DO NOT EDIT THIS FILE as it will be overridden by Composer as part of
* the installation/update process. The original file resides in the
* SensioDistributionBundle.
*
* ************** CAUTION **************
*/
/**
* Represents a single PHP requirement, e.g. an installed extension.
* It can be a mandatory requirement or an optional recommendation.
* There is a special subclass, named PhpIniRequirement, to check a php.ini configuration.
*
* @author Tobias Schultze <http://tobion.de>
*/
class Requirement
{
private $fulfilled;
private $testMessage;
private $helpText;
private $helpHtml;
private $optional;
/**
* Constructor that initializes the requirement.
*
* @param bool $fulfilled Whether the requirement is fulfilled
* @param string $testMessage The message for testing the requirement
* @param string $helpHtml The help text formatted in HTML for resolving the problem
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
* @param bool $optional Whether this is only an optional recommendation not a mandatory requirement
*/
public function __construct($fulfilled, $testMessage, $helpHtml, $helpText = null, $optional = false)
{
$this->fulfilled = (bool) $fulfilled;
$this->testMessage = (string) $testMessage;
$this->helpHtml = (string) $helpHtml;
$this->helpText = null === $helpText ? strip_tags($this->helpHtml) : (string) $helpText;
$this->optional = (bool) $optional;
}
/**
* Returns whether the requirement is fulfilled.
*
* @return bool true if fulfilled, otherwise false
*/
public function isFulfilled()
{
return $this->fulfilled;
}
/**
* Returns the message for testing the requirement.
*
* @return string The test message
*/
public function getTestMessage()
{
return $this->testMessage;
}
/**
* Returns the help text for resolving the problem.
*
* @return string The help text
*/
public function getHelpText()
{
return $this->helpText;
}
/**
* Returns the help text formatted in HTML.
*
* @return string The HTML help
*/
public function getHelpHtml()
{
return $this->helpHtml;
}
/**
* Returns whether this is only an optional recommendation and not a mandatory requirement.
*
* @return bool true if optional, false if mandatory
*/
public function isOptional()
{
return $this->optional;
}
}
/**
* Represents a PHP requirement in form of a php.ini configuration.
*
* @author Tobias Schultze <http://tobion.de>
*/
class PhpIniRequirement extends Requirement
{
/**
* Constructor that initializes the requirement.
*
* @param string $cfgName The configuration name used for ini_get()
* @param bool|callback $evaluation Either a boolean indicating whether the configuration should evaluate to true or false,
* or a callback function receiving the configuration value as parameter to determine the fulfillment of the requirement
* @param bool $approveCfgAbsence If true the Requirement will be fulfilled even if the configuration option does not exist, i.e. ini_get() returns false.
* This is helpful for abandoned configs in later PHP versions or configs of an optional extension, like Suhosin.
* Example: You require a config to be true but PHP later removes this config and defaults it to true internally.
* @param string|null $testMessage The message for testing the requirement (when null and $evaluation is a boolean a default message is derived)
* @param string|null $helpHtml The help text formatted in HTML for resolving the problem (when null and $evaluation is a boolean a default help is derived)
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
* @param bool $optional Whether this is only an optional recommendation not a mandatory requirement
*/
public function __construct($cfgName, $evaluation, $approveCfgAbsence = false, $testMessage = null, $helpHtml = null, $helpText = null, $optional = false)
{
$cfgValue = ini_get($cfgName);
if (is_callable($evaluation)) {
if (null === $testMessage || null === $helpHtml) {
throw new InvalidArgumentException('You must provide the parameters testMessage and helpHtml for a callback evaluation.');
}
$fulfilled = call_user_func($evaluation, $cfgValue);
} else {
if (null === $testMessage) {
$testMessage = sprintf('%s %s be %s in php.ini',
$cfgName,
$optional ? 'should' : 'must',
$evaluation ? 'enabled' : 'disabled'
);
}
if (null === $helpHtml) {
$helpHtml = sprintf('Set <strong>%s</strong> to <strong>%s</strong> in php.ini<a href="#phpini">*</a>.',
$cfgName,
$evaluation ? 'on' : 'off'
);
}
$fulfilled = $evaluation == $cfgValue;
}
parent::__construct($fulfilled || ($approveCfgAbsence && false === $cfgValue), $testMessage, $helpHtml, $helpText, $optional);
}
}
/**
* A RequirementCollection represents a set of Requirement instances.
*
* @author Tobias Schultze <http://tobion.de>
*/
class RequirementCollection implements IteratorAggregate
{
/**
* @var Requirement[]
*/
private $requirements = array();
/**
* Gets the current RequirementCollection as an Iterator.
*
* @return Traversable A Traversable interface
*/
public function getIterator()
{
return new ArrayIterator($this->requirements);
}
/**
* Adds a Requirement.
*
* @param Requirement $requirement A Requirement instance
*/
public function add(Requirement $requirement)
{
$this->requirements[] = $requirement;
}
/**
* Adds a mandatory requirement.
*
* @param bool $fulfilled Whether the requirement is fulfilled
* @param string $testMessage The message for testing the requirement
* @param string $helpHtml The help text formatted in HTML for resolving the problem
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
*/
public function addRequirement($fulfilled, $testMessage, $helpHtml, $helpText = null)
{
$this->add(new Requirement($fulfilled, $testMessage, $helpHtml, $helpText, false));
}
/**
* Adds an optional recommendation.
*
* @param bool $fulfilled Whether the recommendation is fulfilled
* @param string $testMessage The message for testing the recommendation
* @param string $helpHtml The help text formatted in HTML for resolving the problem
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
*/
public function addRecommendation($fulfilled, $testMessage, $helpHtml, $helpText = null)
{
$this->add(new Requirement($fulfilled, $testMessage, $helpHtml, $helpText, true));
}
/**
* Adds a mandatory requirement in form of a php.ini configuration.
*
* @param string $cfgName The configuration name used for ini_get()
* @param bool|callback $evaluation Either a boolean indicating whether the configuration should evaluate to true or false,
* or a callback function receiving the configuration value as parameter to determine the fulfillment of the requirement
* @param bool $approveCfgAbsence If true the Requirement will be fulfilled even if the configuration option does not exist, i.e. ini_get() returns false.
* This is helpful for abandoned configs in later PHP versions or configs of an optional extension, like Suhosin.
* Example: You require a config to be true but PHP later removes this config and defaults it to true internally.
* @param string $testMessage The message for testing the requirement (when null and $evaluation is a boolean a default message is derived)
* @param string $helpHtml The help text formatted in HTML for resolving the problem (when null and $evaluation is a boolean a default help is derived)
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
*/
public function addPhpIniRequirement($cfgName, $evaluation, $approveCfgAbsence = false, $testMessage = null, $helpHtml = null, $helpText = null)
{
$this->add(new PhpIniRequirement($cfgName, $evaluation, $approveCfgAbsence, $testMessage, $helpHtml, $helpText, false));
}
/**
* Adds an optional recommendation in form of a php.ini configuration.
*
* @param string $cfgName The configuration name used for ini_get()
* @param bool|callback $evaluation Either a boolean indicating whether the configuration should evaluate to true or false,
* or a callback function receiving the configuration value as parameter to determine the fulfillment of the requirement
* @param bool $approveCfgAbsence If true the Requirement will be fulfilled even if the configuration option does not exist, i.e. ini_get() returns false.
* This is helpful for abandoned configs in later PHP versions or configs of an optional extension, like Suhosin.
* Example: You require a config to be true but PHP later removes this config and defaults it to true internally.
* @param string $testMessage The message for testing the requirement (when null and $evaluation is a boolean a default message is derived)
* @param string $helpHtml The help text formatted in HTML for resolving the problem (when null and $evaluation is a boolean a default help is derived)
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
*/
public function addPhpIniRecommendation($cfgName, $evaluation, $approveCfgAbsence = false, $testMessage = null, $helpHtml = null, $helpText = null)
{
$this->add(new PhpIniRequirement($cfgName, $evaluation, $approveCfgAbsence, $testMessage, $helpHtml, $helpText, true));
}
/**
* Adds a requirement collection to the current set of requirements.
*
* @param RequirementCollection $collection A RequirementCollection instance
*/
public function addCollection(RequirementCollection $collection)
{
$this->requirements = array_merge($this->requirements, $collection->all());
}
/**
* Returns both requirements and recommendations.
*
* @return Requirement[]
*/
public function all()
{
return $this->requirements;
}
/**
* Returns all mandatory requirements.
*
* @return Requirement[]
*/
public function getRequirements()
{
$array = array();
foreach ($this->requirements as $req) {
if (!$req->isOptional()) {
$array[] = $req;
}
}
return $array;
}
/**
* Returns the mandatory requirements that were not met.
*
* @return Requirement[]
*/
public function getFailedRequirements()
{
$array = array();
foreach ($this->requirements as $req) {
if (!$req->isFulfilled() && !$req->isOptional()) {
$array[] = $req;
}
}
return $array;
}
/**
* Returns all optional recommendations.
*
* @return Requirement[]
*/
public function getRecommendations()
{
$array = array();
foreach ($this->requirements as $req) {
if ($req->isOptional()) {
$array[] = $req;
}
}
return $array;
}
/**
* Returns the recommendations that were not met.
*
* @return Requirement[]
*/
public function getFailedRecommendations()
{
$array = array();
foreach ($this->requirements as $req) {
if (!$req->isFulfilled() && $req->isOptional()) {
$array[] = $req;
}
}
return $array;
}
/**
* Returns whether a php.ini configuration is not correct.
*
* @return bool php.ini configuration problem?
*/
public function hasPhpIniConfigIssue()
{
foreach ($this->requirements as $req) {
if (!$req->isFulfilled() && $req instanceof PhpIniRequirement) {
return true;
}
}
return false;
}
/**
* Returns the PHP configuration file (php.ini) path.
*
* @return string|false php.ini file path
*/
public function getPhpIniConfigPath()
{
return get_cfg_var('cfg_file_path');
}
}
/**
* This class specifies all requirements and optional recommendations that
* are necessary to run the Symfony Standard Edition.
*
* @author Tobias Schultze <http://tobion.de>
* @author Fabien Potencier <fabien@symfony.com>
*/
class SymfonyRequirements extends RequirementCollection
{
const LEGACY_REQUIRED_PHP_VERSION = '5.3.3';
const REQUIRED_PHP_VERSION = '5.5.9';
/**
* Constructor that initializes the requirements.
*/
public function __construct()
{
/* mandatory requirements follow */
$installedPhpVersion = PHP_VERSION;
$requiredPhpVersion = $this->getPhpRequiredVersion();
$this->addRecommendation(
$requiredPhpVersion,
'Vendors should be installed in order to check all requirements.',
'Run the <code>composer install</code> command.',
'Run the "composer install" command.'
);
if (false !== $requiredPhpVersion) {
$this->addRequirement(
version_compare($installedPhpVersion, $requiredPhpVersion, '>='),
sprintf('PHP version must be at least %s (%s installed)', $requiredPhpVersion, $installedPhpVersion),
sprintf('You are running PHP version "<strong>%s</strong>", but Symfony needs at least PHP "<strong>%s</strong>" to run.
Before using Symfony, upgrade your PHP installation, preferably to the latest version.',
$installedPhpVersion, $requiredPhpVersion),
sprintf('Install PHP %s or newer (installed version is %s)', $requiredPhpVersion, $installedPhpVersion)
);
}
$this->addRequirement(
version_compare($installedPhpVersion, '5.3.16', '!='),
'PHP version must not be 5.3.16 as Symfony won\'t work properly with it',
'Install PHP 5.3.17 or newer (or downgrade to an earlier PHP version)'
);
$this->addRequirement(
is_dir(__DIR__.'/../vendor/composer'),
'Vendor libraries must be installed',
'Vendor libraries are missing. Install composer following instructions from <a href="http://getcomposer.org/">http://getcomposer.org/</a>. '.
'Then run "<strong>php composer.phar install</strong>" to install them.'
);
$cacheDir = is_dir(__DIR__.'/../var/cache') ? __DIR__.'/../var/cache' : __DIR__.'/cache';
$this->addRequirement(
is_writable($cacheDir),
'app/cache/ or var/cache/ directory must be writable',
'Change the permissions of either "<strong>app/cache/</strong>" or "<strong>var/cache/</strong>" directory so that the web server can write into it.'
);
$logsDir = is_dir(__DIR__.'/../var/logs') ? __DIR__.'/../var/logs' : __DIR__.'/logs';
$this->addRequirement(
is_writable($logsDir),
'app/logs/ or var/logs/ directory must be writable',
'Change the permissions of either "<strong>app/logs/</strong>" or "<strong>var/logs/</strong>" directory so that the web server can write into it.'
);
if (version_compare($installedPhpVersion, '7.0.0', '<')) {
$this->addPhpIniRequirement(
'date.timezone', true, false,
'date.timezone setting must be set',
'Set the "<strong>date.timezone</strong>" setting in php.ini<a href="#phpini">*</a> (like Europe/Paris).'
);
}
if (false !== $requiredPhpVersion && version_compare($installedPhpVersion, $requiredPhpVersion, '>=')) {
$this->addRequirement(
in_array(@date_default_timezone_get(), DateTimeZone::listIdentifiers(), true),
sprintf('Configured default timezone "%s" must be supported by your installation of PHP', @date_default_timezone_get()),
'Your default timezone is not supported by PHP. Check for typos in your <strong>php.ini</strong> file and have a look at the list of deprecated timezones at <a href="http://php.net/manual/en/timezones.others.php">http://php.net/manual/en/timezones.others.php</a>.'
);
}
$this->addRequirement(
function_exists('iconv'),
'iconv() must be available',
'Install and enable the <strong>iconv</strong> extension.'
);
$this->addRequirement(
function_exists('json_encode'),
'json_encode() must be available',
'Install and enable the <strong>JSON</strong> extension.'
);
$this->addRequirement(
function_exists('session_start'),
'session_start() must be available',
'Install and enable the <strong>session</strong> extension.'
);
$this->addRequirement(
function_exists('ctype_alpha'),
'ctype_alpha() must be available',
'Install and enable the <strong>ctype</strong> extension.'
);
$this->addRequirement(
function_exists('token_get_all'),
'token_get_all() must be available',
'Install and enable the <strong>Tokenizer</strong> extension.'
);
$this->addRequirement(
function_exists('simplexml_import_dom'),
'simplexml_import_dom() must be available',
'Install and enable the <strong>SimpleXML</strong> extension.'
);
if (function_exists('apc_store') && ini_get('apc.enabled')) {
if (version_compare($installedPhpVersion, '5.4.0', '>=')) {
$this->addRequirement(
version_compare(phpversion('apc'), '3.1.13', '>='),
'APC version must be at least 3.1.13 when using PHP 5.4',
'Upgrade your <strong>APC</strong> extension (3.1.13+).'
);
} else {
$this->addRequirement(
version_compare(phpversion('apc'), '3.0.17', '>='),
'APC version must be at least 3.0.17',
'Upgrade your <strong>APC</strong> extension (3.0.17+).'
);
}
}
$this->addPhpIniRequirement('detect_unicode', false);
if (extension_loaded('suhosin')) {
$this->addPhpIniRequirement(
'suhosin.executor.include.whitelist',
create_function('$cfgValue', 'return false !== stripos($cfgValue, "phar");'),
false,
'suhosin.executor.include.whitelist must be configured correctly in php.ini',
'Add "<strong>phar</strong>" to <strong>suhosin.executor.include.whitelist</strong> in php.ini<a href="#phpini">*</a>.'
);
}
if (extension_loaded('xdebug')) {
$this->addPhpIniRequirement(
'xdebug.show_exception_trace', false, true
);
$this->addPhpIniRequirement(
'xdebug.scream', false, true
);
$this->addPhpIniRecommendation(
'xdebug.max_nesting_level',
create_function('$cfgValue', 'return $cfgValue > 100;'),
true,
'xdebug.max_nesting_level should be above 100 in php.ini',
'Set "<strong>xdebug.max_nesting_level</strong>" to e.g. "<strong>250</strong>" in php.ini<a href="#phpini">*</a> to stop Xdebug\'s infinite recursion protection erroneously throwing a fatal error in your project.'
);
}
$pcreVersion = defined('PCRE_VERSION') ? (float) PCRE_VERSION : null;
$this->addRequirement(
null !== $pcreVersion,
'PCRE extension must be available',
'Install the <strong>PCRE</strong> extension (version 8.0+).'
);
if (extension_loaded('mbstring')) {
$this->addPhpIniRequirement(
'mbstring.func_overload',
create_function('$cfgValue', 'return (int) $cfgValue === 0;'),
true,
'string functions should not be overloaded',
'Set "<strong>mbstring.func_overload</strong>" to <strong>0</strong> in php.ini<a href="#phpini">*</a> to disable function overloading by the mbstring extension.'
);
}
/* optional recommendations follow */
if (file_exists(__DIR__.'/../vendor/composer')) {
require_once __DIR__.'/../vendor/autoload.php';
try {
$r = new ReflectionClass('Sensio\Bundle\DistributionBundle\SensioDistributionBundle');
$contents = file_get_contents(dirname($r->getFileName()).'/Resources/skeleton/app/SymfonyRequirements.php');
} catch (ReflectionException $e) {
$contents = '';
}
$this->addRecommendation(
file_get_contents(__FILE__) === $contents,
'Requirements file should be up-to-date',
'Your requirements file is outdated. Run composer install and re-check your configuration.'
);
}
$this->addRecommendation(
version_compare($installedPhpVersion, '5.3.4', '>='),
'You should use at least PHP 5.3.4 due to PHP bug #52083 in earlier versions',
'Your project might malfunction randomly due to PHP bug #52083 ("Notice: Trying to get property of non-object"). Install PHP 5.3.4 or newer.'
);
$this->addRecommendation(
version_compare($installedPhpVersion, '5.3.8', '>='),
'When using annotations you should have at least PHP 5.3.8 due to PHP bug #55156',
'Install PHP 5.3.8 or newer if your project uses annotations.'
);
$this->addRecommendation(
version_compare($installedPhpVersion, '5.4.0', '!='),
'You should not use PHP 5.4.0 due to the PHP bug #61453',
'Your project might not work properly due to the PHP bug #61453 ("Cannot dump definitions which have method calls"). Install PHP 5.4.1 or newer.'
);
$this->addRecommendation(
version_compare($installedPhpVersion, '5.4.11', '>='),
'When using the logout handler from the Symfony Security Component, you should have at least PHP 5.4.11 due to PHP bug #63379 (as a workaround, you can also set invalidate_session to false in the security logout handler configuration)',
'Install PHP 5.4.11 or newer if your project uses the logout handler from the Symfony Security Component.'
);
$this->addRecommendation(
(version_compare($installedPhpVersion, '5.3.18', '>=') && version_compare($installedPhpVersion, '5.4.0', '<'))
||
version_compare($installedPhpVersion, '5.4.8', '>='),
'You should use PHP 5.3.18+ or PHP 5.4.8+ to always get nice error messages for fatal errors in the development environment due to PHP bug #61767/#60909',
'Install PHP 5.3.18+ or PHP 5.4.8+ if you want nice error messages for all fatal errors in the development environment.'
);
if (null !== $pcreVersion) {
$this->addRecommendation(
$pcreVersion >= 8.0,
sprintf('PCRE extension should be at least version 8.0 (%s installed)', $pcreVersion),
'<strong>PCRE 8.0+</strong> is preconfigured in PHP since 5.3.2 but you are using an outdated version of it. Symfony probably works anyway but it is recommended to upgrade your PCRE extension.'
);
}
$this->addRecommendation(
class_exists('DomDocument'),
'PHP-DOM and PHP-XML modules should be installed',
'Install and enable the <strong>PHP-DOM</strong> and the <strong>PHP-XML</strong> modules.'
);
$this->addRecommendation(
function_exists('mb_strlen'),
'mb_strlen() should be available',
'Install and enable the <strong>mbstring</strong> extension.'
);
$this->addRecommendation(
function_exists('utf8_decode'),
'utf8_decode() should be available',
'Install and enable the <strong>XML</strong> extension.'
);
$this->addRecommendation(
function_exists('filter_var'),
'filter_var() should be available',
'Install and enable the <strong>filter</strong> extension.'
);
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->addRecommendation(
function_exists('posix_isatty'),
'posix_isatty() should be available',
'Install and enable the <strong>php_posix</strong> extension (used to colorize the CLI output).'
);
}
$this->addRecommendation(
extension_loaded('intl'),
'intl extension should be available',
'Install and enable the <strong>intl</strong> extension (used for validators).'
);
if (extension_loaded('intl')) {
// in some WAMP server installations, new Collator() returns null
$this->addRecommendation(
null !== new Collator('fr_FR'),
'intl extension should be correctly configured',
'The intl extension does not behave properly. This problem is typical on PHP 5.3.X x64 WIN builds.'
);
// check for compatible ICU versions (only done when you have the intl extension)
if (defined('INTL_ICU_VERSION')) {
$version = INTL_ICU_VERSION;
} else {
$reflector = new ReflectionExtension('intl');
ob_start();
$reflector->info();
$output = strip_tags(ob_get_clean());
preg_match('/^ICU version +(?:=> )?(.*)$/m', $output, $matches);
$version = $matches[1];
}
$this->addRecommendation(
version_compare($version, '4.0', '>='),
'intl ICU version should be at least 4+',
'Upgrade your <strong>intl</strong> extension with a newer ICU version (4+).'
);
if (class_exists('Symfony\Component\Intl\Intl')) {
$this->addRecommendation(
\Symfony\Component\Intl\Intl::getIcuDataVersion() <= \Symfony\Component\Intl\Intl::getIcuVersion(),
sprintf('intl ICU version installed on your system is outdated (%s) and does not match the ICU data bundled with Symfony (%s)', \Symfony\Component\Intl\Intl::getIcuVersion(), \Symfony\Component\Intl\Intl::getIcuDataVersion()),
'To get the latest internationalization data upgrade the ICU system package and the intl PHP extension.'
);
if (\Symfony\Component\Intl\Intl::getIcuDataVersion() <= \Symfony\Component\Intl\Intl::getIcuVersion()) {
$this->addRecommendation(
\Symfony\Component\Intl\Intl::getIcuDataVersion() === \Symfony\Component\Intl\Intl::getIcuVersion(),
sprintf('intl ICU version installed on your system (%s) does not match the ICU data bundled with Symfony (%s)', \Symfony\Component\Intl\Intl::getIcuVersion(), \Symfony\Component\Intl\Intl::getIcuDataVersion()),
'To avoid internationalization data inconsistencies upgrade the symfony/intl component.'
);
}
}
$this->addPhpIniRecommendation(
'intl.error_level',
create_function('$cfgValue', 'return (int) $cfgValue === 0;'),
true,
'intl.error_level should be 0 in php.ini',
'Set "<strong>intl.error_level</strong>" to "<strong>0</strong>" in php.ini<a href="#phpini">*</a> to inhibit the messages when an error occurs in ICU functions.'
);
}
$accelerator =
(extension_loaded('eaccelerator') && ini_get('eaccelerator.enable'))
||
(extension_loaded('apc') && ini_get('apc.enabled'))
||
(extension_loaded('Zend Optimizer+') && ini_get('zend_optimizerplus.enable'))
||
(extension_loaded('Zend OPcache') && ini_get('opcache.enable'))
||
(extension_loaded('xcache') && ini_get('xcache.cacher'))
||
(extension_loaded('wincache') && ini_get('wincache.ocenabled'))
;
$this->addRecommendation(
$accelerator,
'a PHP accelerator should be installed',
'Install and/or enable a <strong>PHP accelerator</strong> (highly recommended).'
);
if ('WIN' === strtoupper(substr(PHP_OS, 0, 3))) {
$this->addRecommendation(
$this->getRealpathCacheSize() >= 5 * 1024 * 1024,
'realpath_cache_size should be at least 5M in php.ini',
'Setting "<strong>realpath_cache_size</strong>" to e.g. "<strong>5242880</strong>" or "<strong>5M</strong>" in php.ini<a href="#phpini">*</a> may improve performance on Windows significantly in some cases.'
);
}
$this->addPhpIniRecommendation('short_open_tag', false);
$this->addPhpIniRecommendation('magic_quotes_gpc', false, true);
$this->addPhpIniRecommendation('register_globals', false, true);
$this->addPhpIniRecommendation('session.auto_start', false);
$this->addRecommendation(
class_exists('PDO'),
'PDO should be installed',
'Install <strong>PDO</strong> (mandatory for Doctrine).'
);
if (class_exists('PDO')) {
$drivers = PDO::getAvailableDrivers();
$this->addRecommendation(
count($drivers) > 0,
sprintf('PDO should have some drivers installed (currently available: %s)', count($drivers) ? implode(', ', $drivers) : 'none'),
'Install <strong>PDO drivers</strong> (mandatory for Doctrine).'
);
}
}
/**
* Loads realpath_cache_size from php.ini and converts it to int.
*
* (e.g. 16k is converted to 16384 int)
*
* @return int
*/
protected function getRealpathCacheSize()
{
$size = ini_get('realpath_cache_size');
$size = trim($size);
$unit = '';
if (!ctype_digit($size)) {
$unit = strtolower(substr($size, -1, 1));
$size = (int) substr($size, 0, -1);
}
switch ($unit) {
case 'g':
return $size * 1024 * 1024 * 1024;
case 'm':
return $size * 1024 * 1024;
case 'k':
return $size * 1024;
default:
return (int) $size;
}
}
/**
* Defines PHP required version from Symfony version.
*
* @return string|false The PHP required version or false if it could not be guessed
*/
protected function getPhpRequiredVersion()
{
if (!file_exists($path = __DIR__.'/../composer.lock')) {
return false;
}
$composerLock = json_decode(file_get_contents($path), true);
foreach ($composerLock['packages'] as $package) {
$name = $package['name'];
if ('symfony/symfony' !== $name && 'symfony/http-kernel' !== $name) {
continue;
}
return (int) $package['version'][1] > 2 ? self::REQUIRED_PHP_VERSION : self::LEGACY_REQUIRED_PHP_VERSION;
}
return false;
}
}

View File

@@ -0,0 +1,145 @@
<?php
require_once dirname(__FILE__).'/SymfonyRequirements.php';
$lineSize = 70;
$symfonyRequirements = new SymfonyRequirements();
$iniPath = $symfonyRequirements->getPhpIniConfigPath();
echo_title('Symfony Requirements Checker');
echo '> PHP is using the following php.ini file:'.PHP_EOL;
if ($iniPath) {
echo_style('green', ' '.$iniPath);
} else {
echo_style('yellow', ' WARNING: No configuration file (php.ini) used by PHP!');
}
echo PHP_EOL.PHP_EOL;
echo '> Checking Symfony requirements:'.PHP_EOL.' ';
$messages = array();
foreach ($symfonyRequirements->getRequirements() as $req) {
if ($helpText = get_error_message($req, $lineSize)) {
echo_style('red', 'E');
$messages['error'][] = $helpText;
} else {
echo_style('green', '.');
}
}
$checkPassed = empty($messages['error']);
foreach ($symfonyRequirements->getRecommendations() as $req) {
if ($helpText = get_error_message($req, $lineSize)) {
echo_style('yellow', 'W');
$messages['warning'][] = $helpText;
} else {
echo_style('green', '.');
}
}
if ($checkPassed) {
echo_block('success', 'OK', 'Your system is ready to run Symfony projects');
} else {
echo_block('error', 'ERROR', 'Your system is not ready to run Symfony projects');
echo_title('Fix the following mandatory requirements', 'red');
foreach ($messages['error'] as $helpText) {
echo ' * '.$helpText.PHP_EOL;
}
}
if (!empty($messages['warning'])) {
echo_title('Optional recommendations to improve your setup', 'yellow');
foreach ($messages['warning'] as $helpText) {
echo ' * '.$helpText.PHP_EOL;
}
}
echo PHP_EOL;
echo_style('title', 'Note');
echo ' The command console could use a different php.ini file'.PHP_EOL;
echo_style('title', '~~~~');
echo ' than the one used with your web server. To be on the'.PHP_EOL;
echo ' safe side, please check the requirements from your web'.PHP_EOL;
echo ' server using the ';
echo_style('yellow', 'web/config.php');
echo ' script.'.PHP_EOL;
echo PHP_EOL;
exit($checkPassed ? 0 : 1);
function get_error_message(Requirement $requirement, $lineSize)
{
if ($requirement->isFulfilled()) {
return;
}
$errorMessage = wordwrap($requirement->getTestMessage(), $lineSize - 3, PHP_EOL.' ').PHP_EOL;
$errorMessage .= ' > '.wordwrap($requirement->getHelpText(), $lineSize - 5, PHP_EOL.' > ').PHP_EOL;
return $errorMessage;
}
function echo_title($title, $style = null)
{
$style = $style ?: 'title';
echo PHP_EOL;
echo_style($style, $title.PHP_EOL);
echo_style($style, str_repeat('~', strlen($title)).PHP_EOL);
echo PHP_EOL;
}
function echo_style($style, $message)
{
// ANSI color codes
$styles = array(
'reset' => "\033[0m",
'red' => "\033[31m",
'green' => "\033[32m",
'yellow' => "\033[33m",
'error' => "\033[37;41m",
'success' => "\033[37;42m",
'title' => "\033[34m",
);
$supports = has_color_support();
echo($supports ? $styles[$style] : '').$message.($supports ? $styles['reset'] : '');
}
function echo_block($style, $title, $message)
{
$message = ' '.trim($message).' ';
$width = strlen($message);
echo PHP_EOL.PHP_EOL;
echo_style($style, str_repeat(' ', $width));
echo PHP_EOL;
echo_style($style, str_pad(' ['.$title.']', $width, ' ', STR_PAD_RIGHT));
echo PHP_EOL;
echo_style($style, $message);
echo PHP_EOL;
echo_style($style, str_repeat(' ', $width));
echo PHP_EOL;
}
function has_color_support()
{
static $support;
if (null === $support) {
if (DIRECTORY_SEPARATOR == '\\') {
$support = false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI');
} else {
$support = function_exists('posix_isatty') && @posix_isatty(STDOUT);
}
}
return $support;
}

View File

@@ -0,0 +1,25 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\DistributionBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* SensioDistributionBundle.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Marc Weistroff <marc.weistroff@sensio.com>
* @author Jérôme Vieilledent <lolautruche@gmail.com>
*/
class SensioDistributionBundle extends Bundle
{
}

View File

@@ -0,0 +1,299 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Configuration;
/**
* The Cache class handles the Cache annotation parts.
*
* @author Fabien Potencier <fabien@symfony.com>
* @Annotation
*/
class Cache extends ConfigurationAnnotation
{
/**
* The expiration date as a valid date for the strtotime() function.
*
* @var string
*/
private $expires;
/**
* The number of seconds that the response is considered fresh by a private
* cache like a web browser.
*
* @var int
*/
private $maxage;
/**
* The number of seconds that the response is considered fresh by a public
* cache like a reverse proxy cache.
*
* @var int
*/
private $smaxage;
/**
* Whether the response is public or not.
*
* @var bool
*/
private $public;
/**
* Whether or not the response must be revalidated.
*
* @var bool
*/
private $mustRevalidate;
/**
* Additional "Vary:"-headers.
*
* @var array
*/
private $vary;
/**
* An expression to compute the Last-Modified HTTP header.
*
* @var string
*/
private $lastModified;
/**
* An expression to compute the ETag HTTP header.
*
* @var string
*/
private $etag;
/**
* max-stale Cache-Control header
* It can be expressed in seconds or with a relative time format (1 day, 2 weeks, ...).
*
* @var int|string
*/
private $maxStale;
/**
* Returns the expiration date for the Expires header field.
*
* @return string
*/
public function getExpires()
{
return $this->expires;
}
/**
* Sets the expiration date for the Expires header field.
*
* @param string $expires A valid php date
*/
public function setExpires($expires)
{
$this->expires = $expires;
}
/**
* Sets the number of seconds for the max-age cache-control header field.
*
* @param int $maxage A number of seconds
*/
public function setMaxAge($maxage)
{
$this->maxage = $maxage;
}
/**
* Returns the number of seconds the response is considered fresh by a
* private cache.
*
* @return int
*/
public function getMaxAge()
{
return $this->maxage;
}
/**
* Sets the number of seconds for the s-maxage cache-control header field.
*
* @param int $smaxage A number of seconds
*/
public function setSMaxAge($smaxage)
{
$this->smaxage = $smaxage;
}
/**
* Returns the number of seconds the response is considered fresh by a
* public cache.
*
* @return int
*/
public function getSMaxAge()
{
return $this->smaxage;
}
/**
* Returns whether or not a response is public.
*
* @return bool
*/
public function isPublic()
{
return true === $this->public;
}
/**
* @return bool
*/
public function mustRevalidate()
{
return true === $this->mustRevalidate;
}
/**
* Forces a response to be revalidated.
*
* @param bool $mustRevalidate
*/
public function setMustRevalidate($mustRevalidate)
{
$this->mustRevalidate = (bool) $mustRevalidate;
}
/**
* Returns whether or not a response is private.
*
* @return bool
*/
public function isPrivate()
{
return false === $this->public;
}
/**
* Sets a response public.
*
* @param bool $public A boolean value
*/
public function setPublic($public)
{
$this->public = (bool) $public;
}
/**
* Returns the custom "Vary"-headers.
*
* @return array
*/
public function getVary()
{
return $this->vary;
}
/**
* Add additional "Vary:"-headers.
*
* @param array $vary
*/
public function setVary($vary)
{
$this->vary = $vary;
}
/**
* Sets the "Last-Modified"-header expression.
*
* @param string $expression
*/
public function setLastModified($expression)
{
$this->lastModified = $expression;
}
/**
* Returns the "Last-Modified"-header expression.
*
* @return string
*/
public function getLastModified()
{
return $this->lastModified;
}
/**
* Sets the "ETag"-header expression.
*
* @param string $expression
*/
public function setEtag($expression)
{
$this->etag = $expression;
}
/**
* Returns the "ETag"-header expression.
*
* @return string
*/
public function getEtag()
{
return $this->etag;
}
/**
* @return int|string
*/
public function getMaxStale()
{
return $this->maxStale;
}
/**
* Sets the number of seconds for the max-stale cache-control header field.
*
* @param int|string $maxStale A number of seconds
*/
public function setMaxStale($maxStale)
{
$this->maxStale = $maxStale;
}
/**
* Returns the annotation alias name.
*
* @return string
*
* @see ConfigurationInterface
*/
public function getAliasName()
{
return 'cache';
}
/**
* Only one cache directive is allowed.
*
* @return bool
*
* @see ConfigurationInterface
*/
public function allowArray()
{
return false;
}
}

View File

@@ -0,0 +1,31 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Configuration;
/**
* Base configuration annotation.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
abstract class ConfigurationAnnotation implements ConfigurationInterface
{
public function __construct(array $values)
{
foreach ($values as $k => $v) {
if (!method_exists($this, $name = 'set'.$k)) {
throw new \RuntimeException(sprintf('Unknown key "%s" for annotation "@%s".', $k, \get_class($this)));
}
$this->$name($v);
}
}
}

View File

@@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Configuration;
/**
* ConfigurationInterface.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface ConfigurationInterface
{
/**
* Returns the alias name for an annotated configuration.
*
* @return string
*/
public function getAliasName();
/**
* Returns whether multiple annotations of this type are allowed.
*
* @return bool
*/
public function allowArray();
}

View File

@@ -0,0 +1,29 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Configuration;
/**
* Doctrine-specific ParamConverter with an easier syntax.
*
* @author Ryan Weaver <ryan@knpuniversity.com>
* @Annotation
*/
class Entity extends ParamConverter
{
public function setExpr($expr)
{
$options = $this->getOptions();
$options['expr'] = $expr;
$this->setOptions($options);
}
}

View File

@@ -0,0 +1,107 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Configuration;
/**
* The Security class handles the Security annotation.
*
* @author Ryan Weaver <ryan@knpuniversity.com>
* @Annotation
*/
class IsGranted extends ConfigurationAnnotation
{
/**
* Sets the first argument that will be passed to isGranted().
*
* @var mixed
*/
private $attributes;
/**
* Sets the second argument passed to isGranted().
*
* @var mixed
*/
private $subject;
/**
* The message of the exception - has a nice default if not set.
*
* @var string
*/
private $message;
/**
* If set, will throw Symfony\Component\HttpKernel\Exception\HttpException
* with the given $statusCode.
* If null, Symfony\Component\Security\Core\Exception\AccessDeniedException.
* will be used.
*
* @var int|null
*/
private $statusCode;
public function setAttributes($attributes)
{
$this->attributes = $attributes;
}
public function getAttributes()
{
return $this->attributes;
}
public function setSubject($subject)
{
$this->subject = $subject;
}
public function getSubject()
{
return $this->subject;
}
public function getMessage()
{
return $this->message;
}
public function setMessage($message)
{
$this->message = $message;
}
public function getStatusCode()
{
return $this->statusCode;
}
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
}
public function setValue($value)
{
$this->setAttributes($value);
}
public function getAliasName()
{
return 'is_granted';
}
public function allowArray()
{
return true;
}
}

View File

@@ -0,0 +1,86 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Configuration;
@trigger_error(sprintf('The "%s" annotation is deprecated since version 5.2. Use "%s" instead.', Method::class, \Symfony\Component\Routing\Annotation\Route::class), E_USER_DEPRECATED);
/**
* The Method class handles the Method annotation parts.
*
* @author Fabien Potencier <fabien@symfony.com>
* @Annotation
*
* @deprecated since version 5.2
*/
class Method extends ConfigurationAnnotation
{
/**
* An array of restricted HTTP methods.
*
* @var array
*/
private $methods = [];
/**
* Returns the array of HTTP methods.
*
* @return array
*/
public function getMethods()
{
return $this->methods;
}
/**
* Sets the HTTP methods.
*
* @param array|string $methods An HTTP method or an array of HTTP methods
*/
public function setMethods($methods)
{
$this->methods = \is_array($methods) ? $methods : [$methods];
}
/**
* Sets the HTTP methods.
*
* @param array|string $methods An HTTP method or an array of HTTP methods
*/
public function setValue($methods)
{
$this->setMethods($methods);
}
/**
* Returns the annotation alias name.
*
* @return string
*
* @see ConfigurationInterface
*/
public function getAliasName()
{
return 'method';
}
/**
* Only one method directive is allowed.
*
* @return bool
*
* @see ConfigurationInterface
*/
public function allowArray()
{
return false;
}
}

View File

@@ -0,0 +1,190 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Configuration;
/**
* The ParamConverter class handles the ParamConverter annotation parts.
*
* @author Fabien Potencier <fabien@symfony.com>
* @Annotation
*/
class ParamConverter extends ConfigurationAnnotation
{
/**
* The parameter name.
*
* @var string
*/
private $name;
/**
* The parameter class.
*
* @var string
*/
private $class;
/**
* An array of options.
*
* @var array
*/
private $options = [];
/**
* Whether or not the parameter is optional.
*
* @var bool
*/
private $isOptional = false;
/**
* Use explicitly named converter instead of iterating by priorities.
*
* @var string
*/
private $converter;
/**
* Returns the parameter name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Sets the parameter name.
*
* @param string $name The parameter name
*/
public function setValue($name)
{
$this->setName($name);
}
/**
* Sets the parameter name.
*
* @param string $name The parameter name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Returns the parameter class name.
*
* @return string $name
*/
public function getClass()
{
return $this->class;
}
/**
* Sets the parameter class name.
*
* @param string $class The parameter class name
*/
public function setClass($class)
{
$this->class = $class;
}
/**
* Returns an array of options.
*
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* Sets an array of options.
*
* @param array $options An array of options
*/
public function setOptions($options)
{
$this->options = $options;
}
/**
* Sets whether or not the parameter is optional.
*
* @param bool $optional Whether the parameter is optional
*/
public function setIsOptional($optional)
{
$this->isOptional = (bool) $optional;
}
/**
* Returns whether or not the parameter is optional.
*
* @return bool
*/
public function isOptional()
{
return $this->isOptional;
}
/**
* Get explicit converter name.
*
* @return string
*/
public function getConverter()
{
return $this->converter;
}
/**
* Set explicit converter name.
*
* @param string $converter
*/
public function setConverter($converter)
{
$this->converter = $converter;
}
/**
* Returns the annotation alias name.
*
* @return string
*
* @see ConfigurationInterface
*/
public function getAliasName()
{
return 'converters';
}
/**
* Multiple ParamConverters are allowed.
*
* @return bool
*
* @see ConfigurationInterface
*/
public function allowArray()
{
return true;
}
}

View File

@@ -0,0 +1,53 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Configuration;
use Symfony\Component\Routing\Annotation\Route as BaseRoute;
@trigger_error(sprintf('The "%s" annotation is deprecated since version 5.2. Use "%s" instead.', Route::class, BaseRoute::class), E_USER_DEPRECATED);
/**
* @author Kris Wallsmith <kris@symfony.com>
* @Annotation
*
* @deprecated since version 5.2
*/
class Route extends BaseRoute
{
private $service;
public function setService($service)
{
// avoid a BC notice in case of @Route(service="") with sf ^2.7
if (null === $this->getPath()) {
$this->setPath('');
}
$this->service = $service;
}
public function getService()
{
return $this->service;
}
/**
* Multiple route annotations are allowed.
*
* @return bool
*
* @see ConfigurationInterface
*/
public function allowArray()
{
return true;
}
}

View File

@@ -0,0 +1,90 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Configuration;
/**
* The Security class handles the Security annotation.
*
* @author Fabien Potencier <fabien@symfony.com>
* @Annotation
*/
class Security extends ConfigurationAnnotation
{
/**
* The expression evaluated to allow or deny access.
*
* @var string
*/
private $expression;
/**
* If set, will throw Symfony\Component\HttpKernel\Exception\HttpException
* with the given $statusCode.
* If null, Symfony\Component\Security\Core\Exception\AccessDeniedException.
* will be used.
*
* @var int|null
*/
protected $statusCode;
/**
* The message of the exception.
*
* @var string
*/
protected $message = 'Access denied.';
public function getExpression()
{
return $this->expression;
}
public function setExpression($expression)
{
$this->expression = $expression;
}
public function getStatusCode()
{
return $this->statusCode;
}
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
}
public function getMessage()
{
return $this->message;
}
public function setMessage($message)
{
$this->message = $message;
}
public function setValue($expression)
{
$this->setExpression($expression);
}
public function getAliasName()
{
return 'security';
}
public function allowArray()
{
return true;
}
}

View File

@@ -0,0 +1,157 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Configuration;
/**
* The Template class handles the Template annotation parts.
*
* @author Fabien Potencier <fabien@symfony.com>
* @Annotation
*/
class Template extends ConfigurationAnnotation
{
/**
* The template.
*
* @var string
*/
protected $template;
/**
* The associative array of template variables.
*
* @var array
*/
private $vars = [];
/**
* Should the template be streamed?
*
* @var bool
*/
private $streamable = false;
/**
* The controller (+action) this annotation is set to.
*
* @var array
*/
private $owner;
/**
* Returns the array of templates variables.
*
* @return array
*/
public function getVars()
{
return $this->vars;
}
/**
* @param bool $streamable
*/
public function setIsStreamable($streamable)
{
$this->streamable = $streamable;
}
/**
* @return bool
*/
public function isStreamable()
{
return (bool) $this->streamable;
}
/**
* Sets the template variables.
*
* @param array $vars The template variables
*/
public function setVars($vars)
{
$this->vars = $vars;
}
/**
* Sets the template logic name.
*
* @param string $template The template logic name
*/
public function setValue($template)
{
$this->setTemplate($template);
}
/**
* Returns the template.
*
* @return string
*/
public function getTemplate()
{
return $this->template;
}
/**
* Sets the template.
*
* @param string $template The template
*/
public function setTemplate($template)
{
$this->template = $template;
}
/**
* Returns the annotation alias name.
*
* @return string
*
* @see ConfigurationInterface
*/
public function getAliasName()
{
return 'template';
}
/**
* Only one template directive is allowed.
*
* @return bool
*
* @see ConfigurationInterface
*/
public function allowArray()
{
return false;
}
/**
* @param array $owner
*/
public function setOwner(array $owner)
{
$this->owner = $owner;
}
/**
* The controller (+action) this annotation is attached to.
*
* @return array
*/
public function getOwner()
{
return $this->owner;
}
}

View File

@@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class AddExpressionLanguageProvidersPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if ($container->hasDefinition('sensio_framework_extra.security.expression_language.default')) {
$definition = $container->findDefinition('sensio_framework_extra.security.expression_language.default');
foreach ($container->findTaggedServiceIds('security.expression_language_provider') as $id => $attributes) {
$definition->addMethodCall('registerProvider', [new Reference($id)]);
}
}
}
}

View File

@@ -0,0 +1,53 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Adds tagged request.param_converter services to converter.manager service.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class AddParamConverterPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (false === $container->hasDefinition('sensio_framework_extra.converter.manager')) {
return;
}
$definition = $container->getDefinition('sensio_framework_extra.converter.manager');
$disabled = $container->getParameter('sensio_framework_extra.disabled_converters');
$container->getParameterBag()->remove('sensio_framework_extra.disabled_converters');
foreach ($container->findTaggedServiceIds('request.param_converter') as $id => $converters) {
foreach ($converters as $converter) {
$name = isset($converter['converter']) ? $converter['converter'] : null;
if (null !== $name && \in_array($name, $disabled)) {
continue;
}
$priority = isset($converter['priority']) ? $converter['priority'] : 0;
if ('false' === $priority || false === $priority) {
$priority = null;
}
$definition->addMethodCall('add', [new Reference($id), $priority, $name]);
}
}
}
}

View File

@@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Optimizes the container by removing unneeded listeners.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class OptimizerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('security.token_storage')) {
$container->removeDefinition('sensio_framework_extra.security.listener');
}
if (!$container->hasDefinition('twig')) {
$container->removeDefinition('sensio_framework_extra.view.listener');
}
}
}

View File

@@ -0,0 +1,95 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\NodeInterface;
/**
* FrameworkExtraBundle configuration structure.
*
* @author Henrik Bjornskov <hb@peytz.dk>
*/
class Configuration implements ConfigurationInterface
{
/**
* Generates the configuration tree.
*
* @return NodeInterface
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('sensio_framework_extra');
if (method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->getRootNode();
} else {
// BC layer for symfony/config 4.1 and older
$rootNode = $treeBuilder->root('sensio_framework_extra');
}
$rootNode
->children()
->arrayNode('router')
->addDefaultsIfNotSet()
->children()
->booleanNode('annotations')->defaultTrue()->end()
->end()
->end()
->arrayNode('request')
->addDefaultsIfNotSet()
->children()
->booleanNode('converters')->defaultTrue()->end()
->booleanNode('auto_convert')->defaultTrue()->end()
->arrayNode('disable')->prototype('scalar')->end()->end()
->end()
->end()
->arrayNode('view')
->addDefaultsIfNotSet()
->children()
->booleanNode('annotations')->defaultTrue()->end()
->end()
->end()
->arrayNode('cache')
->addDefaultsIfNotSet()
->children()
->booleanNode('annotations')->defaultTrue()->end()
->end()
->end()
->arrayNode('security')
->addDefaultsIfNotSet()
->children()
->booleanNode('annotations')->defaultTrue()->end()
->scalarNode('expression_language')->defaultValue('sensio_framework_extra.security.expression_language.default')->end()
->end()
->end()
->arrayNode('psr_message')
->addDefaultsIfNotSet()
->children()
->booleanNode('enabled')->defaultValue(interface_exists('Symfony\Bridge\PsrHttpMessage\HttpFoundationFactoryInterface') && class_exists('Zend\Diactoros\ServerRequestFactory'))->end()
->end()
->end()
->arrayNode('templating')
->fixXmlConfig('controller_pattern')
->children()
->arrayNode('controller_patterns')
->prototype('scalar')
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
}

View File

@@ -0,0 +1,175 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\DependencyInjection;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Resource\ClassExistenceResource;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage as SecurityExpressionLanguage;
use Zend\Diactoros\ServerRequestFactory;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class SensioFrameworkExtraExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$configuration = $this->getConfiguration($configs, $container);
$config = $this->processConfiguration($configuration, $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$annotationsToLoad = [];
$definitionsToRemove = [];
if ($config['router']['annotations']) {
@trigger_error(sprintf('Enabling the "sensio_framework_extra.router.annotations" configuration is deprecated since version 5.2. Set it to false and use the "%s" annotation from Symfony itself.', \Symfony\Component\Routing\Annotation\Route::class), E_USER_DEPRECATED);
$annotationsToLoad[] = 'routing.xml';
if (\PHP_VERSION_ID < 70000) {
$this->addClassesToCompile([
'Sensio\\Bundle\\FrameworkExtraBundle\\EventListener\\ControllerListener',
]);
}
}
if ($config['request']['converters']) {
$annotationsToLoad[] = 'converters.xml';
$container->registerForAutoconfiguration(ParamConverterInterface::class)
->addTag('request.param_converter');
$container->setParameter('sensio_framework_extra.disabled_converters', \is_string($config['request']['disable']) ? implode(',', $config['request']['disable']) : $config['request']['disable']);
$container->addResource(new ClassExistenceResource(ExpressionLanguage::class));
if (class_exists(ExpressionLanguage::class)) {
$container->setAlias('sensio_framework_extra.converter.doctrine.orm.expression_language', new Alias('sensio_framework_extra.converter.doctrine.orm.expression_language.default', false));
} else {
$definitionsToRemove[] = 'sensio_framework_extra.converter.doctrine.orm.expression_language.default';
}
if (\PHP_VERSION_ID < 70000) {
$this->addClassesToCompile([
// cannot be added because it has some annotations
//'Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\ParamConverter',
'Sensio\\Bundle\\FrameworkExtraBundle\\EventListener\\ParamConverterListener',
'Sensio\\Bundle\\FrameworkExtraBundle\\Request\\ParamConverter\\DateTimeParamConverter',
'Sensio\\Bundle\\FrameworkExtraBundle\\Request\\ParamConverter\\DoctrineParamConverter',
'Sensio\\Bundle\\FrameworkExtraBundle\\Request\\ParamConverter\\ParamConverterInterface',
'Sensio\\Bundle\\FrameworkExtraBundle\\Request\\ParamConverter\\ParamConverterManager',
]);
}
}
if ($config['view']['annotations']) {
$annotationsToLoad[] = 'view.xml';
if (\PHP_VERSION_ID < 70000) {
$this->addClassesToCompile([
'Sensio\\Bundle\\FrameworkExtraBundle\\EventListener\\TemplateListener',
]);
}
}
if ($config['cache']['annotations']) {
$annotationsToLoad[] = 'cache.xml';
if (\PHP_VERSION_ID < 70000) {
$this->addClassesToCompile([
'Sensio\\Bundle\\FrameworkExtraBundle\\EventListener\\HttpCacheListener',
]);
}
}
if ($config['security']['annotations']) {
$annotationsToLoad[] = 'security.xml';
$container->addResource(new ClassExistenceResource(ExpressionLanguage::class));
if (class_exists(ExpressionLanguage::class)) {
// this resource can only be added if ExpressionLanguage exists (to avoid a fatal error)
$container->addResource(new ClassExistenceResource(SecurityExpressionLanguage::class));
if (class_exists(SecurityExpressionLanguage::class)) {
$container->setAlias('sensio_framework_extra.security.expression_language', new Alias($config['security']['expression_language'], false));
} else {
$definitionsToRemove[] = 'sensio_framework_extra.security.expression_language.default';
}
} else {
$definitionsToRemove[] = 'sensio_framework_extra.security.expression_language.default';
}
if (\PHP_VERSION_ID < 70000) {
$this->addClassesToCompile([
'Sensio\\Bundle\\FrameworkExtraBundle\\EventListener\\SecurityListener',
]);
}
}
if ($annotationsToLoad) {
// must be first
$loader->load('annotations.xml');
foreach ($annotationsToLoad as $configFile) {
$loader->load($configFile);
}
if (\PHP_VERSION_ID < 70000) {
$this->addClassesToCompile([
'Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\ConfigurationAnnotation',
]);
}
if ($config['request']['converters']) {
$container->getDefinition('sensio_framework_extra.converter.listener')->replaceArgument(1, $config['request']['auto_convert']);
}
}
if (!empty($config['templating']['controller_patterns'])) {
$container
->getDefinition('sensio_framework_extra.view.guesser')
->addArgument($config['templating']['controller_patterns']);
}
if ($config['psr_message']['enabled']) {
$loader->load('psr7.xml');
if (!class_exists(ServerRequestFactory::class)) {
$definitionsToRemove[] = 'sensio_framework_extra.psr7.argument_value_resolver.server_request';
}
}
foreach ($definitionsToRemove as $definition) {
$container->removeDefinition($definition);
}
}
/**
* Returns the base path for the XSD files.
*
* @return string The XSD base path
*/
public function getXsdValidationBasePath()
{
return __DIR__.'/../Resources/config/schema';
}
public function getNamespace()
{
return 'http://symfony.com/schema/dic/symfony_extra';
}
}

View File

@@ -0,0 +1,115 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\EventListener;
use Doctrine\Common\Annotations\Reader;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface;
use Doctrine\Common\Util\ClassUtils;
/**
* The ControllerListener class parses annotation blocks located in
* controller classes.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ControllerListener implements EventSubscriberInterface
{
/**
* @var Reader
*/
private $reader;
public function __construct(Reader $reader)
{
$this->reader = $reader;
}
/**
* Modifies the Request object to apply configuration information found in
* controllers annotations like the template to render or HTTP caching
* configuration.
*/
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
if (!\is_array($controller) && method_exists($controller, '__invoke')) {
$controller = [$controller, '__invoke'];
}
if (!\is_array($controller)) {
return;
}
$className = class_exists('Doctrine\Common\Util\ClassUtils') ? ClassUtils::getClass($controller[0]) : \get_class($controller[0]);
$object = new \ReflectionClass($className);
$method = $object->getMethod($controller[1]);
$classConfigurations = $this->getConfigurations($this->reader->getClassAnnotations($object));
$methodConfigurations = $this->getConfigurations($this->reader->getMethodAnnotations($method));
$configurations = [];
foreach (array_merge(array_keys($classConfigurations), array_keys($methodConfigurations)) as $key) {
if (!array_key_exists($key, $classConfigurations)) {
$configurations[$key] = $methodConfigurations[$key];
} elseif (!array_key_exists($key, $methodConfigurations)) {
$configurations[$key] = $classConfigurations[$key];
} else {
if (\is_array($classConfigurations[$key])) {
if (!\is_array($methodConfigurations[$key])) {
throw new \UnexpectedValueException('Configurations should both be an array or both not be an array');
}
$configurations[$key] = array_merge($classConfigurations[$key], $methodConfigurations[$key]);
} else {
// method configuration overrides class configuration
$configurations[$key] = $methodConfigurations[$key];
}
}
}
$request = $event->getRequest();
foreach ($configurations as $key => $attributes) {
$request->attributes->set($key, $attributes);
}
}
private function getConfigurations(array $annotations)
{
$configurations = [];
foreach ($annotations as $configuration) {
if ($configuration instanceof ConfigurationInterface) {
if ($configuration->allowArray()) {
$configurations['_'.$configuration->getAliasName()][] = $configuration;
} elseif (!isset($configurations['_'.$configuration->getAliasName()])) {
$configurations['_'.$configuration->getAliasName()] = $configuration;
} else {
throw new \LogicException(sprintf('Multiple "%s" annotations are not allowed.', $configuration->getAliasName()));
}
}
}
return $configurations;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
}

View File

@@ -0,0 +1,184 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\EventListener;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
/**
* HttpCacheListener handles HTTP cache headers.
*
* It can be configured via the Cache annotation.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class HttpCacheListener implements EventSubscriberInterface
{
private $lastModifiedDates;
private $etags;
private $expressionLanguage;
public function __construct()
{
$this->lastModifiedDates = new \SplObjectStorage();
$this->etags = new \SplObjectStorage();
}
/**
* Handles HTTP validation headers.
*/
public function onKernelController(FilterControllerEvent $event)
{
$request = $event->getRequest();
if (!$configuration = $request->attributes->get('_cache')) {
return;
}
$response = new Response();
$lastModifiedDate = '';
if ($configuration->getLastModified()) {
$lastModifiedDate = $this->getExpressionLanguage()->evaluate($configuration->getLastModified(), $request->attributes->all());
$response->setLastModified($lastModifiedDate);
}
$etag = '';
if ($configuration->getEtag()) {
$etag = hash('sha256', $this->getExpressionLanguage()->evaluate($configuration->getEtag(), $request->attributes->all()));
$response->setEtag($etag);
}
if ($response->isNotModified($request)) {
$event->setController(function () use ($response) {
return $response;
});
$event->stopPropagation();
} else {
if ($etag) {
$this->etags[$request] = $etag;
}
if ($lastModifiedDate) {
$this->lastModifiedDates[$request] = $lastModifiedDate;
}
}
}
/**
* Modifies the response to apply HTTP cache headers when needed.
*/
public function onKernelResponse(FilterResponseEvent $event)
{
$request = $event->getRequest();
if (!$configuration = $request->attributes->get('_cache')) {
return;
}
$response = $event->getResponse();
// http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-12#section-3.1
if (!\in_array($response->getStatusCode(), [200, 203, 300, 301, 302, 304, 404, 410])) {
return;
}
if (!$response->headers->hasCacheControlDirective('s-maxage') && null !== $age = $configuration->getSMaxAge()) {
$age = $this->convertToSecondsIfNeeded($age);
$response->setSharedMaxAge($age);
}
if ($configuration->mustRevalidate()) {
$response->headers->addCacheControlDirective('must-revalidate');
}
if (!$response->headers->hasCacheControlDirective('max-age') && null !== $age = $configuration->getMaxAge()) {
$age = $this->convertToSecondsIfNeeded($age);
$response->setMaxAge($age);
}
if (!$response->headers->hasCacheControlDirective('max-stale') && null !== $stale = $configuration->getMaxStale()) {
$stale = $this->convertToSecondsIfNeeded($stale);
$response->headers->addCacheControlDirective('max-stale', $stale);
}
if (!$response->headers->has('Expires') && null !== $configuration->getExpires()) {
$date = \DateTime::createFromFormat('U', strtotime($configuration->getExpires()), new \DateTimeZone('UTC'));
$response->setExpires($date);
}
if (!$response->headers->has('Vary') && null !== $configuration->getVary()) {
$response->setVary($configuration->getVary());
}
if ($configuration->isPublic()) {
$response->setPublic();
}
if ($configuration->isPrivate()) {
$response->setPrivate();
}
if (!$response->headers->has('Last-Modified') && isset($this->lastModifiedDates[$request])) {
$response->setLastModified($this->lastModifiedDates[$request]);
unset($this->lastModifiedDates[$request]);
}
if (!$response->headers->has('Etag') && isset($this->etags[$request])) {
$response->setEtag($this->etags[$request]);
unset($this->etags[$request]);
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
private function getExpressionLanguage()
{
if (null === $this->expressionLanguage) {
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
}
$this->expressionLanguage = new ExpressionLanguage();
}
return $this->expressionLanguage;
}
/**
* @param int|string $time Time that can be either expressed in seconds or with relative time format (1 day, 2 weeks, ...)
*
* @return int
*/
private function convertToSecondsIfNeeded($time)
{
if (!is_numeric($time)) {
$now = microtime(true);
$time = ceil(strtotime($time, $now) - $now);
}
return $time;
}
}

View File

@@ -0,0 +1,102 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\EventListener;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sensio\Bundle\FrameworkExtraBundle\Request\ArgumentNameConverter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* Handles the IsGranted annotation on controllers.
*
* @author Ryan Weaver <ryan@knpuniversity.com>
*/
class IsGrantedListener implements EventSubscriberInterface
{
private $argumentNameConverter;
private $authChecker;
public function __construct(ArgumentNameConverter $argumentNameConverter, AuthorizationCheckerInterface $authChecker = null)
{
$this->argumentNameConverter = $argumentNameConverter;
$this->authChecker = $authChecker;
}
public function onKernelControllerArguments(FilterControllerArgumentsEvent $event)
{
$request = $event->getRequest();
/** @var $configurations IsGranted[] */
if (!$configurations = $request->attributes->get('_is_granted')) {
return;
}
if (null === $this->authChecker) {
throw new \LogicException('To use the @IsGranted tag, you need to install symfony/security-bundle and configure your security system.');
}
$arguments = $this->argumentNameConverter->getControllerArguments($event);
foreach ($configurations as $configuration) {
$subject = null;
if ($configuration->getSubject()) {
if (!isset($arguments[$configuration->getSubject()])) {
throw new \RuntimeException(sprintf('Could not find the subject "%s" for the @IsGranted annotation. Try adding a "$%s" argument to your controller method.', $configuration->getSubject(), $configuration->getSubject()));
}
$subject = $arguments[$configuration->getSubject()];
}
if (!$this->authChecker->isGranted($configuration->getAttributes(), $subject)) {
$argsString = $this->getIsGrantedString($configuration);
$message = $configuration->getMessage() ?: sprintf('Access Denied by controller annotation @IsGranted(%s)', $argsString);
if ($statusCode = $configuration->getStatusCode()) {
throw new HttpException($statusCode, $message);
}
throw new AccessDeniedException($message);
}
}
}
private function getIsGrantedString(IsGranted $isGranted)
{
$attributes = array_map(function ($attribute) {
return sprintf('"%s"', $attribute);
}, (array) $isGranted->getAttributes());
if (1 === \count($attributes)) {
$argsString = reset($attributes);
} else {
$argsString = sprintf('[%s]', implode(', ', $attributes));
}
if (null !== $isGranted->getSubject()) {
$argsString = sprintf('%s, %s', $argsString, $isGranted->getSubject());
}
return $argsString;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [KernelEvents::CONTROLLER_ARGUMENTS => 'onKernelControllerArguments'];
}
}

View File

@@ -0,0 +1,122 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\EventListener;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* The ParamConverterListener handles the ParamConverter annotation.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ParamConverterListener implements EventSubscriberInterface
{
/**
* @var ParamConverterManager
*/
private $manager;
private $autoConvert;
/**
* @var bool
*/
private $isParameterTypeSupported;
/**
* @param bool $autoConvert Auto convert non-configured objects
*/
public function __construct(ParamConverterManager $manager, $autoConvert = true)
{
$this->manager = $manager;
$this->autoConvert = $autoConvert;
$this->isParameterTypeSupported = method_exists('ReflectionParameter', 'getType');
}
/**
* Modifies the ParamConverterManager instance.
*/
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
$request = $event->getRequest();
$configurations = [];
if ($configuration = $request->attributes->get('_converters')) {
foreach (\is_array($configuration) ? $configuration : [$configuration] as $configuration) {
$configurations[$configuration->getName()] = $configuration;
}
}
if (\is_array($controller)) {
$r = new \ReflectionMethod($controller[0], $controller[1]);
} elseif (\is_object($controller) && \is_callable([$controller, '__invoke'])) {
$r = new \ReflectionMethod($controller, '__invoke');
} else {
$r = new \ReflectionFunction($controller);
}
// automatically apply conversion for non-configured objects
if ($this->autoConvert) {
$configurations = $this->autoConfigure($r, $request, $configurations);
}
$this->manager->apply($request, $configurations);
}
private function autoConfigure(\ReflectionFunctionAbstract $r, Request $request, $configurations)
{
foreach ($r->getParameters() as $param) {
if ($param->getClass() && $param->getClass()->isInstance($request)) {
continue;
}
$name = $param->getName();
$class = $param->getClass();
$hasType = $this->isParameterTypeSupported && $param->hasType();
if ($class || $hasType) {
if (!isset($configurations[$name])) {
$configuration = new ParamConverter([]);
$configuration->setName($name);
$configurations[$name] = $configuration;
}
if ($class && null === $configurations[$name]->getClass()) {
$configurations[$name]->setClass($class->getName());
}
}
if (isset($configurations[$name])) {
$configurations[$name]->setIsOptional($param->isOptional() || $param->isDefaultValueAvailable() || $hasType && $param->getType()->allowsNull());
}
}
return $configurations;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
}

View File

@@ -0,0 +1,60 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\EventListener;
use Psr\Http\Message\ResponseInterface;
use Symfony\Bridge\PsrHttpMessage\HttpFoundationFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Converts PSR-7 Response to HttpFoundation Response using the bridge.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class PsrResponseListener implements EventSubscriberInterface
{
/**
* @var HttpFoundationFactoryInterface
*/
private $httpFoundationFactory;
public function __construct(HttpFoundationFactoryInterface $httpFoundationFactory)
{
$this->httpFoundationFactory = $httpFoundationFactory;
}
/**
* Do the conversion if applicable and update the response of the event.
*/
public function onKernelView(GetResponseForControllerResultEvent $event)
{
$controllerResult = $event->getControllerResult();
if (!$controllerResult instanceof ResponseInterface) {
return;
}
$event->setResponse($this->httpFoundationFactory->createResponse($controllerResult));
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => 'onKernelView',
];
}
}

View File

@@ -0,0 +1,137 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\EventListener;
use Psr\Log\LoggerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Request\ArgumentNameConverter;
use Sensio\Bundle\FrameworkExtraBundle\Security\ExpressionLanguage;
use Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
/**
* SecurityListener handles security restrictions on controllers.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SecurityListener implements EventSubscriberInterface
{
private $argumentNameConverter;
private $tokenStorage;
private $authChecker;
private $language;
private $trustResolver;
private $roleHierarchy;
private $logger;
public function __construct(ArgumentNameConverter $argumentNameConverter, ExpressionLanguage $language = null, AuthenticationTrustResolverInterface $trustResolver = null, RoleHierarchyInterface $roleHierarchy = null, TokenStorageInterface $tokenStorage = null, AuthorizationCheckerInterface $authChecker = null, LoggerInterface $logger = null)
{
$this->argumentNameConverter = $argumentNameConverter;
$this->tokenStorage = $tokenStorage;
$this->authChecker = $authChecker;
$this->language = $language;
$this->trustResolver = $trustResolver;
$this->roleHierarchy = $roleHierarchy;
$this->logger = $logger;
}
public function onKernelControllerArguments(FilterControllerArgumentsEvent $event)
{
$request = $event->getRequest();
if (!$configurations = $request->attributes->get('_security')) {
return;
}
if (null === $this->tokenStorage || null === $this->trustResolver) {
throw new \LogicException('To use the @Security tag, you need to install the Symfony Security bundle.');
}
if (null === $this->tokenStorage->getToken()) {
throw new \LogicException('To use the @Security tag, your controller needs to be behind a firewall.');
}
if (null === $this->language) {
throw new \LogicException('To use the @Security tag, you need to use the Security component 2.4 or newer and install the ExpressionLanguage component.');
}
foreach ($configurations as $configuration) {
if (!$this->language->evaluate($configuration->getExpression(), $this->getVariables($event))) {
if ($statusCode = $configuration->getStatusCode()) {
throw new HttpException($statusCode, $configuration->getMessage());
}
throw new AccessDeniedException($configuration->getMessage() ?: sprintf('Expression "%s" denied access.', $configuration->getExpression()));
}
}
}
// code should be sync with Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter
private function getVariables(FilterControllerArgumentsEvent $event)
{
$request = $event->getRequest();
$token = $this->tokenStorage->getToken();
if (null !== $this->roleHierarchy) {
$roles = $this->roleHierarchy->getReachableRoles($token->getRoles());
} else {
$roles = $token->getRoles();
}
$variables = [
'token' => $token,
'user' => $token->getUser(),
'object' => $request,
'subject' => $request,
'request' => $request,
'roles' => array_map(function ($role) {
return $role->getRole();
}, $roles),
'trust_resolver' => $this->trustResolver,
// needed for the is_granted expression function
'auth_checker' => $this->authChecker,
];
$controllerArguments = $this->argumentNameConverter->getControllerArguments($event);
if ($diff = array_intersect(array_keys($variables), array_keys($controllerArguments))) {
foreach ($diff as $key => $variableName) {
if ($variables[$variableName] === $controllerArguments[$variableName]) {
unset($diff[$key]);
}
}
if ($diff) {
$singular = 1 === \count($diff);
if (null !== $this->logger) {
$this->logger->warning(sprintf('Controller argument%s "%s" collided with the built-in security expression variables. The built-in value%s are being used for the @Security expression.', $singular ? '' : 's', implode('", "', $diff), $singular ? 's' : ''));
}
}
}
// controller variables should also be accessible
return array_merge($controllerArguments, $variables);
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [KernelEvents::CONTROLLER_ARGUMENTS => 'onKernelControllerArguments'];
}
}

View File

@@ -0,0 +1,147 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\EventListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Templating\TemplateGuesser;
/**
* Handles the Template annotation for actions.
*
* Depends on pre-processing of the ControllerListener.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TemplateListener implements EventSubscriberInterface
{
private $templateGuesser;
private $twig;
public function __construct(TemplateGuesser $templateGuesser, \Twig_Environment $twig = null)
{
$this->templateGuesser = $templateGuesser;
$this->twig = $twig;
}
/**
* Guesses the template name to render and its variables and adds them to
* the request object.
*/
public function onKernelController(FilterControllerEvent $event)
{
$request = $event->getRequest();
$template = $request->attributes->get('_template');
if (!$template instanceof Template) {
return;
}
$controller = $event->getController();
if (!\is_array($controller) && method_exists($controller, '__invoke')) {
$controller = [$controller, '__invoke'];
}
$template->setOwner($controller);
// when no template has been given, try to resolve it based on the controller
if (null === $template->getTemplate()) {
$template->setTemplate($this->templateGuesser->guessTemplateName($controller, $request));
}
}
/**
* Renders the template and initializes a new response object with the
* rendered template content.
*/
public function onKernelView(GetResponseForControllerResultEvent $event)
{
/* @var Template $template */
$request = $event->getRequest();
$template = $request->attributes->get('_template');
if (!$template instanceof Template) {
return;
}
if (null === $this->twig) {
throw new \LogicException('You can not use the "@Template" annotation if the Twig Bundle is not available.');
}
$parameters = $event->getControllerResult();
$owner = $template->getOwner();
list($controller, $action) = $owner;
// when the annotation declares no default vars and the action returns
// null, all action method arguments are used as default vars
if (null === $parameters) {
$parameters = $this->resolveDefaultParameters($request, $template, $controller, $action);
}
// attempt to render the actual response
if ($template->isStreamable()) {
$callback = function () use ($template, $parameters) {
$this->twig->display($template->getTemplate(), $parameters);
};
$event->setResponse(new StreamedResponse($callback));
} else {
$event->setResponse(new Response($this->twig->render($template->getTemplate(), $parameters)));
}
// make sure the owner (controller+dependencies) is not cached or stored elsewhere
$template->setOwner([]);
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => ['onKernelController', -128],
KernelEvents::VIEW => 'onKernelView',
];
}
private function resolveDefaultParameters(Request $request, Template $template, $controller, $action)
{
$parameters = [];
$arguments = $template->getVars();
if (0 === \count($arguments)) {
$r = new \ReflectionObject($controller);
$arguments = [];
foreach ($r->getMethod($action)->getParameters() as $param) {
$arguments[] = $param;
}
}
// fetch the arguments of @Template.vars or everything if desired
// and assign them to the designated template
foreach ($arguments as $argument) {
if ($argument instanceof \ReflectionParameter) {
$parameters[$name = $argument->getName()] = !$request->attributes->has($name) && $argument->isDefaultValueAvailable() ? $argument->getDefaultValue() : $request->attributes->get($name);
} else {
$parameters[$argument] = $request->attributes->get($argument);
}
}
return $parameters;
}
}

View File

@@ -0,0 +1,19 @@
Copyright (c) 2010-2017 Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,59 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Request;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactoryInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent;
/**
* @author Ryan Weaver <ryan@knpuniversity.com>
*/
class ArgumentNameConverter
{
private $argumentMetadataFactory;
public function __construct(ArgumentMetadataFactoryInterface $argumentMetadataFactory)
{
$this->argumentMetadataFactory = $argumentMetadataFactory;
}
/**
* Returns an associative array of the controller arguments for the event.
*
* @param FilterControllerArgumentsEvent $event
*
* @return array
*/
public function getControllerArguments(FilterControllerArgumentsEvent $event)
{
$namedArguments = $event->getRequest()->attributes->all();
$argumentMetadatas = $this->argumentMetadataFactory->createArgumentMetadata($event->getController());
$controllerArguments = $event->getArguments();
foreach ($argumentMetadatas as $index => $argumentMetadata) {
if ($argumentMetadata->isVariadic()) {
// set the rest of the arguments as this arg's value
$namedArguments[$argumentMetadata->getName()] = \array_slice($controllerArguments, $index);
break;
}
if (!array_key_exists($index, $controllerArguments)) {
throw new \LogicException(sprintf('Could not find an argument value for argument %d of the controller.', $index));
}
$namedArguments[$argumentMetadata->getName()] = $controllerArguments[$index];
}
return $namedArguments;
}
}

View File

@@ -0,0 +1,54 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Request\ArgumentValueResolver;
use Symfony\Bridge\PsrHttpMessage\HttpMessageFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
/**
* Injects the RequestInterface, MessageInterface or ServerRequestInterface when requested.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
final class Psr7ServerRequestResolver implements ArgumentValueResolverInterface
{
private static $supportedTypes = [
'Psr\Http\Message\ServerRequestInterface' => true,
'Psr\Http\Message\RequestInterface' => true,
'Psr\Http\Message\MessageInterface' => true,
];
private $httpMessageFactory;
public function __construct(HttpMessageFactoryInterface $httpMessageFactory)
{
$this->httpMessageFactory = $httpMessageFactory;
}
/**
* {@inheritdoc}
*/
public function supports(Request $request, ArgumentMetadata $argument)
{
return isset(self::$supportedTypes[$argument->getType()]);
}
/**
* {@inheritdoc}
*/
public function resolve(Request $request, ArgumentMetadata $argument)
{
yield $this->httpMessageFactory->createRequest($request);
}
}

View File

@@ -0,0 +1,84 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use DateTime;
/**
* Convert DateTime instances from request attribute variable.
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class DateTimeParamConverter implements ParamConverterInterface
{
/**
* {@inheritdoc}
*
* @throws NotFoundHttpException When invalid date given
*/
public function apply(Request $request, ParamConverter $configuration)
{
$param = $configuration->getName();
if (!$request->attributes->has($param)) {
return false;
}
$options = $configuration->getOptions();
$value = $request->attributes->get($param);
if (!$value && $configuration->isOptional()) {
$request->attributes->set($param, null);
return true;
}
$class = $configuration->getClass();
if (isset($options['format'])) {
$date = $class::createFromFormat($options['format'], $value);
if (0 < DateTime::getLastErrors()['warning_count']) {
$date = false;
}
if (!$date) {
throw new NotFoundHttpException(sprintf('Invalid date given for parameter "%s".', $param));
}
} else {
if (false === strtotime($value)) {
throw new NotFoundHttpException(sprintf('Invalid date given for parameter "%s".', $param));
}
$date = new $class($value);
}
$request->attributes->set($param, $date);
return true;
}
/**
* {@inheritdoc}
*/
public function supports(ParamConverter $configuration)
{
if (null === $configuration->getClass()) {
return false;
}
return 'DateTime' === $configuration->getClass() || is_subclass_of($configuration->getClass(), \PHP_VERSION_ID < 50500 ? 'DateTime' : 'DateTimeInterface');
}
}

View File

@@ -0,0 +1,344 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter;
use Doctrine\DBAL\Types\ConversionException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\SyntaxError;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NoResultException;
/**
* DoctrineParamConverter.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class DoctrineParamConverter implements ParamConverterInterface
{
/**
* @var ManagerRegistry
*/
private $registry;
/**
* @var ExpressionLanguage
*/
private $language;
/**
* @var array
*/
private $defaultOptions;
public function __construct(ManagerRegistry $registry = null, ExpressionLanguage $expressionLanguage = null, array $options = [])
{
$this->registry = $registry;
$this->language = $expressionLanguage;
$defaultValues = [
'entity_manager' => null,
'exclude' => [],
'mapping' => [],
'strip_null' => false,
'expr' => null,
'id' => null,
'repository_method' => null,
'map_method_signature' => false,
'evict_cache' => false,
];
$this->defaultOptions = array_merge($defaultValues, $options);
}
/**
* {@inheritdoc}
*
* @throws \LogicException When unable to guess how to get a Doctrine instance from the request information
* @throws NotFoundHttpException When object not found
*/
public function apply(Request $request, ParamConverter $configuration)
{
$name = $configuration->getName();
$class = $configuration->getClass();
$options = $this->getOptions($configuration);
if (null === $request->attributes->get($name, false)) {
$configuration->setIsOptional(true);
}
$errorMessage = null;
if ($expr = $options['expr']) {
$object = $this->findViaExpression($class, $request, $expr, $options, $configuration);
if (null === $object) {
$errorMessage = sprintf('The expression "%s" returned null', $expr);
}
// find by identifier?
} elseif (false === $object = $this->find($class, $request, $options, $name)) {
// find by criteria
if (false === $object = $this->findOneBy($class, $request, $options)) {
if ($configuration->isOptional()) {
$object = null;
} else {
throw new \LogicException(sprintf('Unable to guess how to get a Doctrine instance from the request information for parameter "%s".', $name));
}
}
}
if (null === $object && false === $configuration->isOptional()) {
$message = sprintf('%s object not found by the @%s annotation.', $class, $this->getAnnotationName($configuration));
if ($errorMessage) {
$message .= ' '.$errorMessage;
}
throw new NotFoundHttpException($message);
}
$request->attributes->set($name, $object);
return true;
}
private function find($class, Request $request, $options, $name)
{
if ($options['mapping'] || $options['exclude']) {
return false;
}
$id = $this->getIdentifier($request, $options, $name);
if (false === $id || null === $id) {
return false;
}
if ($options['repository_method']) {
$method = $options['repository_method'];
} else {
$method = 'find';
}
$om = $this->getManager($options['entity_manager'], $class);
if ($options['evict_cache'] && $om instanceof EntityManagerInterface) {
$cacheProvider = $om->getCache();
if ($cacheProvider && $cacheProvider->containsEntity($class, $id)) {
$cacheProvider->evictEntity($class, $id);
}
}
try {
return $om->getRepository($class)->$method($id);
} catch (NoResultException $e) {
return;
} catch (ConversionException $e) {
return;
}
}
private function getIdentifier(Request $request, $options, $name)
{
if (null !== $options['id']) {
if (!\is_array($options['id'])) {
$name = $options['id'];
} elseif (\is_array($options['id'])) {
$id = [];
foreach ($options['id'] as $field) {
if (false !== strstr($field, '%s')) {
// Convert "%s_uuid" to "foobar_uuid"
$field = sprintf($field, $name);
}
$id[$field] = $request->attributes->get($field);
}
return $id;
}
}
if ($request->attributes->has($name)) {
return $request->attributes->get($name);
}
if ($request->attributes->has('id') && !$options['id']) {
return $request->attributes->get('id');
}
return false;
}
private function findOneBy($class, Request $request, $options)
{
if (!$options['mapping']) {
$keys = $request->attributes->keys();
$options['mapping'] = $keys ? array_combine($keys, $keys) : [];
}
foreach ($options['exclude'] as $exclude) {
unset($options['mapping'][$exclude]);
}
if (!$options['mapping']) {
return false;
}
// if a specific id has been defined in the options and there is no corresponding attribute
// return false in order to avoid a fallback to the id which might be of another object
if ($options['id'] && null === $request->attributes->get($options['id'])) {
return false;
}
$criteria = [];
$em = $this->getManager($options['entity_manager'], $class);
$metadata = $em->getClassMetadata($class);
$mapMethodSignature = $options['repository_method']
&& $options['map_method_signature']
&& true === $options['map_method_signature'];
foreach ($options['mapping'] as $attribute => $field) {
if ($metadata->hasField($field)
|| ($metadata->hasAssociation($field) && $metadata->isSingleValuedAssociation($field))
|| $mapMethodSignature) {
$criteria[$field] = $request->attributes->get($attribute);
}
}
if ($options['strip_null']) {
$criteria = array_filter($criteria, function ($value) {
return null !== $value;
});
}
if (!$criteria) {
return false;
}
if ($options['repository_method']) {
$repositoryMethod = $options['repository_method'];
} else {
$repositoryMethod = 'findOneBy';
}
try {
if ($mapMethodSignature) {
return $this->findDataByMapMethodSignature($em, $class, $repositoryMethod, $criteria);
}
return $em->getRepository($class)->$repositoryMethod($criteria);
} catch (NoResultException $e) {
return;
} catch (ConversionException $e) {
return;
}
}
private function findDataByMapMethodSignature($em, $class, $repositoryMethod, $criteria)
{
$arguments = [];
$repository = $em->getRepository($class);
$ref = new \ReflectionMethod($repository, $repositoryMethod);
foreach ($ref->getParameters() as $parameter) {
if (array_key_exists($parameter->name, $criteria)) {
$arguments[] = $criteria[$parameter->name];
} elseif ($parameter->isDefaultValueAvailable()) {
$arguments[] = $parameter->getDefaultValue();
} else {
throw new \InvalidArgumentException(sprintf('Repository method "%s::%s" requires that you provide a value for the "$%s" argument.', \get_class($repository), $repositoryMethod, $parameter->name));
}
}
return $ref->invokeArgs($repository, $arguments);
}
private function findViaExpression($class, Request $request, $expression, $options, ParamConverter $configuration)
{
if (null === $this->language) {
throw new \LogicException(sprintf('To use the @%s tag with the "expr" option, you need to install the ExpressionLanguage component.', $this->getAnnotationName($configuration)));
}
$repository = $this->getManager($options['entity_manager'], $class)->getRepository($class);
$variables = array_merge($request->attributes->all(), ['repository' => $repository]);
try {
return $this->language->evaluate($expression, $variables);
} catch (NoResultException $e) {
return;
} catch (ConversionException $e) {
return;
} catch (SyntaxError $e) {
throw new \LogicException(sprintf('Error parsing expression -- %s -- (%s)', $expression, $e->getMessage()), 0, $e);
}
}
/**
* {@inheritdoc}
*/
public function supports(ParamConverter $configuration)
{
// if there is no manager, this means that only Doctrine DBAL is configured
if (null === $this->registry || !\count($this->registry->getManagerNames())) {
return false;
}
if (null === $configuration->getClass()) {
return false;
}
$options = $this->getOptions($configuration, false);
// Doctrine Entity?
$em = $this->getManager($options['entity_manager'], $configuration->getClass());
if (null === $em) {
return false;
}
return !$em->getMetadataFactory()->isTransient($configuration->getClass());
}
private function getOptions(ParamConverter $configuration, $strict = true)
{
$passedOptions = $configuration->getOptions();
if (isset($passedOptions['repository_method'])) {
@trigger_error('The repository_method option of @ParamConverter is deprecated and will be removed in 6.0. Use the expr option or @Entity.', E_USER_DEPRECATED);
}
if (isset($passedOptions['map_method_signature'])) {
@trigger_error('The map_method_signature option of @ParamConverter is deprecated and will be removed in 6.0. Use the expr option or @Entity.', E_USER_DEPRECATED);
}
$extraKeys = array_diff(array_keys($passedOptions), array_keys($this->defaultOptions));
if ($extraKeys && $strict) {
throw new \InvalidArgumentException(sprintf('Invalid option(s) passed to @%s: %s', $this->getAnnotationName($configuration), implode(', ', $extraKeys)));
}
return array_replace($this->defaultOptions, $passedOptions);
}
private function getManager($name, $class)
{
if (null === $name) {
return $this->registry->getManagerForClass($class);
}
return $this->registry->getManager($name);
}
private function getAnnotationName(ParamConverter $configuration)
{
$r = new \ReflectionClass($configuration);
return $r->getShortName();
}
}

View File

@@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
/**
* Converts request parameters to objects and stores them as request
* attributes, so they can be injected as controller method arguments.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface ParamConverterInterface
{
/**
* Stores the object in the request.
*
* @param ParamConverter $configuration Contains the name, class and options of the object
*
* @return bool True if the object has been successfully set, else false
*/
public function apply(Request $request, ParamConverter $configuration);
/**
* Checks if the object is supported.
*
* @return bool True if the object is supported, else false
*/
public function supports(ParamConverter $configuration);
}

View File

@@ -0,0 +1,141 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
/**
* Managers converters.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Henrik Bjornskov <henrik@bjrnskov.dk>
*/
class ParamConverterManager
{
/**
* @var array
*/
private $converters = [];
/**
* @var array
*/
private $namedConverters = [];
/**
* Applies all converters to the passed configurations and stops when a
* converter is applied it will move on to the next configuration and so on.
*
* @param array|object $configurations
*/
public function apply(Request $request, $configurations)
{
if (\is_object($configurations)) {
$configurations = [$configurations];
}
foreach ($configurations as $configuration) {
$this->applyConverter($request, $configuration);
}
}
/**
* Applies converter on request based on the given configuration.
*/
private function applyConverter(Request $request, ParamConverter $configuration)
{
$value = $request->attributes->get($configuration->getName());
$className = $configuration->getClass();
// If the value is already an instance of the class we are trying to convert it into
// we should continue as no conversion is required
if (\is_object($value) && $value instanceof $className) {
return;
}
if ($converterName = $configuration->getConverter()) {
if (!isset($this->namedConverters[$converterName])) {
throw new \RuntimeException(sprintf(
"No converter named '%s' found for conversion of parameter '%s'.",
$converterName,
$configuration->getName()
));
}
$converter = $this->namedConverters[$converterName];
if (!$converter->supports($configuration)) {
throw new \RuntimeException(sprintf(
"Converter '%s' does not support conversion of parameter '%s'.",
$converterName,
$configuration->getName()
));
}
$converter->apply($request, $configuration);
return;
}
foreach ($this->all() as $converter) {
if ($converter->supports($configuration)) {
if ($converter->apply($request, $configuration)) {
return;
}
}
}
}
/**
* Adds a parameter converter.
*
* Converters match either explicitly via $name or by iteration over all
* converters with a $priority. If you pass a $priority = null then the
* added converter will not be part of the iteration chain and can only
* be invoked explicitly.
*
* @param int $priority the priority (between -10 and 10)
* @param string $name name of the converter
*/
public function add(ParamConverterInterface $converter, $priority = 0, $name = null)
{
if (null !== $priority) {
if (!isset($this->converters[$priority])) {
$this->converters[$priority] = [];
}
$this->converters[$priority][] = $converter;
}
if (null !== $name) {
$this->namedConverters[$name] = $converter;
}
}
/**
* Returns all registered param converters.
*
* @return array An array of param converters
*/
public function all()
{
krsort($this->converters);
$converters = [];
foreach ($this->converters as $all) {
$converters = array_merge($converters, $all);
}
return $converters;
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="sensio_framework_extra.controller.listener" class="Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener" public="false">
<tag name="kernel.event_subscriber" />
<argument type="service" id="annotation_reader" />
</service>
</services>
</container>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="sensio_framework_extra.cache.listener" class="Sensio\Bundle\FrameworkExtraBundle\EventListener\HttpCacheListener" public="false">
<tag name="kernel.event_subscriber" />
</service>
</services>
</container>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="sensio_framework_extra.converter.listener" class="Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener" public="false">
<tag name="kernel.event_subscriber" />
<argument type="service" id="sensio_framework_extra.converter.manager" />
<argument>true</argument>
</service>
<service id="sensio_framework_extra.converter.manager" class="Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterManager" />
<service id="sensio_framework_extra.converter.doctrine.orm" class="Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter" public="false">
<tag name="request.param_converter" converter="doctrine.orm" />
<argument type="service" id="doctrine" on-invalid="ignore" />
<argument type="service" id="sensio_framework_extra.converter.doctrine.orm.expression_language" on-invalid="null" />
</service>
<service id="framework_extra_bundle.date_time_param_converter" class="Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DateTimeParamConverter" public="false">
<tag name="request.param_converter" converter="datetime" />
</service>
<service id="sensio_framework_extra.converter.doctrine.orm.expression_language.default" class="Symfony\Component\ExpressionLanguage\ExpressionLanguage" public="false" />
</services>
</container>

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="sensio_framework_extra.psr7.http_message_factory" class="Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory" public="false" />
<service id="sensio_framework_extra.psr7.http_foundation_factory" class="Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory" public="false" />
<service id="sensio_framework_extra.psr7.argument_value_resolver.server_request" class="Sensio\Bundle\FrameworkExtraBundle\Request\ArgumentValueResolver\Psr7ServerRequestResolver" public="false">
<argument type="service" id="sensio_framework_extra.psr7.http_message_factory" />
<tag name="controller.argument_value_resolver" />
</service>
<service id="sensio_framework_extra.psr7.listener.response" class="Sensio\Bundle\FrameworkExtraBundle\EventListener\PsrResponseListener" public="false">
<argument type="service" id="sensio_framework_extra.psr7.http_foundation_factory" />
<tag name="kernel.event_subscriber" />
</service>
</services>
</container>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="sensio_framework_extra.routing.loader.annot_class" class="Sensio\Bundle\FrameworkExtraBundle\Routing\AnnotatedRouteControllerLoader" public="false">
<tag name="routing.loader" />
<argument type="service" id="annotation_reader" />
<deprecated>The "%service_id%" service is deprecated since version 5.2</deprecated>
</service>
<service id="sensio_framework_extra.routing.loader.annot_dir" class="Symfony\Component\Routing\Loader\AnnotationDirectoryLoader" public="false">
<tag name="routing.loader" />
<argument type="service" id="file_locator" />
<argument type="service" id="sensio_framework_extra.routing.loader.annot_class" />
<deprecated>The "%service_id%" service is deprecated since version 5.2</deprecated>
</service>
<service id="sensio_framework_extra.routing.loader.annot_file" class="Symfony\Component\Routing\Loader\AnnotationFileLoader" public="false">
<tag name="routing.loader" />
<argument type="service" id="file_locator" />
<argument type="service" id="sensio_framework_extra.routing.loader.annot_class" />
<deprecated>The "%service_id%" service is deprecated since version 5.2</deprecated>
</service>
</services>
</container>

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="sensio_framework_extra.security.listener" class="Sensio\Bundle\FrameworkExtraBundle\EventListener\SecurityListener" public="false">
<argument type="service" id="framework_extra_bundle.argument_name_convertor" />
<argument type="service" id="sensio_framework_extra.security.expression_language.default" on-invalid="null" />
<argument type="service" id="security.authentication.trust_resolver" on-invalid="null" />
<argument type="service" id="security.role_hierarchy" on-invalid="null" />
<argument type="service" id="security.token_storage" on-invalid="null" />
<argument type="service" id="security.authorization_checker" on-invalid="null" />
<argument type="service" id="logger" on-invalid="null" />
<tag name="kernel.event_subscriber" />
</service>
<service id="sensio_framework_extra.security.expression_language.default" class="Sensio\Bundle\FrameworkExtraBundle\Security\ExpressionLanguage" public="false" />
<service id="framework_extra_bundle.event.is_granted" class="Sensio\Bundle\FrameworkExtraBundle\EventListener\IsGrantedListener" public="false">
<argument type="service" id="framework_extra_bundle.argument_name_convertor" />
<argument type="service" id="security.authorization_checker" on-invalid="null" />
<tag name="kernel.event_subscriber" />
</service>
<service id="framework_extra_bundle.argument_name_convertor" class="Sensio\Bundle\FrameworkExtraBundle\Request\ArgumentNameConverter" public="false">
<argument type="service" id="argument_metadata_factory" />
</service>
</services>
</container>

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="sensio_framework_extra.view.guesser" class="Sensio\Bundle\FrameworkExtraBundle\Templating\TemplateGuesser" public="false">
<argument type="service" id="kernel" />
</service>
<service id="sensio_framework_extra.view.listener" class="Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener" public="false">
<tag name="kernel.event_subscriber" />
<argument type="service" id="sensio_framework_extra.view.guesser" />
<argument type="service" id="twig" on-invalid="null" />
</service>
</services>
</container>

View File

@@ -0,0 +1,91 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Routing;
use Symfony\Component\Routing\Loader\AnnotationClassLoader;
use Symfony\Component\Routing\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route as FrameworkExtraBundleRoute;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
@trigger_error(sprintf('The "%s" class is deprecated since version 5.2. Use "%s" instead.', AnnotatedRouteControllerLoader::class, \Symfony\Bundle\FrameworkBundle\Routing\AnnotatedRouteControllerLoader::class), E_USER_DEPRECATED);
/**
* AnnotatedRouteControllerLoader is an implementation of AnnotationClassLoader
* that sets the '_controller' default based on the class and method names.
*
* It also parse the @Method annotation.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since version 5.2
*/
class AnnotatedRouteControllerLoader extends AnnotationClassLoader
{
/**
* Configures the _controller default parameter and eventually the HTTP method
* requirement of a given Route instance.
*
* @param mixed $annot The annotation class instance
*
* @throws \LogicException When the service option is specified on a method
*/
protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot)
{
// controller
$classAnnot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass);
if ($classAnnot instanceof FrameworkExtraBundleRoute && $service = $classAnnot->getService()) {
$route->setDefault('_controller', $service.':'.$method->getName());
} elseif ('__invoke' === $method->getName()) {
$route->setDefault('_controller', $class->getName());
} else {
$route->setDefault('_controller', $class->getName().'::'.$method->getName());
}
// requirements (@Method)
foreach ($this->reader->getMethodAnnotations($method) as $configuration) {
if ($configuration instanceof Method) {
$route->setMethods($configuration->getMethods());
} elseif ($configuration instanceof FrameworkExtraBundleRoute && $configuration->getService()) {
throw new \LogicException('The service option can only be specified at class level.');
}
}
}
protected function getGlobals(\ReflectionClass $class)
{
$globals = parent::getGlobals($class);
foreach ($this->reader->getClassAnnotations($class) as $configuration) {
if ($configuration instanceof Method) {
$globals['methods'] = array_merge($globals['methods'], $configuration->getMethods());
}
}
return $globals;
}
/**
* Makes the default route name more sane by removing common keywords.
*
* @return string The default route name
*/
protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
{
$routeName = parent::getDefaultRouteName($class, $method);
return preg_replace(
['/(bundle|controller)_/', '/action(_\d+)?$/', '/__/'],
['_', '\\1', '_'],
$routeName
);
}
}

View File

@@ -0,0 +1,33 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Security;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage as BaseExpressionLanguage;
/**
* Adds some function to the default Symfony Security ExpressionLanguage.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ExpressionLanguage extends BaseExpressionLanguage
{
protected function registerFunctions()
{
parent::registerFunctions();
$this->register('is_granted', function ($attributes, $object = 'null') {
return sprintf('$auth_checker->isGranted(%s, %s)', $attributes, $object);
}, function (array $variables, $attributes, $object = null) {
return $variables['auth_checker']->isGranted($attributes, $object);
});
}
}

View File

@@ -0,0 +1,33 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler\AddExpressionLanguageProvidersPass;
use Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler\AddParamConverterPass;
use Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler\OptimizerPass;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class SensioFrameworkExtraBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new AddParamConverterPass());
$container->addCompilerPass(new OptimizerPass());
$container->addCompilerPass(new AddExpressionLanguageProvidersPass());
}
}

View File

@@ -0,0 +1,116 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\FrameworkExtraBundle\Templating;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Util\ClassUtils;
/**
* The TemplateGuesser class handles the guessing of template name based on controller.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TemplateGuesser
{
/**
* @var KernelInterface
*/
private $kernel;
/**
* @var string[]
*/
private $controllerPatterns;
/**
* @param string[] $controllerPatterns Regexps extracting the controller name from its FQN
*/
public function __construct(KernelInterface $kernel, array $controllerPatterns = [])
{
$controllerPatterns[] = '/Controller\\\(.+)Controller$/';
$this->kernel = $kernel;
$this->controllerPatterns = $controllerPatterns;
}
/**
* Guesses and returns the template name to render based on the controller
* and action names.
*
* @param callable $controller An array storing the controller object and action method
*
* @return string The template name
*
* @throws \InvalidArgumentException
*/
public function guessTemplateName($controller, Request $request)
{
if (\is_object($controller) && method_exists($controller, '__invoke')) {
$controller = [$controller, '__invoke'];
} elseif (!\is_array($controller)) {
throw new \InvalidArgumentException(sprintf('First argument of %s must be an array callable or an object defining the magic method __invoke. "%s" given.', __METHOD__, \gettype($controller)));
}
$className = class_exists('Doctrine\Common\Util\ClassUtils') ? ClassUtils::getClass($controller[0]) : \get_class($controller[0]);
$matchController = null;
foreach ($this->controllerPatterns as $pattern) {
if (preg_match($pattern, $className, $tempMatch)) {
$matchController = str_replace('\\', '/', strtolower(preg_replace('/([a-z\d])([A-Z])/', '\\1_\\2', $tempMatch[1])));
break;
}
}
if (null === $matchController) {
throw new \InvalidArgumentException(sprintf('The "%s" class does not look like a controller class (its FQN must match one of the following regexps: "%s")', \get_class($controller[0]), implode('", "', $this->controllerPatterns)));
}
if ('__invoke' === $controller[1]) {
$matchAction = $matchController;
$matchController = null;
} else {
$matchAction = preg_replace('/Action$/', '', $controller[1]);
}
$matchAction = strtolower(preg_replace('/([a-z\d])([A-Z])/', '\\1_\\2', $matchAction));
$bundleName = $this->getBundleForClass($className);
return sprintf(($bundleName ? '@'.$bundleName.'/' : '').$matchController.($matchController ? '/' : '').$matchAction.'.'.$request->getRequestFormat().'.twig');
}
/**
* Returns the bundle name in which the given class name is located.
*
* @param string $class A fully qualified controller class name
*
* @return string|null $bundle A bundle name
*/
private function getBundleForClass($class)
{
$reflectionClass = new \ReflectionClass($class);
$bundles = $this->kernel->getBundles();
do {
$namespace = $reflectionClass->getNamespaceName();
foreach ($bundles as $bundle) {
if ('Symfony\Bundle\FrameworkBundle' === $bundle->getNamespace()) {
continue;
}
if (0 === strpos($namespace, $bundle->getNamespace())) {
return preg_replace('/Bundle$/', '', $bundle->getName());
}
}
$reflectionClass = $reflectionClass->getParentClass();
} while ($reflectionClass);
}
}