CHANGE: peaufinage .gitignore.
/app/cache/*
/app/config/parameters.ini
*swp
+/web/bundles
+/vendor
{% include "::menu.html.twig" with { 'menu_id' : 'bottom_nav' } only %}
{# render quand dynamique, on appelle one action qui appellera un template au besoin #}
- {% render "SensioTrainingBundle:Default:counter" %}
</div>
{% block javascripts %}{% endblock %}
#_internal:
# resource: "@FrameworkBundle/Resources/config/routing/internal.xml"
# prefix: /_internal
-
-SensioUserBundle:
- resource: "@SensioUserBundle/Controller/"
- type: annotation
- prefix: /
-
-SensioTrainingBundle:
- resource: "@SensioTrainingBundle/Controller/"
- type: annotation
- prefix: /
-_welcome:
- pattern: /
- defaults: { _controller: AcmeDemoBundle:Welcome:index }
-
-_demo_secured:
- resource: "@AcmeDemoBundle/Controller/SecuredController.php"
- type: annotation
-
-_demo:
- resource: "@AcmeDemoBundle/Controller/DemoController.php"
- type: annotation
- prefix: /demo
-
_assetic:
resource: .
type: assetic
{
$resource = new Resource();
- $form = $this->createForm('epn_resource', $resource, array('parentChoice'=>Resource::getAllFormatted($this->getDoctrine()->getEntityManager())));
+ $form = $this->createForm('epn_resource', $resource);#, array('parentChoice'=>Resource::getAllFormatted($this->getDoctrine()->getEntityManager())));
$request = $this->getRequest();
if ('POST' === $request->getMethod()) {
namespace Epnadmin\CoreBundle\Form\Type;
-use Symfony\Component\Form\FormBuilder;
+use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
+use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ResourceType extends AbstractType
{
- public function buildForm(FormBuilder $builder, array $options)
+ public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('type', 'choice', array(
'choices' => array(
));
}
- public function getDefaultOptions(array $options)
+ public function setDefaultOptions(OptionsResolverInterface $resolver)
{
- return array(
+ $resolver->setDefaults(array(
'data_class' => 'Epnadmin\CoreBundle\Entity\Resource',
- 'parentChoice' => $options['parentChoice'],
- );
+ //'parentChoice' => $resolver['parentChoice'],
+ ));
}
public function getName()
+++ /dev/null
-<?php
-
-// autoload.php generated by Composer
-if (!class_exists('Composer\\Autoload\\ClassLoader', false)) {
- require __DIR__ . '/composer' . '/ClassLoader.php';
-}
-
-return call_user_func(function() {
- $loader = new \Composer\Autoload\ClassLoader();
- $composerDir = __DIR__ . '/composer';
-
- $map = require $composerDir . '/autoload_namespaces.php';
- foreach ($map as $namespace => $path) {
- $loader->add($namespace, $path);
- }
-
- $classMap = require $composerDir . '/autoload_classmap.php';
- if ($classMap) {
- $loader->addClassMap($classMap);
- }
-
- $loader->register();
-
- require __DIR__ . '/swiftmailer/swiftmailer/lib/swift_required.php';
-
- return $loader;
-});
+++ /dev/null
-<?php
-
-/*
- * This file is part of Composer.
- *
- * (c) Nils Adermann <naderman@naderman.de>
- * Jordi Boggiano <j.boggiano@seld.be>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Composer\Autoload;
-
-/**
- * ClassLoader implements a PSR-0 class loader
- *
- * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
- *
- * $loader = new \Composer\Autoload\ClassLoader();
- *
- * // register classes with namespaces
- * $loader->add('Symfony\Component', __DIR__.'/component');
- * $loader->add('Symfony', __DIR__.'/framework');
- *
- * // activate the autoloader
- * $loader->register();
- *
- * // to enable searching the include path (eg. for PEAR packages)
- * $loader->setUseIncludePath(true);
- *
- * In this example, if you try to use a class in the Symfony\Component
- * namespace or one of its children (Symfony\Component\Console for instance),
- * the autoloader will first look for the class under the component/
- * directory, and it will then fallback to the framework/ directory if not
- * found before giving up.
- *
- * This class is loosely based on the Symfony UniversalClassLoader.
- *
- * @author Fabien Potencier <fabien@symfony.com>
- * @author Jordi Boggiano <j.boggiano@seld.be>
- */
-class ClassLoader
-{
- private $prefixes = array();
- private $fallbackDirs = array();
- private $useIncludePath = false;
- private $classMap = array();
-
- public function getPrefixes()
- {
- return $this->prefixes;
- }
-
- public function getFallbackDirs()
- {
- return $this->fallbackDirs;
- }
-
- public function getClassMap()
- {
- return $this->classMap;
- }
-
- /**
- * @param array $classMap Class to filename map
- */
- public function addClassMap(array $classMap)
- {
- if ($this->classMap) {
- $this->classMap = array_merge($this->classMap, $classMap);
- } else {
- $this->classMap = $classMap;
- }
- }
-
- /**
- * Registers a set of classes
- *
- * @param string $prefix The classes prefix
- * @param array|string $paths The location(s) of the classes
- */
- public function add($prefix, $paths)
- {
- if (!$prefix) {
- foreach ((array) $paths as $path) {
- $this->fallbackDirs[] = $path;
- }
-
- return;
- }
- if (isset($this->prefixes[$prefix])) {
- $this->prefixes[$prefix] = array_merge(
- $this->prefixes[$prefix],
- (array) $paths
- );
- } else {
- $this->prefixes[$prefix] = (array) $paths;
- }
- }
-
- /**
- * Turns on searching the include path for class files.
- *
- * @param bool $useIncludePath
- */
- public function setUseIncludePath($useIncludePath)
- {
- $this->useIncludePath = $useIncludePath;
- }
-
- /**
- * Can be used to check if the autoloader uses the include path to check
- * for classes.
- *
- * @return bool
- */
- public function getUseIncludePath()
- {
- return $this->useIncludePath;
- }
-
- /**
- * Registers this instance as an autoloader.
- *
- * @param bool $prepend Whether to prepend the autoloader or not
- */
- public function register($prepend = false)
- {
- spl_autoload_register(array($this, 'loadClass'), true, $prepend);
- }
-
- /**
- * Unregisters this instance as an autoloader.
- */
- public function unregister()
- {
- spl_autoload_unregister(array($this, 'loadClass'));
- }
-
- /**
- * Loads the given class or interface.
- *
- * @param string $class The name of the class
- * @return bool|null True, if loaded
- */
- public function loadClass($class)
- {
- if ($file = $this->findFile($class)) {
- include $file;
-
- return true;
- }
- }
-
- /**
- * Finds the path to the file where the class is defined.
- *
- * @param string $class The name of the class
- *
- * @return string|null The path, if found
- */
- public function findFile($class)
- {
- if (isset($this->classMap[$class])) {
- return $this->classMap[$class];
- }
-
- if ('\\' == $class[0]) {
- $class = substr($class, 1);
- }
-
- if (false !== $pos = strrpos($class, '\\')) {
- // namespaced class name
- $classPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $pos)) . DIRECTORY_SEPARATOR;
- $className = substr($class, $pos + 1);
- } else {
- // PEAR-like class name
- $classPath = null;
- $className = $class;
- }
-
- $classPath .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
-
- foreach ($this->prefixes as $prefix => $dirs) {
- if (0 === strpos($class, $prefix)) {
- foreach ($dirs as $dir) {
- if (file_exists($dir . DIRECTORY_SEPARATOR . $classPath)) {
- return $dir . DIRECTORY_SEPARATOR . $classPath;
- }
- }
- }
- }
-
- foreach ($this->fallbackDirs as $dir) {
- if (file_exists($dir . DIRECTORY_SEPARATOR . $classPath)) {
- return $dir . DIRECTORY_SEPARATOR . $classPath;
- }
- }
-
- if ($this->useIncludePath && $file = stream_resolve_include_path($classPath)) {
- return $file;
- }
- }
-}
+++ /dev/null
-<?php
-
-// autoload_classmap.php generated by Composer
-
-$vendorDir = dirname(__DIR__);
-$baseDir = dirname($vendorDir);
-
-return array(
-);
+++ /dev/null
-<?php
-
-// autoload_namespace.php generated by Composer
-
-$vendorDir = dirname(__DIR__);
-$baseDir = dirname($vendorDir);
-
-return array(
- 'Twig_Extensions_' => $vendorDir . '/twig/extensions/lib/',
- 'Twig_' => $vendorDir . '/twig/twig/lib/',
- 'Symfony\\Bundle\\SwiftmailerBundle' => $vendorDir . '/symfony/swiftmailer-bundle/',
- 'Symfony\\Bundle\\MonologBundle' => $vendorDir . '/symfony/monolog-bundle/',
- 'Symfony\\Bundle\\AsseticBundle' => $vendorDir . '/symfony/assetic-bundle/',
- 'Symfony' => $vendorDir . '/symfony/symfony/src/',
- 'SessionHandlerInterface' => $vendorDir . '/symfony/symfony/src/Symfony/Component/HttpFoundation/Resources/stubs',
- 'Sensio\\Bundle\\GeneratorBundle' => $vendorDir . '/sensio/generator-bundle/',
- 'Sensio\\Bundle\\FrameworkExtraBundle' => $vendorDir . '/sensio/framework-extra-bundle/',
- 'Sensio\\Bundle\\DistributionBundle' => $vendorDir . '/sensio/distribution-bundle/',
- 'Monolog' => $vendorDir . '/monolog/monolog/src/',
- 'Metadata\\' => $vendorDir . '/jms/metadata/src/',
- 'JMS\\SecurityExtraBundle' => $vendorDir . '/jms/security-extra-bundle/',
- 'JMS\\DiExtraBundle' => $vendorDir . '/jms/di-extra-bundle/',
- 'JMS\\AopBundle' => $vendorDir . '/jms/aop-bundle/',
- 'Doctrine\\ORM' => $vendorDir . '/doctrine/orm/lib/',
- 'Doctrine\\DBAL' => $vendorDir . '/doctrine/dbal/lib/',
- 'Doctrine\\Common\\DataFixtures' => $vendorDir . '/doctrine/data-fixtures/lib/',
- 'Doctrine\\Common' => $vendorDir . '/doctrine/common/lib/',
- 'Doctrine\\Bundle\\FixturesBundle' => $vendorDir . '/doctrine/doctrine-fixtures-bundle/',
- 'Doctrine\\Bundle\\DoctrineBundle' => $vendorDir . '/doctrine/doctrine-bundle/',
- 'CG\\' => $vendorDir . '/jms/cg/src/',
- 'Assetic' => $vendorDir . '/kriswallsmith/assetic/src/',
- '' => $baseDir . '/src/',
-);
+++ /dev/null
-[
- {
- "name": "doctrine/common",
- "version": "2.2.2",
- "version_normalized": "2.2.2.0",
- "time": "2012-04-13 07:46:44",
- "source": {
- "type": "git",
- "url": "https://github.com/doctrine/common",
- "reference": "2.2.2"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/doctrine/common/zipball/2.2.2",
- "reference": "2.2.2",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.2"
- },
- "type": "library",
- "installation-source": "dist",
- "license": [
- "LGPL"
- ],
- "authors": [
- {
- "name": "Jonathan Wage",
- "email": "jonwage@gmail.com",
- "homepage": "http://www.jwage.com/",
- "role": null
- },
- {
- "name": "Guilherme Blanco",
- "email": "guilhermeblanco@gmail.com",
- "homepage": null,
- "role": null
- },
- {
- "name": "Roman Borschel",
- "email": "roman@code-factory.org",
- "homepage": null,
- "role": null
- },
- {
- "name": "Benjamin Eberlei",
- "email": "kontakt@beberlei.de",
- "homepage": null,
- "role": null
- },
- {
- "name": "Johannes M. Schmitt",
- "email": "schmittjoh@gmail.com",
- "homepage": "https://github.com/schmittjoh",
- "role": null
- }
- ],
- "description": "Common Library for Doctrine projects",
- "homepage": "http://www.doctrine-project.org",
- "keywords": [
- "collections",
- "spl",
- "eventmanager",
- "annotations",
- "persistence"
- ],
- "autoload": {
- "psr-0": {
- "Doctrine\\Common": "lib/"
- }
- }
- },
- {
- "name": "twig/twig",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "time": "2012-07-13 06:40:06",
- "source": {
- "type": "git",
- "url": "git://github.com/fabpot/Twig.git",
- "reference": "0d5a63993726057d28d68884112cc48508ab835e"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/fabpot/Twig/zipball/0d5a63993726057d28d68884112cc48508ab835e",
- "reference": "0d5a63993726057d28d68884112cc48508ab835e",
- "shasum": ""
- },
- "require": {
- "php": ">=5.2.4"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.9-dev"
- }
- },
- "installation-source": "source",
- "license": [
- "BSD-3"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com",
- "homepage": null,
- "role": null
- },
- {
- "name": "Armin Ronacher",
- "email": "armin.ronacher@active-4.com",
- "homepage": null,
- "role": null
- }
- ],
- "description": "Twig, the flexible, fast, and secure template language for PHP",
- "homepage": "http://twig.sensiolabs.org",
- "keywords": [
- "templating"
- ],
- "autoload": {
- "psr-0": {
- "Twig_": "lib/"
- }
- }
- },
- {
- "name": "symfony/symfony",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "time": "2012-07-13 07:48:10",
- "source": {
- "type": "git",
- "url": "git://github.com/symfony/symfony.git",
- "reference": "bd1890715078abd06241a65c721d5e2429cc3ac4"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/symfony/symfony/zipball/bd1890715078abd06241a65c721d5e2429cc3ac4",
- "reference": "bd1890715078abd06241a65c721d5e2429cc3ac4",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3",
- "twig/twig": ">=1.8,<2.0-dev",
- "doctrine/common": ">2.2,<2.4-dev"
- },
- "replace": {
- "symfony/doctrine-bridge": "self.version",
- "symfony/monolog-bridge": "self.version",
- "symfony/twig-bridge": "self.version",
- "symfony/framework-bundle": "self.version",
- "symfony/security-bundle": "self.version",
- "symfony/twig-bundle": "self.version",
- "symfony/web-profiler-bundle": "self.version",
- "symfony/browser-kit": "self.version",
- "symfony/class-loader": "self.version",
- "symfony/config": "self.version",
- "symfony/console": "self.version",
- "symfony/css-selector": "self.version",
- "symfony/dependency-injection": "self.version",
- "symfony/dom-crawler": "self.version",
- "symfony/event-dispatcher": "self.version",
- "symfony/filesystem": "self.version",
- "symfony/finder": "self.version",
- "symfony/form": "self.version",
- "symfony/http-foundation": "self.version",
- "symfony/http-kernel": "self.version",
- "symfony/locale": "self.version",
- "symfony/process": "self.version",
- "symfony/routing": "self.version",
- "symfony/security": "self.version",
- "symfony/serializer": "self.version",
- "symfony/templating": "self.version",
- "symfony/translation": "self.version",
- "symfony/validator": "self.version",
- "symfony/yaml": "self.version",
- "symfony/propel1-bridge": "self.version",
- "symfony/options-resolver": "self.version",
- "symfony/swiftmailer-bridge": "self.version"
- },
- "require-dev": {
- "doctrine/data-fixtures": "1.0.*",
- "propel/propel1": "dev-master",
- "monolog/monolog": "dev-master",
- "doctrine/dbal": ">=2.2,<2.4-dev",
- "doctrine/orm": ">=2.2,<2.4-dev"
- },
- "suggest": {
- "doctrine/data-fixtures": "1.0.*"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "2.1-dev"
- }
- },
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com",
- "homepage": null,
- "role": null
- },
- {
- "name": "Symfony Community",
- "email": null,
- "homepage": "http://symfony.com/contributors",
- "role": null
- }
- ],
- "description": "The Symfony PHP framework",
- "homepage": "http://symfony.com",
- "keywords": [
- "framework"
- ],
- "autoload": {
- "psr-0": {
- "Symfony": "src/",
- "SessionHandlerInterface": "src/Symfony/Component/HttpFoundation/Resources/stubs"
- }
- }
- },
- {
- "name": "doctrine/dbal",
- "version": "2.2.x-dev",
- "version_normalized": "2.2.9999999.9999999-dev",
- "time": "2012-07-08 20:30:35",
- "source": {
- "type": "git",
- "url": "https://github.com/doctrine/dbal",
- "reference": "b961a3fce6bf220f1dca47d7d747b9074bea4730"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/doctrine/dbal/zipball/b961a3fce6bf220f1dca47d7d747b9074bea4730",
- "reference": "b961a3fce6bf220f1dca47d7d747b9074bea4730",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.2",
- "doctrine/common": ">=2.2.0,<=2.2.99"
- },
- "type": "library",
- "installation-source": "source",
- "license": [
- "LGPL"
- ],
- "authors": [
- {
- "name": "Jonathan Wage",
- "email": "jonwage@gmail.com",
- "homepage": "http://www.jwage.com/",
- "role": null
- },
- {
- "name": "Guilherme Blanco",
- "email": "guilhermeblanco@gmail.com",
- "homepage": null,
- "role": null
- },
- {
- "name": "Roman Borschel",
- "email": "roman@code-factory.org",
- "homepage": null,
- "role": null
- },
- {
- "name": "Benjamin Eberlei",
- "email": "kontakt@beberlei.de",
- "homepage": null,
- "role": null
- }
- ],
- "description": "Database Abstraction Layer",
- "homepage": "http://www.doctrine-project.org",
- "keywords": [
- "database",
- "persistence",
- "dbal",
- "queryobject"
- ],
- "autoload": {
- "psr-0": {
- "Doctrine\\DBAL": "lib/"
- }
- }
- },
- {
- "name": "doctrine/doctrine-bundle",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "target-dir": "Doctrine/Bundle/DoctrineBundle",
- "time": "2012-07-04 12:42:17",
- "source": {
- "type": "git",
- "url": "git://github.com/doctrine/DoctrineBundle.git",
- "reference": "c9ea46d1f0c48bb88bb87b44214fe44e03c0c692"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/doctrine/DoctrineBundle/zipball/c9ea46d1f0c48bb88bb87b44214fe44e03c0c692",
- "reference": "c9ea46d1f0c48bb88bb87b44214fe44e03c0c692",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.2",
- "doctrine/dbal": ">=2.2,<2.4-dev",
- "symfony/framework-bundle": "2.1.*",
- "symfony/doctrine-bridge": "2.1.*"
- },
- "require-dev": {
- "doctrine/orm": ">=2.2,<2.4-dev",
- "symfony/validator": "2.1.*",
- "symfony/yaml": "2.1.*"
- },
- "suggest": {
- "doctrine/orm": "The Doctrine ORM integration is optional in the bundle."
- },
- "type": "symfony-bundle",
- "extra": {
- "branch-alias": {
- "dev-master": "1.0.x-dev"
- }
- },
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com",
- "homepage": null,
- "role": null
- },
- {
- "name": "Symfony Community",
- "email": null,
- "homepage": "http://symfony.com/contributors",
- "role": null
- },
- {
- "name": "Benjamin Eberlei",
- "email": "kontakt@beberlei.de",
- "homepage": null,
- "role": null
- }
- ],
- "description": "Symfony DoctrineBundle",
- "homepage": "http://www.doctrine-project.org",
- "keywords": [
- "database",
- "orm",
- "persistence",
- "dbal"
- ],
- "autoload": {
- "psr-0": {
- "Doctrine\\Bundle\\DoctrineBundle": ""
- }
- }
- },
- {
- "name": "twig/extensions",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "time": "2012-05-21 11:28:19",
- "source": {
- "type": "git",
- "url": "https://github.com/fabpot/Twig-extensions",
- "reference": "feb6d3f10c411e2631997c0a905aa581c80305c1"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/fabpot/Twig-extensions/zipball/feb6d3f10c411e2631997c0a905aa581c80305c1",
- "reference": "feb6d3f10c411e2631997c0a905aa581c80305c1",
- "shasum": ""
- },
- "require": {
- "twig/twig": "1.*"
- },
- "type": "library",
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com",
- "homepage": null,
- "role": null
- }
- ],
- "description": "Common additional features for Twig that do not directly belong in core",
- "homepage": "https://github.com/fabpot/Twig-extensions",
- "keywords": [
- "debug",
- "i18n",
- "text"
- ],
- "autoload": {
- "psr-0": {
- "Twig_Extensions_": "lib/"
- }
- }
- },
- {
- "name": "kriswallsmith/assetic",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "time": "2012-06-12 15:41:54",
- "source": {
- "type": "git",
- "url": "http://github.com/kriswallsmith/assetic.git",
- "reference": "d6f89a3170c5280ad554347dc113eb25fdf00ad7"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/kriswallsmith/assetic/zipball/d6f89a3170c5280ad554347dc113eb25fdf00ad7",
- "reference": "d6f89a3170c5280ad554347dc113eb25fdf00ad7",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.0",
- "symfony/process": "2.1.*"
- },
- "require-dev": {
- "twig/twig": ">=1.6.0,<2.0",
- "leafo/lessphp": "*"
- },
- "suggest": {
- "twig/twig": "Assetic provides the integration with the Twig templating engine",
- "leafo/lessphp": "Assetic provides the integration with the lessphp LESS compiler"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.1-dev"
- }
- },
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Kris Wallsmith",
- "email": "kris.wallsmith@gmail.com",
- "homepage": "http://kriswallsmith.net/",
- "role": null
- }
- ],
- "description": "Asset Management for PHP",
- "homepage": "https://github.com/kriswallsmith/assetic",
- "keywords": [
- "assets",
- "compression",
- "minification"
- ],
- "autoload": {
- "psr-0": {
- "Assetic": "src/"
- }
- }
- },
- {
- "name": "symfony/assetic-bundle",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "target-dir": "Symfony/Bundle/AsseticBundle",
- "time": "2012-07-12 20:51:17",
- "source": {
- "type": "git",
- "url": "https://github.com/symfony/AsseticBundle",
- "reference": "ed933dcfa45f00b6bc6d7727007403f3ff429e5a"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/symfony/AsseticBundle/zipball/ed933dcfa45f00b6bc6d7727007403f3ff429e5a",
- "reference": "ed933dcfa45f00b6bc6d7727007403f3ff429e5a",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.0",
- "symfony/framework-bundle": "2.1.*",
- "kriswallsmith/assetic": "1.1.*"
- },
- "suggest": {
- "symfony/twig-bundle": "2.1.*"
- },
- "type": "symfony-bundle",
- "extra": {
- "branch-alias": {
- "dev-master": "2.1.x-dev"
- }
- },
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Kris Wallsmith",
- "email": "kris.wallsmith@gmail.com",
- "homepage": "http://kriswallsmith.net/",
- "role": null
- }
- ],
- "description": "Integrates Assetic into Symfony2",
- "homepage": "https://github.com/symfony/AsseticBundle",
- "keywords": [
- "assets",
- "compression",
- "minification"
- ],
- "autoload": {
- "psr-0": {
- "Symfony\\Bundle\\AsseticBundle": ""
- }
- }
- },
- {
- "name": "swiftmailer/swiftmailer",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "time": "2012-07-10 19:39:15",
- "source": {
- "type": "git",
- "url": "git://github.com/swiftmailer/swiftmailer.git",
- "reference": "420e227f2238d2c21e464c15f103540d83b0d23b"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/swiftmailer/swiftmailer/zipball/420e227f2238d2c21e464c15f103540d83b0d23b",
- "reference": "420e227f2238d2c21e464c15f103540d83b0d23b",
- "shasum": ""
- },
- "require": {
- "php": ">=5.2.4"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "4.2-dev"
- }
- },
- "installation-source": "source",
- "license": [
- "LGPL"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com",
- "homepage": null,
- "role": null
- },
- {
- "name": "Chris Corbyn",
- "email": "",
- "homepage": null,
- "role": null
- }
- ],
- "description": "Swiftmailer, free feature-rich PHP mailer",
- "homepage": "http://swiftmailer.org",
- "keywords": [
- "mail",
- "mailer"
- ],
- "autoload": {
- "files": [
- "lib/swift_required.php"
- ]
- }
- },
- {
- "name": "symfony/swiftmailer-bundle",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "target-dir": "Symfony/Bundle/SwiftmailerBundle",
- "time": "2012-07-05 17:33:34",
- "source": {
- "type": "git",
- "url": "https://github.com/symfony/SwiftmailerBundle",
- "reference": "v2.1.0-BETA2"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/symfony/SwiftmailerBundle/zipball/v2.1.0-BETA2",
- "reference": "v2.1.0-BETA2",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.2",
- "symfony/swiftmailer-bridge": "2.1.*",
- "swiftmailer/swiftmailer": ">=4.2.0,<4.3-dev"
- },
- "require-dev": {
- "symfony/dependency-injection": "2.1.*",
- "symfony/http-kernel": "2.1.*",
- "symfony/config": "2.1.*"
- },
- "type": "symfony-bundle",
- "extra": {
- "branch-alias": {
- "dev-master": "2.1-dev"
- }
- },
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com",
- "homepage": null,
- "role": null
- },
- {
- "name": "Symfony Community",
- "email": null,
- "homepage": "http://symfony.com/contributors",
- "role": null
- }
- ],
- "description": "Symfony SwiftmailerBundle",
- "homepage": "http://symfony.com",
- "autoload": {
- "psr-0": {
- "Symfony\\Bundle\\SwiftmailerBundle": ""
- }
- }
- },
- {
- "name": "monolog/monolog",
- "version": "1.1.0",
- "version_normalized": "1.1.0.0",
- "time": "2012-04-23 16:27:40",
- "source": {
- "type": "git",
- "url": "https://github.com/Seldaek/monolog.git",
- "reference": "1.1.0"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/Seldaek/monolog/zipball/1.1.0",
- "reference": "1.1.0",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.0"
- },
- "require-dev": {
- "mlehner/gelf-php": "1.0.*"
- },
- "suggest": {
- "mlehner/gelf-php": "Allow sending log messages to a GrayLog2 server"
- },
- "type": "library",
- "installation-source": "dist",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Jordi Boggiano",
- "email": "j.boggiano@seld.be",
- "homepage": "http://seld.be",
- "role": "Developer"
- }
- ],
- "description": "Logging for PHP 5.3",
- "homepage": "http://github.com/Seldaek/monolog",
- "keywords": [
- "log",
- "logging"
- ],
- "autoload": {
- "psr-0": {
- "Monolog": "src/"
- }
- }
- },
- {
- "name": "symfony/monolog-bundle",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "target-dir": "Symfony/Bundle/MonologBundle",
- "time": "2012-06-30 17:48:07",
- "source": {
- "type": "git",
- "url": "https://github.com/symfony/MonologBundle",
- "reference": "v2.1.0-BETA2"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/symfony/MonologBundle/zipball/v2.1.0-BETA2",
- "reference": "v2.1.0-BETA2",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.2",
- "monolog/monolog": "1.*",
- "symfony/monolog-bridge": "2.1.*",
- "symfony/dependency-injection": "2.1.*",
- "symfony/config": "2.1.*"
- },
- "require-dev": {
- "symfony/yaml": "2.1.*",
- "symfony/config": "2.1.*"
- },
- "type": "symfony-bundle",
- "extra": {
- "branch-alias": {
- "dev-master": "2.1.x-dev"
- }
- },
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com",
- "homepage": null,
- "role": null
- },
- {
- "name": "Symfony Community",
- "email": null,
- "homepage": "http://symfony.com/contributors",
- "role": null
- }
- ],
- "description": "Symfony MonologBundle",
- "homepage": "http://symfony.com",
- "autoload": {
- "psr-0": {
- "Symfony\\Bundle\\MonologBundle": ""
- }
- }
- },
- {
- "name": "sensio/distribution-bundle",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "target-dir": "Sensio/Bundle/DistributionBundle",
- "time": "2012-07-13 06:02:13",
- "source": {
- "type": "git",
- "url": "https://github.com/sensio/SensioDistributionBundle",
- "reference": "77323c97860fc2f73d988b2020ae414faebed153"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/sensio/SensioDistributionBundle/zipball/77323c97860fc2f73d988b2020ae414faebed153",
- "reference": "77323c97860fc2f73d988b2020ae414faebed153",
- "shasum": ""
- },
- "require": {
- "symfony/framework-bundle": "2.1.*"
- },
- "type": "symfony-bundle",
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com",
- "homepage": null,
- "role": null
- }
- ],
- "description": "The base bundle for the Symfony Distributions",
- "keywords": [
- "distribution",
- "configuration"
- ],
- "autoload": {
- "psr-0": {
- "Sensio\\Bundle\\DistributionBundle": ""
- }
- }
- },
- {
- "name": "sensio/framework-extra-bundle",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "target-dir": "Sensio/Bundle/FrameworkExtraBundle",
- "time": "2012-07-12 09:13:52",
- "source": {
- "type": "git",
- "url": "https://github.com/sensio/SensioFrameworkExtraBundle",
- "reference": "e9ac8f1a911ed29e30296c7f1549f53d4c94eddf"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/sensio/SensioFrameworkExtraBundle/zipball/e9ac8f1a911ed29e30296c7f1549f53d4c94eddf",
- "reference": "e9ac8f1a911ed29e30296c7f1549f53d4c94eddf",
- "shasum": ""
- },
- "require": {
- "doctrine/common": ">=2.1,<2.4-dev",
- "symfony/framework-bundle": "2.1.*"
- },
- "type": "symfony-bundle",
- "extra": {
- "branch-alias": {
- "dev-master": "2.1.x-dev"
- }
- },
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com",
- "homepage": null,
- "role": null
- }
- ],
- "description": "This bundle provides a way to configure your controllers with annotations",
- "keywords": [
- "annotations",
- "controllers"
- ],
- "autoload": {
- "psr-0": {
- "Sensio\\Bundle\\FrameworkExtraBundle": ""
- }
- }
- },
- {
- "name": "sensio/generator-bundle",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "target-dir": "Sensio/Bundle/GeneratorBundle",
- "time": "2012-06-19 20:40:45",
- "source": {
- "type": "git",
- "url": "https://github.com/sensio/SensioGeneratorBundle",
- "reference": "43ed45c48db18e4a0e48aec0c098f42e56e22d36"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/sensio/SensioGeneratorBundle/zipball/43ed45c48db18e4a0e48aec0c098f42e56e22d36",
- "reference": "43ed45c48db18e4a0e48aec0c098f42e56e22d36",
- "shasum": ""
- },
- "require": {
- "symfony/framework-bundle": "2.1.*"
- },
- "require-dev": {
- "symfony/doctrine-bridge": "2.1.*",
- "doctrine/orm": ">=2.1,<2.4-dev",
- "twig/twig": ">=1.8,<2.0-dev"
- },
- "suggest": {
- "doctrine/doctrine-bundle": "to generate entities and their crud controller"
- },
- "type": "symfony-bundle",
- "extra": {
- "branch-alias": {
- "dev-master": "2.1.x-dev"
- }
- },
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com",
- "homepage": null,
- "role": null
- }
- ],
- "description": "This bundle generates code for you",
- "autoload": {
- "psr-0": {
- "Sensio\\Bundle\\GeneratorBundle": ""
- }
- }
- },
- {
- "name": "jms/cg",
- "version": "1.0.0",
- "version_normalized": "1.0.0.0",
- "time": "2012-01-02 20:40:52",
- "source": {
- "type": "git",
- "url": "git://github.com/schmittjoh/cg-library.git",
- "reference": "1.0.0"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/schmittjoh/cg-library/zipball/1.0.0",
- "reference": "1.0.0",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.0"
- },
- "type": "library",
- "installation-source": "dist",
- "license": [
- "Apache"
- ],
- "authors": [
- {
- "name": "Johannes M. Schmitt",
- "email": "schmittjoh@gmail.com",
- "homepage": "https://github.com/schmittjoh",
- "role": null
- }
- ],
- "description": "Toolset for generating PHP code",
- "keywords": [
- "code generation"
- ],
- "autoload": {
- "psr-0": {
- "CG\\": "src/"
- }
- }
- },
- {
- "name": "jms/aop-bundle",
- "version": "1.0.0",
- "version_normalized": "1.0.0.0",
- "target-dir": "JMS/AopBundle",
- "time": "2012-01-02 20:50:26",
- "source": {
- "type": "git",
- "url": "https://github.com/schmittjoh/JMSAopBundle",
- "reference": "1.0.0"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/schmittjoh/JMSAopBundle/zipball/1.0.0",
- "reference": "1.0.0",
- "shasum": ""
- },
- "require": {
- "symfony/framework-bundle": "2.*",
- "jms/cg": "1.0.0"
- },
- "type": "symfony-bundle",
- "installation-source": "dist",
- "license": [
- "Apache"
- ],
- "authors": [
- {
- "name": "Johannes M. Schmitt",
- "email": "schmittjoh@gmail.com",
- "homepage": "https://github.com/schmittjoh",
- "role": null
- }
- ],
- "description": "Adds AOP capabilities to Symfony2",
- "keywords": [
- "annotations",
- "aop"
- ],
- "autoload": {
- "psr-0": {
- "JMS\\AopBundle": ""
- }
- }
- },
- {
- "name": "jms/metadata",
- "version": "1.1.1",
- "version_normalized": "1.1.1.0",
- "time": "2012-01-02 21:32:49",
- "source": {
- "type": "git",
- "url": "https://github.com/schmittjoh/metadata",
- "reference": "1.1.1"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/schmittjoh/metadata/zipball/1.1.1",
- "reference": "1.1.1",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.0"
- },
- "type": "library",
- "installation-source": "dist",
- "license": [
- "Apache"
- ],
- "authors": [
- {
- "name": "Johannes M. Schmitt",
- "email": "schmittjoh@gmail.com",
- "homepage": "https://github.com/schmittjoh",
- "role": null
- }
- ],
- "description": "Class/method/property metadata management in PHP",
- "keywords": [
- "annotations",
- "yaml",
- "xml",
- "metadata"
- ],
- "autoload": {
- "psr-0": {
- "Metadata\\": "src/"
- }
- }
- },
- {
- "name": "jms/security-extra-bundle",
- "version": "1.1.0",
- "version_normalized": "1.1.0.0",
- "target-dir": "JMS/SecurityExtraBundle",
- "time": "2012-01-02 21:38:12",
- "source": {
- "type": "git",
- "url": "https://github.com/schmittjoh/JMSSecurityExtraBundle",
- "reference": "1.1.0"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/schmittjoh/JMSSecurityExtraBundle/zipball/1.1.0",
- "reference": "1.1.0",
- "shasum": ""
- },
- "require": {
- "symfony/framework-bundle": "2.*",
- "jms/metadata": "1.1.*",
- "jms/aop-bundle": "1.0.*"
- },
- "type": "symfony-bundle",
- "installation-source": "dist",
- "license": [
- "Apache"
- ],
- "authors": [
- {
- "name": "Johannes M. Schmitt",
- "email": "schmittjoh@gmail.com",
- "homepage": "https://github.com/schmittjoh",
- "role": null
- }
- ],
- "description": "Enhances the Symfony2 Security Component by adding several new features",
- "keywords": [
- "annotations",
- "authorization"
- ],
- "autoload": {
- "psr-0": {
- "JMS\\SecurityExtraBundle": ""
- }
- }
- },
- {
- "name": "doctrine/data-fixtures",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "time": "2012-07-08 20:48:55",
- "source": {
- "type": "git",
- "url": "https://github.com/doctrine/data-fixtures.git",
- "reference": "779c3dfe446b6da893be87b908d6be28345d1e01"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/doctrine/data-fixtures/zipball/779c3dfe446b6da893be87b908d6be28345d1e01",
- "reference": "779c3dfe446b6da893be87b908d6be28345d1e01",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.2"
- },
- "type": "library",
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Jonathan Wage",
- "email": "jonwage@gmail.com",
- "homepage": "http://www.jwage.com/",
- "role": null
- }
- ],
- "description": "Data Fixtures for all Doctrine Object Managers",
- "homepage": "http://www.doctrine-project.org",
- "keywords": [
- "database"
- ],
- "autoload": {
- "psr-0": {
- "Doctrine\\Common\\DataFixtures": "lib/"
- }
- }
- },
- {
- "name": "doctrine/doctrine-fixtures-bundle",
- "version": "dev-master",
- "version_normalized": "9999999-dev",
- "target-dir": "Doctrine/Bundle/FixturesBundle",
- "time": "2012-07-05 07:20:47",
- "source": {
- "type": "git",
- "url": "https://github.com/doctrine/DoctrineFixturesBundle.git",
- "reference": "a5103a71bcd9b2f851ca6c16519a077784a3184a"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/doctrine/DoctrineFixturesBundle/zipball/a5103a71bcd9b2f851ca6c16519a077784a3184a",
- "reference": "a5103a71bcd9b2f851ca6c16519a077784a3184a",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.2",
- "doctrine/data-fixtures": "*",
- "symfony/doctrine-bridge": "2.1.*",
- "doctrine/doctrine-bundle": "1.0.*"
- },
- "type": "symfony-bundle",
- "installation-source": "source",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com",
- "homepage": null,
- "role": null
- },
- {
- "name": "Symfony Community",
- "email": null,
- "homepage": "http://symfony.com/contributors",
- "role": null
- },
- {
- "name": "Doctrine Project",
- "email": null,
- "homepage": "http://www.doctrine-project.org",
- "role": null
- }
- ],
- "description": "Symfony DoctrineFixturesBundle",
- "homepage": "http://www.doctrine-project.org",
- "keywords": [
- "persistence",
- "Fixture"
- ],
- "autoload": {
- "psr-0": {
- "Doctrine\\Bundle\\FixturesBundle": ""
- }
- }
- },
- {
- "name": "jms/di-extra-bundle",
- "version": "1.0.1",
- "version_normalized": "1.0.1.0",
- "target-dir": "JMS/DiExtraBundle",
- "time": "2012-02-28 05:01:54",
- "source": {
- "type": "git",
- "url": "https://github.com/schmittjoh/JMSDiExtraBundle",
- "reference": "1.0.1"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/schmittjoh/JMSDiExtraBundle/zipball/1.0.1",
- "reference": "1.0.1",
- "shasum": ""
- },
- "require": {
- "symfony/framework-bundle": "2.*",
- "jms/metadata": "1.1.*"
- },
- "type": "symfony-bundle",
- "installation-source": "dist",
- "license": [
- "Apache"
- ],
- "authors": [
- {
- "name": "Johannes M. Schmitt",
- "email": "schmittjoh@gmail.com",
- "homepage": "https://github.com/schmittjoh",
- "role": null
- }
- ],
- "description": "Allows to configure dependency injection using annotations",
- "keywords": [
- "dependency injection",
- "annotations"
- ],
- "autoload": {
- "psr-0": {
- "JMS\\DiExtraBundle": ""
- }
- }
- },
- {
- "name": "doctrine/orm",
- "version": "2.2.x-dev",
- "version_normalized": "2.2.9999999.9999999-dev",
- "time": "2012-07-07 15:48:00",
- "source": {
- "type": "git",
- "url": "git://github.com/doctrine/doctrine2.git",
- "reference": "5d2a3bcb3b467f41ee58575764f3ba84937f76e4"
- },
- "dist": {
- "type": "zip",
- "url": "https://github.com/doctrine/doctrine2/zipball/5d2a3bcb3b467f41ee58575764f3ba84937f76e4",
- "reference": "5d2a3bcb3b467f41ee58575764f3ba84937f76e4",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.2",
- "ext-pdo": "*",
- "doctrine/common": "2.2.*",
- "doctrine/dbal": "2.2.*"
- },
- "type": "library",
- "installation-source": "source",
- "license": [
- "LGPL"
- ],
- "authors": [
- {
- "name": "Jonathan Wage",
- "email": "jonwage@gmail.com",
- "homepage": "http://www.jwage.com/",
- "role": null
- },
- {
- "name": "Guilherme Blanco",
- "email": "guilhermeblanco@gmail.com",
- "homepage": null,
- "role": null
- },
- {
- "name": "Roman Borschel",
- "email": "roman@code-factory.org",
- "homepage": null,
- "role": null
- },
- {
- "name": "Benjamin Eberlei",
- "email": "kontakt@beberlei.de",
- "homepage": null,
- "role": null
- }
- ],
- "description": "Object-Relational-Mapper for PHP",
- "homepage": "http://www.doctrine-project.org",
- "keywords": [
- "database",
- "orm"
- ],
- "autoload": {
- "psr-0": {
- "Doctrine\\ORM": "lib/"
- }
- }
- }
-]
+++ /dev/null
-Subproject commit e1647229cd2544bd77f10620e1b95a5781c4a733
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Aop;
-
-use CG\Proxy\InterceptorLoaderInterface;
-use Symfony\Component\DependencyInjection\ContainerInterface;
-
-/**
- * Lazy-loading interceptor loader implementation.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class InterceptorLoader implements InterceptorLoaderInterface
-{
- private $container;
- private $interceptors;
- private $loadedInterceptors = array();
-
- public function __construct(ContainerInterface $container, array $interceptors)
- {
- $this->container = $container;
- $this->interceptors = $interceptors;
- }
-
- public function loadInterceptors(\ReflectionMethod $method)
- {
- if (!isset($this->interceptors[$method->class][$method->name])) {
- return array();
- }
-
- if (isset($this->loadedInterceptors[$method->class][$method->name])) {
- return $this->loadedInterceptors[$method->class][$method->name];
- }
-
- $interceptors = array();
- foreach ($this->interceptors[$method->class][$method->name] as $id) {
- $interceptors[] = $this->container->get($id);
- }
-
- return $this->loadedInterceptors[$method->class][$method->name] = $interceptors;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Aop;
-
-final class PointcutContainer
-{
- private $pointcuts;
-
- public function __construct(array $pointcuts)
- {
- $this->pointcuts = $pointcuts;
- }
-
- public function getPointcuts()
- {
- return $this->pointcuts;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Aop;
-
-/**
- * Pointcut Interface.
- *
- * Implementations of this class are responsible for making a decision on whether
- * a certain method call matches the advice which is associated with this pointcut.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface PointcutInterface
-{
- /**
- * Determines whether the advice applies to instances of the given class.
- *
- * There are some limits as to what you can do in this method. Namely, you may
- * only base your decision on resources that are part of the ContainerBuilder.
- * Specifically, you may not use any data in the class itself, such as
- * annotations.
- *
- * @param \ReflectionClass $class
- * @return boolean
- */
- function matchesClass(\ReflectionClass $class);
-
- /**
- * Determines whether the advice applies to the given method.
- *
- * This method is not limited in the way the matchesClass method is. It may
- * use information in the associated class to make its decision.
- *
- * @param \ReflectionMethod $method
- * @return boolean
- */
- function matchesMethod(\ReflectionMethod $method);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Aop;
-
-/**
- * A regex pointcut implementation.
- *
- * Uses a regular expression for determining whether the pointcut matches.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class RegexPointcut implements PointcutInterface
-{
- private $pattern;
-
- public function __construct($pattern)
- {
- $this->pattern = $pattern;
- }
-
- public function matchesClass(\ReflectionClass $class)
- {
- return true;
- }
-
- public function matchesMethod(\ReflectionMethod $method)
- {
- return 0 < preg_match('#'.$this->pattern.'#', sprintf('%s::%s', $method->class, $method->name));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\DependencyInjection\Compiler;
-
-use CG\Core\ClassUtils;
-
-use JMS\AopBundle\Exception\RuntimeException;
-use Symfony\Component\Config\Resource\FileResource;
-use Symfony\Component\DependencyInjection\Reference;
-use CG\Proxy\Enhancer;
-use CG\Proxy\InterceptionGenerator;
-use Symfony\Component\DependencyInjection\Definition;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
-
-/**
- * Matches pointcuts against service methods.
- *
- * This pass will collect the advices that match a certain method, and then
- * generate proxy classes where necessary.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class PointcutMatchingPass implements CompilerPassInterface
-{
- private $pointcuts;
- private $cacheDir;
- private $container;
-
- public function __construct(array $pointcuts = null)
- {
- $this->pointcuts = $pointcuts;
- }
-
- public function process(ContainerBuilder $container)
- {
- $this->container = $container;
- $this->cacheDir = $container->getParameter('jms_aop.cache_dir').'/proxies';
- $pointcuts = $this->getPointcuts();
-
- $interceptors = array();
- foreach ($container->getDefinitions() as $id => $definition) {
- $this->processDefinition($definition, $pointcuts, $interceptors);
-
- $this->processInlineDefinitions($pointcuts, $interceptors, $definition->getArguments());
- $this->processInlineDefinitions($pointcuts, $interceptors, $definition->getMethodCalls());
- $this->processInlineDefinitions($pointcuts, $interceptors, $definition->getProperties());
- }
-
- $container
- ->getDefinition('jms_aop.interceptor_loader')
- ->addArgument($interceptors)
- ;
- }
-
- private function processInlineDefinitions($pointcuts, &$interceptors, array $a) {
- foreach ($a as $k => $v) {
- if ($v instanceof Definition) {
- $this->processDefinition($v, $pointcuts, $interceptors);
- } else if (is_array($v)) {
- $this->processInlineDefinitions($pointcuts, $interceptors, $v);
- }
- }
- }
-
- private function processDefinition(Definition $definition, $pointcuts, &$interceptors)
- {
- if ($definition->isSynthetic()) {
- return;
- }
-
- if ($definition->getFactoryService() || $definition->getFactoryClass()) {
- return;
- }
-
- if ($file = $definition->getFile()) {
- require_once $file;
- }
-
- if (!class_exists($definition->getClass())) {
- return;
- }
-
- $class = new \ReflectionClass($definition->getClass());
-
- // check if class is matched
- $matchingPointcuts = array();
- foreach ($pointcuts as $interceptor => $pointcut) {
- if ($pointcut->matchesClass($class)) {
- $matchingPointcuts[$interceptor] = $pointcut;
- }
- }
-
- if (empty($matchingPointcuts)) {
- return;
- }
-
- $this->addResources($class, $this->container);
-
- if ($class->isFinal()) {
- return;
- }
-
- $classAdvices = array();
- foreach ($class->getMethods(\ReflectionMethod::IS_PROTECTED | \ReflectionMethod::IS_PUBLIC) as $method) {
- if ($method->isFinal()) {
- continue;
- }
-
- $advices = array();
- foreach ($matchingPointcuts as $interceptor => $pointcut) {
- if ($pointcut->matchesMethod($method)) {
- $advices[] = $interceptor;
- }
- }
-
- if (empty($advices)) {
- continue;
- }
-
- $classAdvices[$method->name] = $advices;
- }
-
- if (empty($classAdvices)) {
- return;
- }
-
- $interceptors[ClassUtils::getUserClass($class->name)] = $classAdvices;
-
- $generator = new InterceptionGenerator();
- $generator->setFilter(function(\ReflectionMethod $method) use ($classAdvices) {
- return isset($classAdvices[$method->name]);
- });
- if ($file) {
- $generator->setRequiredFile($file);
- }
- $enhancer = new Enhancer($class, array(), array(
- $generator
- ));
- $enhancer->writeClass($filename = $this->cacheDir.'/'.str_replace('\\', '-', $class->name).'.php');
- $definition->setFile($filename);
- $definition->setClass($enhancer->getClassName($class));
- $definition->addMethodCall('__CGInterception__setLoader', array(
- new Reference('jms_aop.interceptor_loader')
- ));
- }
-
- private function addResources(\ReflectionClass $class)
- {
- do {
- $this->container->addResource(new FileResource($class->getFilename()));
- } while (($class = $class->getParentClass()) && $class->getFilename());
- }
-
- private function getPointcuts()
- {
- if (null !== $this->pointcuts) {
- return $this->pointcuts;
- }
-
- $pointcuts = $pointcutReferences = array();
-
- foreach ($this->container->findTaggedServiceIds('jms_aop.pointcut') as $id => $attr) {
- if (!isset($attr[0]['interceptor'])) {
- throw new RuntimeException('You need to set the "interceptor" attribute for the "jms_aop.pointcut" tag of service "'.$id.'".');
- }
-
- $pointcutReferences[$attr[0]['interceptor']] = new Reference($id);
- $pointcuts[$attr[0]['interceptor']] = $this->container->get($id);
- }
-
- $this->container
- ->getDefinition('jms_aop.pointcut_container')
- ->addArgument($pointcutReferences)
- ;
-
- return $pointcuts;
- }
-}
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\DependencyInjection;
-
-use Symfony\Component\Config\Definition\Builder\TreeBuilder;
-use Symfony\Component\Config\Definition\ConfigurationInterface;
-
-/**
- * This is the class that validates and merges configuration from your app/config files
- *
- * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
- */
-class Configuration implements ConfigurationInterface
-{
- /**
- * {@inheritDoc}
- */
- public function getConfigTreeBuilder()
- {
- $treeBuilder = new TreeBuilder();
- $treeBuilder->root('jms_aop')
- ->children()
- ->scalarNode('cache_dir')->cannotBeEmpty()->defaultValue('%kernel.cache_dir%/jms_aop')->end()
- ->end()
- ;
-
- return $treeBuilder;
- }
-}
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\DependencyInjection;
-
-use JMS\AopBundle\Exception\RuntimeException;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\Config\FileLocator;
-use Symfony\Component\HttpKernel\DependencyInjection\Extension;
-use Symfony\Component\DependencyInjection\Loader;
-
-/**
- * JMSAopExtension.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class JMSAopExtension extends Extension
-{
- /**
- * {@inheritDoc}
- */
- public function load(array $configs, ContainerBuilder $container)
- {
- $configuration = new Configuration();
- $config = $this->processConfiguration($configuration, $configs);
-
- $cacheDir = $container->getParameterBag()->resolveValue($config['cache_dir']);
- if (!is_dir($cacheDir)) {
- if (false === @mkdir($cacheDir, 0777, true)) {
- throw new RuntimeException(sprintf('Could not create cache directory "%s".', $cacheDir));
- }
- }
- $container->setParameter('jms_aop.cache_dir', $cacheDir);
-
- $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
- $loader->load('services.xml');
- }
-}
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Exception;
-
-/**
- * Base exception for the AopBundle.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface Exception
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Exception;
-
-/**
- * RuntimeException for the AopBundle.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class RuntimeException extends \RuntimeException implements Exception
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle;
-
-use Symfony\Component\DependencyInjection\Compiler\PassConfig;
-use JMS\AopBundle\DependencyInjection\Compiler\PointcutMatchingPass;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\HttpKernel\Bundle\Bundle;
-
-class JMSAopBundle extends Bundle
-{
- const VERSION = '1.0.0';
-
- public function build(ContainerBuilder $container)
- {
- $container->addCompilerPass(new PointcutMatchingPass(), PassConfig::TYPE_AFTER_REMOVING);
- }
-}
+++ /dev/null
-For documentation, see:
-
- Resources/doc
-
-
-For license, see:
-
- Resources/meta/LICENSE
\ No newline at end of file
+++ /dev/null
-<?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">
-
- <parameters>
- <parameter key="jms_aop.interceptor_loader.class">JMS\AopBundle\Aop\InterceptorLoader</parameter>
- </parameters>
-
- <services>
- <service id="jms_aop.pointcut_container" class="JMS\AopBundle\Aop\PointcutContainer" />
-
- <service id="jms_aop.interceptor_loader" class="%jms_aop.interceptor_loader.class%">
- <argument type="service" id="service_container" />
- </service>
- </services>
-</container>
+++ /dev/null
-========
-Overview
-========
-
-This bundle adds AOP capabilities to Symfony2.
-
-If you haven't heard of AOP yet, it basically allows you to separate a
-cross-cutting concern (for example, security checks) into a dedicated class,
-and not having to repeat that code in all places where it is needed.
-
-In other words, this allows you to execute custom code before, and after the
-invocation of certain methods in your service layer, or your controllers. You
-can also choose to skip the invocation of the original method, or throw exceptions.
-
-Installation
-------------
-Checkout a copy of the code::
-
- git submodule add https://github.com/schmittjoh/JMSAopBundle.git src/JMS/AopBundle
-
-Then register the bundle with your kernel::
-
- // in AppKernel::registerBundles()
- $bundles = array(
- // ...
- new JMS\AopBundle\JMSAopBundle(),
- // ...
- );
-
-This bundle also requires the CG library for code generation::
-
- git submodule add https://github.com/schmittjoh/cg-library.git vendor/cg-library
-
-Make sure that you also register the namespaces with the autoloader::
-
- // app/autoload.php
- $loader->registerNamespaces(array(
- // ...
- 'JMS' => __DIR__.'/../vendor/bundles',
- 'CG' => __DIR__.'/../vendor/cg-library/src',
- // ...
- ));
-
-
-Configuration
--------------
-::
-
- jms_aop:
- cache_dir: %kernel.cache_dir%/jms_aop
-
-
-Usage
------
-In order to execute custom code, you need two classes. First, you need a so-called
-pointcut. The purpose of this class is to make a decision whether a method call
-should be intercepted by a certain interceptor. This decision has to be made
-statically only on the basis of the method signature itself.
-
-The second class is the interceptor. This class is being called instead
-of the original method. It contains the custom code that you would like to
-execute. At this point, you have access to the object on which the method is
-called, and all the arguments which were passed to that method.
-
-Examples
---------
-
-1. Logging
-~~~~~~~~~~
-
-In this example, we will be implementing logging for all methods that contain
-"delete".
-
-Pointcut
-^^^^^^^^
-
-::
-
- <?php
-
- use JMS\AopBundle\Aop\PointcutInterface;
-
- class LoggingPointcut implements PointcutInterface
- {
- public function matchesClass(\ReflectionClass $class)
- {
- return true;
- }
-
- public function matchesMethod(\ReflectionMethod $method)
- {
- return false !== strpos($method->name, 'delete');
- }
- }
-
-::
-
- # services.yml
- services:
- my_logging_pointcut:
- class: LoggingPointcut
- tags:
- - { name: jms_aop.pointcut, interceptor: logging_interceptor }
-
-
-LoggingInterceptor
-^^^^^^^^^^^^^^^^^^
-
-::
-
- <?php
-
- use CG\Proxy\MethodInterceptorInterface;
- use CG\Proxy\MethodInvocation;
- use Symfony\Component\HttpKernel\Log\LoggerInterface;
- use Symfony\Component\Security\Core\SecurityContextInterface;
-
- class LoggingInterceptor implements MethodInterceptorInterface
- {
- private $context;
- private $logger;
-
- public function __construct(SecurityContextInterface $context,
- LoggerInterface $logger)
- {
- $this->context = $context;
- $this->logger = $logger;
- }
-
- public function intercept(MethodInvocation $invocation)
- {
- $user = $this->context->getToken()->getUsername();
- $this->logger->info(sprintf('User "%s" invoked method "%s".', $user, $invocation->reflection->name));
-
- // make sure to proceed with the invocation otherwise the original
- // method will never be called
- return $invocation->proceed();
- }
- }
-
-::
-
- # services.yml
- services:
- logging_interceptor:
- class: LoggingInterceptor
- arguments: [@security.context, @logger]
-
-
-2. Transaction Management
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-In this example, we add a @Transactional annotation, and we automatically wrap all methods
-where this annotation is declared in a transaction.
-
-Pointcut
-^^^^^^^^
-
-::
-
- use Doctrine\Common\Annotations\Reader;
- use JMS\AopBundle\Aop\PointcutInterface;
- use JMS\DiExtraBundle\Annotation as DI;
-
- /**
- * @DI\Service
- * @DI\Tag("jms_aop.pointcut", attributes = {"interceptor" = "aop.transactional_interceptor"})
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
- class TransactionalPointcut implements PointcutInterface
- {
- private $reader;
-
- /**
- * @DI\InjectParams({
- * "reader" = @DI\Inject("annotation_reader"),
- * })
- * @param Reader $reader
- */
- public function __construct(Reader $reader)
- {
- $this->reader = $reader;
- }
-
- public function matchesClass(\ReflectionClass $class)
- {
- return true;
- }
-
- public function matchesMethod(\ReflectionMethod $method)
- {
- return null !== $this->reader->getMethodAnnotation($method, 'Annotation\Transactional');
- }
- }
-
-Interceptor
-^^^^^^^^^^^
-
-::
-
- use Symfony\Component\HttpKernel\Log\LoggerInterface;
- use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
- use CG\Proxy\MethodInvocation;
- use CG\Proxy\MethodInterceptorInterface;
- use Doctrine\ORM\EntityManager;
- use JMS\DiExtraBundle\Annotation as DI;
-
- /**
- * @DI\Service("aop.transactional_interceptor")
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
- class TransactionalInterceptor implements MethodInterceptorInterface
- {
- private $em;
- private $logger;
-
- /**
- * @DI\InjectParams
- * @param EntityManager $em
- */
- public function __construct(EntityManager $em, LoggerInterface $logger)
- {
- $this->em = $em;
- $this->logger = $logger;
- }
-
- public function intercept(MethodInvocation $invocation)
- {
- $this->logger->info('Beginning transaction for method "'.$invocation.'")');
- $this->em->getConnection()->beginTransaction();
- try {
- $rs = $invocation->proceed();
-
- $this->logger->info(sprintf('Comitting transaction for method "%s" (method invocation successful)', $invocation));
- $this->em->getConnection()->commit();
-
- return $rs;
- } catch (\Exception $ex) {
- if ($ex instanceof NotFoundHttpException) {
- $this->logger->info(sprintf('Committing transaction for method "%s" (exception thrown, but no rollback)', $invocation));
- $this->em->getConnection()->commit();
- } else {
- $this->logger->info(sprintf('Rolling back transaction for method "%s" (exception thrown)', $invocation));
- $this->em->getConnection()->rollBack();
- }
-
- throw $ex;
- }
- }
- }
+++ /dev/null
- Apache License\r
- Version 2.0, January 2004\r
- http://www.apache.org/licenses/\r
-\r
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\r
-\r
- 1. Definitions.\r
-\r
- "License" shall mean the terms and conditions for use, reproduction,\r
- and distribution as defined by Sections 1 through 9 of this document.\r
-\r
- "Licensor" shall mean the copyright owner or entity authorized by\r
- the copyright owner that is granting the License.\r
-\r
- "Legal Entity" shall mean the union of the acting entity and all\r
- other entities that control, are controlled by, or are under common\r
- control with that entity. For the purposes of this definition,\r
- "control" means (i) the power, direct or indirect, to cause the\r
- direction or management of such entity, whether by contract or\r
- otherwise, or (ii) ownership of fifty percent (50%) or more of the\r
- outstanding shares, or (iii) beneficial ownership of such entity.\r
-\r
- "You" (or "Your") shall mean an individual or Legal Entity\r
- exercising permissions granted by this License.\r
-\r
- "Source" form shall mean the preferred form for making modifications,\r
- including but not limited to software source code, documentation\r
- source, and configuration files.\r
-\r
- "Object" form shall mean any form resulting from mechanical\r
- transformation or translation of a Source form, including but\r
- not limited to compiled object code, generated documentation,\r
- and conversions to other media types.\r
-\r
- "Work" shall mean the work of authorship, whether in Source or\r
- Object form, made available under the License, as indicated by a\r
- copyright notice that is included in or attached to the work\r
- (an example is provided in the Appendix below).\r
-\r
- "Derivative Works" shall mean any work, whether in Source or Object\r
- form, that is based on (or derived from) the Work and for which the\r
- editorial revisions, annotations, elaborations, or other modifications\r
- represent, as a whole, an original work of authorship. For the purposes\r
- of this License, Derivative Works shall not include works that remain\r
- separable from, or merely link (or bind by name) to the interfaces of,\r
- the Work and Derivative Works thereof.\r
-\r
- "Contribution" shall mean any work of authorship, including\r
- the original version of the Work and any modifications or additions\r
- to that Work or Derivative Works thereof, that is intentionally\r
- submitted to Licensor for inclusion in the Work by the copyright owner\r
- or by an individual or Legal Entity authorized to submit on behalf of\r
- the copyright owner. For the purposes of this definition, "submitted"\r
- means any form of electronic, verbal, or written communication sent\r
- to the Licensor or its representatives, including but not limited to\r
- communication on electronic mailing lists, source code control systems,\r
- and issue tracking systems that are managed by, or on behalf of, the\r
- Licensor for the purpose of discussing and improving the Work, but\r
- excluding communication that is conspicuously marked or otherwise\r
- designated in writing by the copyright owner as "Not a Contribution."\r
-\r
- "Contributor" shall mean Licensor and any individual or Legal Entity\r
- on behalf of whom a Contribution has been received by Licensor and\r
- subsequently incorporated within the Work.\r
-\r
- 2. Grant of Copyright License. Subject to the terms and conditions of\r
- this License, each Contributor hereby grants to You a perpetual,\r
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable\r
- copyright license to reproduce, prepare Derivative Works of,\r
- publicly display, publicly perform, sublicense, and distribute the\r
- Work and such Derivative Works in Source or Object form.\r
-\r
- 3. Grant of Patent License. Subject to the terms and conditions of\r
- this License, each Contributor hereby grants to You a perpetual,\r
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable\r
- (except as stated in this section) patent license to make, have made,\r
- use, offer to sell, sell, import, and otherwise transfer the Work,\r
- where such license applies only to those patent claims licensable\r
- by such Contributor that are necessarily infringed by their\r
- Contribution(s) alone or by combination of their Contribution(s)\r
- with the Work to which such Contribution(s) was submitted. If You\r
- institute patent litigation against any entity (including a\r
- cross-claim or counterclaim in a lawsuit) alleging that the Work\r
- or a Contribution incorporated within the Work constitutes direct\r
- or contributory patent infringement, then any patent licenses\r
- granted to You under this License for that Work shall terminate\r
- as of the date such litigation is filed.\r
-\r
- 4. Redistribution. You may reproduce and distribute copies of the\r
- Work or Derivative Works thereof in any medium, with or without\r
- modifications, and in Source or Object form, provided that You\r
- meet the following conditions:\r
-\r
- (a) You must give any other recipients of the Work or\r
- Derivative Works a copy of this License; and\r
-\r
- (b) You must cause any modified files to carry prominent notices\r
- stating that You changed the files; and\r
-\r
- (c) You must retain, in the Source form of any Derivative Works\r
- that You distribute, all copyright, patent, trademark, and\r
- attribution notices from the Source form of the Work,\r
- excluding those notices that do not pertain to any part of\r
- the Derivative Works; and\r
-\r
- (d) If the Work includes a "NOTICE" text file as part of its\r
- distribution, then any Derivative Works that You distribute must\r
- include a readable copy of the attribution notices contained\r
- within such NOTICE file, excluding those notices that do not\r
- pertain to any part of the Derivative Works, in at least one\r
- of the following places: within a NOTICE text file distributed\r
- as part of the Derivative Works; within the Source form or\r
- documentation, if provided along with the Derivative Works; or,\r
- within a display generated by the Derivative Works, if and\r
- wherever such third-party notices normally appear. The contents\r
- of the NOTICE file are for informational purposes only and\r
- do not modify the License. You may add Your own attribution\r
- notices within Derivative Works that You distribute, alongside\r
- or as an addendum to the NOTICE text from the Work, provided\r
- that such additional attribution notices cannot be construed\r
- as modifying the License.\r
-\r
- You may add Your own copyright statement to Your modifications and\r
- may provide additional or different license terms and conditions\r
- for use, reproduction, or distribution of Your modifications, or\r
- for any such Derivative Works as a whole, provided Your use,\r
- reproduction, and distribution of the Work otherwise complies with\r
- the conditions stated in this License.\r
-\r
- 5. Submission of Contributions. Unless You explicitly state otherwise,\r
- any Contribution intentionally submitted for inclusion in the Work\r
- by You to the Licensor shall be under the terms and conditions of\r
- this License, without any additional terms or conditions.\r
- Notwithstanding the above, nothing herein shall supersede or modify\r
- the terms of any separate license agreement you may have executed\r
- with Licensor regarding such Contributions.\r
-\r
- 6. Trademarks. This License does not grant permission to use the trade\r
- names, trademarks, service marks, or product names of the Licensor,\r
- except as required for reasonable and customary use in describing the\r
- origin of the Work and reproducing the content of the NOTICE file.\r
-\r
- 7. Disclaimer of Warranty. Unless required by applicable law or\r
- agreed to in writing, Licensor provides the Work (and each\r
- Contributor provides its Contributions) on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\r
- implied, including, without limitation, any warranties or conditions\r
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\r
- PARTICULAR PURPOSE. You are solely responsible for determining the\r
- appropriateness of using or redistributing the Work and assume any\r
- risks associated with Your exercise of permissions under this License.\r
-\r
- 8. Limitation of Liability. In no event and under no legal theory,\r
- whether in tort (including negligence), contract, or otherwise,\r
- unless required by applicable law (such as deliberate and grossly\r
- negligent acts) or agreed to in writing, shall any Contributor be\r
- liable to You for damages, including any direct, indirect, special,\r
- incidental, or consequential damages of any character arising as a\r
- result of this License or out of the use or inability to use the\r
- Work (including but not limited to damages for loss of goodwill,\r
- work stoppage, computer failure or malfunction, or any and all\r
- other commercial damages or losses), even if such Contributor\r
- has been advised of the possibility of such damages.\r
-\r
- 9. Accepting Warranty or Additional Liability. While redistributing\r
- the Work or Derivative Works thereof, You may choose to offer,\r
- and charge a fee for, acceptance of support, warranty, indemnity,\r
- or other liability obligations and/or rights consistent with this\r
- License. However, in accepting such obligations, You may act only\r
- on Your own behalf and on Your sole responsibility, not on behalf\r
- of any other Contributor, and only if You agree to indemnify,\r
- defend, and hold each Contributor harmless for any liability\r
- incurred by, or claims asserted against, such Contributor by reason\r
- of your accepting any such warranty or additional liability.\r
-\r
- END OF TERMS AND CONDITIONS\r
-\r
- APPENDIX: How to apply the Apache License to your work.\r
-\r
- To apply the Apache License to your work, attach the following\r
- boilerplate notice, with the fields enclosed by brackets "[]"\r
- replaced with your own identifying information. (Don't include\r
- the brackets!) The text should be enclosed in the appropriate\r
- comment syntax for the file format. We also recommend that a\r
- file or class name and description of purpose be included on the\r
- same "printed page" as the copyright notice for easier\r
- identification within third-party archives.\r
-\r
- Copyright [yyyy] [name of copyright owner]\r
-\r
- Licensed under the Apache License, Version 2.0 (the "License");\r
- you may not use this file except in compliance with the License.\r
- You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Tests\Aop;
-
-use JMS\AopBundle\Aop\PointcutContainer;
-
-use JMS\AopBundle\Aop\InterceptorLoader;
-
-class InterceptorLoaderTest extends \PHPUnit_Framework_TestCase
-{
- public function testLoadInterceptors()
- {
- $interceptor = $this->getMock('CG\Proxy\MethodInterceptorInterface');
-
- list($loader, $container) = $this->getLoader(array(
- 'JMS\AopBundle\Tests\Aop\InterceptorLoaderTestClass' => array(
- 'foo' => array('foo'),
- ),
- ));
-
- $container
- ->expects($this->once())
- ->method('get')
- ->with($this->equalTo('foo'))
- ->will($this->returnValue($interceptor))
- ;
-
- $method = new \ReflectionMethod('JMS\AopBundle\Tests\Aop\InterceptorLoaderTestClass', 'foo');
-
- $this->assertSame(array($interceptor), $loader->loadInterceptors($method));
- // yes, twice
- $this->assertSame(array($interceptor), $loader->loadInterceptors($method));
- }
-
- private function getLoader(array $interceptors = array())
- {
- $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
-
- return array(new InterceptorLoader($container, $interceptors), $container);
- }
-}
-
-class InterceptorLoaderTestClass
-{
- public function foo()
- {
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Tests\Aop;
-
-use JMS\AopBundle\Aop\RegexPointcut;
-
-class RegexPointcutTest extends \PHPUnit_Framework_TestCase
-{
- public function testMatchesClass()
- {
- $pointcut = new RegexPointcut('');
- $this->assertTrue($pointcut->matchesClass(new \ReflectionClass('stdClass')));
- }
-
- public function testMatchesMethod()
- {
- $pointcut = new RegexPointcut('foo$');
-
- $method = new \ReflectionMethod('JMS\AopBundle\Tests\Aop\RegexPointcutTestClass', 'foo');
- $this->assertTrue($pointcut->matchesMethod($method));
-
- $method = new \ReflectionMethod('JMS\AopBundle\Tests\Aop\RegexPointcutTestClass', 'bar');
- $this->assertFalse($pointcut->matchesMethod($method));
- }
-}
-
-class RegexPointcutTestClass
-{
- public function foo() {}
- public function bar() {}
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture;
-
-use CG\Proxy\MethodInvocation;
-use CG\Proxy\MethodInterceptorInterface;
-
-class LoggingInterceptor implements MethodInterceptorInterface
-{
- private $log = array();
-
- public function getLog()
- {
- return $this->log;
- }
-
- public function intercept(MethodInvocation $invocation)
- {
- $this->log[] = $invocation->reflection->name;
-
- return $invocation->proceed();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture;
-
-use JMS\AopBundle\Aop\PointcutInterface;
-
-class LoggingPointcut implements PointcutInterface
-{
- public function matchesClass(\ReflectionClass $class)
- {
- return true;
- }
-
- public function matchesMethod(\ReflectionMethod $method)
- {
- return false !== strpos($method->name, 'delete');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture;
-
-class TestService
-{
- public function add()
- {
- return true;
- }
-
- public function delete()
- {
- return true;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\AopBundle\Tests\DependencyInjection\Compiler;
-
-use JMS\AopBundle\Exception\RuntimeException;
-use Symfony\Component\DependencyInjection\Compiler\ResolveParameterPlaceHoldersPass;
-use JMS\AopBundle\DependencyInjection\JMSAopExtension;
-use JMS\AopBundle\DependencyInjection\Compiler\PointcutMatchingPass;
-use Symfony\Component\HttpKernel\Util\Filesystem;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-
-class PointcutMatchingPassTest extends \PHPUnit_Framework_TestCase
-{
- private $cacheDir;
- private $fs;
-
- public function testProcess()
- {
- $container = $this->getContainer();
-
- $container
- ->register('pointcut', 'JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture\LoggingPointcut')
- ->addTag('jms_aop.pointcut', array('interceptor' => 'interceptor'))
- ;
- $container
- ->register('interceptor', 'JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture\LoggingInterceptor')
- ;
- $container
- ->register('test', 'JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture\TestService')
- ;
-
- $this->process($container);
-
- $service = $container->get('test');
- $this->assertInstanceOf('JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture\TestService', $service);
- $this->assertTrue($service->add());
- $this->assertTrue($service->delete());
- $this->assertEquals(array('delete'), $container->get('interceptor')->getLog());
- }
-
- protected function setUp()
- {
- $this->cacheDir = sys_get_temp_dir().'/jms_aop_test';
- $this->fs = new Filesystem();
-
- if (is_dir($this->cacheDir)) {
- $this->fs->remove($this->cacheDir);
- }
-
- if (false === @mkdir($this->cacheDir, 0777, true)) {
- throw new RuntimeException(sprintf('Could not create cache dir "%s".', $this->cacheDir));
- }
- }
-
- protected function tearDown()
- {
- $this->fs->remove($this->cacheDir);
- }
-
- private function getContainer()
- {
- $container = new ContainerBuilder();
-
- $extension = new JMSAopExtension();
- $extension->load(array(array(
- 'cache_dir' => $this->cacheDir,
- )), $container);
-
- return $container;
- }
-
- private function process(ContainerBuilder $container)
- {
- $pass = new ResolveParameterPlaceHoldersPass();
- $pass->process($container);
-
- $pass = new PointcutMatchingPass();
- $pass->process($container);
- }
-}
\ No newline at end of file
+++ /dev/null
-{
- "name": "jms/aop-bundle",
- "description": "Adds AOP capabilities to Symfony2",
- "keywords": ["annotations","aop"],
- "type": "symfony-bundle",
- "license": "Apache",
- "authors": [
- {
- "name": "Johannes M. Schmitt",
- "email": "schmittjoh@gmail.com"
- }
- ],
- "require": {
- "symfony/framework-bundle": "2.*",
- "jms/cg": "1.0.0"
- },
- "autoload": {
- "psr-0": { "JMS\\AopBundle": "" }
- },
- "target-dir": "JMS/AopBundle"
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-\r
-<phpunit backupGlobals="false"\r
- backupStaticAttributes="false"\r
- colors="true"\r
- convertErrorsToExceptions="true"\r
- convertNoticesToExceptions="true"\r
- convertWarningsToExceptions="true"\r
- processIsolation="false"\r
- stopOnFailure="false"\r
- syntaxCheck="false"\r
- bootstrap="./../../../../app/bootstrap.php.cache"\r
->\r
- \r
- <testsuites>\r
- <testsuite name="AopBundle Test Suite">\r
- <directory>./Tests</directory>\r
- </testsuite>\r
- </testsuites>\r
- \r
- <groups>\r
- <exclude>\r
- <group>performance</group>\r
- </exclude>\r
- </groups>\r
-</phpunit>\r
+++ /dev/null
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
\ No newline at end of file
+++ /dev/null
-CG library provides a toolset for generating PHP code
-=====================================================
-
-Overview
---------
-
-This library provides some tools that you commonly need for generating PHP code.
-One of it's strength lies in the enhancement of existing classes with behaviors.
-
+++ /dev/null
-{
- "name": "jms/cg",
- "description": "Toolset for generating PHP code",
- "keywords": ["code generation"],
- "type": "library",
- "license": "Apache",
- "authors": [
- {
- "name": "Johannes M. Schmitt",
- "email": "schmittjoh@gmail.com"
- }
- ],
- "require": {
- "php": ">=5.3.0"
- },
- "autoload": {
- "psr-0": { "CG\\": "src/" }
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-
-<phpunit backupGlobals="false"
- backupStaticAttributes="false"
- colors="true"
- convertErrorsToExceptions="true"
- convertNoticesToExceptions="true"
- convertWarningsToExceptions="true"
- processIsolation="false"
- stopOnFailure="false"
- syntaxCheck="false"
- bootstrap="tests/bootstrap.php"
->
- <testsuites>
- <testsuite name="CG Test Suite">
- <directory>./tests/CG/</directory>
- </testsuite>
- </testsuites>
-
- <groups>
- <exclude>
- <group>performance</group>
- </exclude>
- </groups>
-</phpunit>
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Core;
-
-use CG\Generator\PhpClass;
-
-/**
- * Abstract base class for all class generators.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-abstract class AbstractClassGenerator implements ClassGeneratorInterface
-{
- private $namingStrategy;
- private $generatorStrategy;
-
- public function setNamingStrategy(NamingStrategyInterface $namingStrategy = null)
- {
- $this->namingStrategy = $namingStrategy;
- }
-
- public function setGeneratorStrategy(GeneratorStrategyInterface $generatorStrategy = null)
- {
- $this->generatorStrategy = $generatorStrategy;
- }
-
- public function getClassName(\ReflectionClass $class)
- {
- if (null === $this->namingStrategy) {
- $this->namingStrategy = new DefaultNamingStrategy();
- }
-
- return $this->namingStrategy->getClassName($class);
- }
-
- protected function generateCode(PhpClass $class)
- {
- if (null === $this->generatorStrategy) {
- $this->generatorStrategy = new DefaultGeneratorStrategy();
- }
-
- return $this->generatorStrategy->generate($class);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Core;
-
-use CG\Generator\PhpClass;
-
-/**
- * Interface for class generators.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface ClassGeneratorInterface
-{
- /**
- * Generates the PHP class.
- *
- * @return string
- */
- function generateClass();
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Core;
-
-use CG\Proxy\Enhancer;
-
-abstract class ClassUtils
-{
- public static function getUserClass($className)
- {
- if (false === $pos = strrpos($className, '\\'.NamingStrategyInterface::SEPARATOR.'\\')) {\r
- return $className;\r
- }\r
-\r
- return substr($className, $pos + NamingStrategyInterface::SEPARATOR_LENGTH + 2);
- }
-
- private final function __construct() {}
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Core;
-
-use CG\Generator\DefaultVisitorInterface;
-use CG\Generator\PhpClass;
-use CG\Generator\DefaultVisitor;
-use CG\Generator\DefaultNavigator;
-
-/**
- * The default generator strategy.
- *
- * This strategy allows to change the order in which methods, properties and
- * constants are sorted.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class DefaultGeneratorStrategy implements GeneratorStrategyInterface
-{
- private $navigator;
- private $visitor;
-
- public function __construct(DefaultVisitorInterface $visitor = null)
- {
- $this->navigator = new DefaultNavigator();
- $this->visitor = $visitor ?: new DefaultVisitor();
- }
-
- public function setConstantSortFunc(\Closure $func = null)
- {
- $this->navigator->setConstantSortFunc($func);
- }
-
- public function setMethodSortFunc(\Closure $func = null)
- {
- $this->navigator->setMethodSortFunc($func);
- }
-
- public function setPropertySortFunc(\Closure $func = null)
- {
- $this->navigator->setPropertySortFunc($func);
- }
-
- public function generate(PhpClass $class)
- {
- $this->visitor->reset();
- $this->navigator->accept($this->visitor, $class);
-
- return $this->visitor->getContent();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Core;
-
-/**
- * The default naming strategy.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class DefaultNamingStrategy implements NamingStrategyInterface
-{
- private $prefix;
-
- public function __construct($prefix = 'EnhancedProxy')
- {
- $this->prefix = $prefix;
- }
-
- public function getClassName(\ReflectionClass $class)
- {
- $userClass = ClassUtils::getUserClass($class->name);
-
- return $this->prefix.'_'.sha1($class->name).'\\'.self::SEPARATOR.'\\'.$userClass;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Core;
-
-use CG\Generator\PhpClass;
-
-/**
- * Generator Strategy Interface.
- *
- * Implementing classes are responsible for generating PHP code from the given
- * PhpClass instance.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface GeneratorStrategyInterface
-{
- function generate(PhpClass $class);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Core;
-
-/**
- * The naming strategy interface.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface NamingStrategyInterface
-{
- const SEPARATOR = '__CG__';
- const SEPARATOR_LENGTH = 6;
-
- /**
- * Returns the class name for the proxy class.
- *
- * The generated class name MUST be the concatenation of a nonempty prefix,
- * the namespace separator __CG__, and the original class name.
- *
- * Examples:
- *
- * +----------------------------+------------------------------+
- * | Original Name | Generated Name |
- * +============================+==============================+
- * | Foo\Bar | dred332\__CG__\Foo\Bar |
- * | Bar\Baz | Foo\Doo\__CG__\Bar\Baz |
- * +----------------------------+------------------------------+
- *
- * @param \ReflectionClass $class
- * @return string the class name for the generated class
- */
- function getClassName(\ReflectionClass $class);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Core;
-
-abstract class ReflectionUtils
-{
- public static function getOverrideableMethods(\ReflectionClass $class, $publicOnly = false)
- {
- $filter = \ReflectionMethod::IS_PUBLIC;
-
- if (!$publicOnly) {
- $filter |= \ReflectionMethod::IS_PROTECTED;
- }
-
- return array_filter(
- $class->getMethods($filter),
- function($method) { return !$method->isFinal() && !$method->isStatic(); }
- );
- }
-
- public static function getUnindentedDocComment($docComment)
- {
- $lines = explode("\n", $docComment);
- for ($i=0,$c=count($lines); $i<$c; $i++) {
- if (0 === $i) {
- $docBlock = $lines[0]."\n";
- continue;
- }
-
- $docBlock .= ' '.ltrim($lines[$i]);
-
- if ($i+1 < $c) {
- $docBlock .= "\n";
- }
- }
-
- return $docBlock;
- }
-
- private final function __construct() { }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Generator;
-
-/**
- * Abstract PHP member class.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-abstract class AbstractPhpMember
-{
- const VISIBILITY_PRIVATE = 'private';
- const VISIBILITY_PROTECTED = 'protected';
- const VISIBILITY_PUBLIC = 'public';
-
- private $static = false;
- private $visibility = self::VISIBILITY_PUBLIC;
- private $name;
- private $docblock;
-
- public function __construct($name = null)
- {
- $this->setName($name);
- }
-
- public function setName($name)
- {
- $this->name = $name;
-
- return $this;
- }
-
- public function setVisibility($visibility)
- {
- if ($visibility !== self::VISIBILITY_PRIVATE
- && $visibility !== self::VISIBILITY_PROTECTED
- && $visibility !== self::VISIBILITY_PUBLIC) {
- throw new \InvalidArgumentException(sprintf('The visibility "%s" does not exist.', $visibility));
- }
-
- $this->visibility = $visibility;
-
- return $this;
- }
-
- public function setStatic($bool)
- {
- $this->static = (Boolean) $bool;
-
- return $this;
- }
-
- public function setDocblock($doc)
- {
- $this->docblock = $doc;
-
- return $this;
- }
-
- public function isStatic()
- {
- return $this->static;
- }
-
- public function getVisibility()
- {
- return $this->visibility;
- }
-
- public function getName()
- {
- return $this->name;
- }
-
- public function getDocblock()
- {
- return $this->docblock;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Generator;
-
-/**
- * The default navigator.
- *
- * This class is responsible for the default traversal algorithm of the different
- * code elements.
- *
- * Unlike other visitor pattern implementations, this allows to separate the
- * traversal logic from the objects that are traversed.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class DefaultNavigator
-{
- private $constantSortFunc;
- private $propertySortFunc;
- private $methodSortFunc;
-
- /**
- * Sets a custom constant sorting function.
- *
- * @param \Closure $func
- */
- public function setConstantSortFunc(\Closure $func = null)
- {
- $this->constantSortFunc = $func;
- }
-
- /**
- * Sets a custom property sorting function.
- *
- * @param \Closure $func
- */
- public function setPropertySortFunc(\Closure $func = null)
- {
- $this->propertySortFunc = $func;
- }
-
- /**
- * Sets a custom method sorting function.
- *
- * @param \Closure $func
- */
- public function setMethodSortFunc(\Closure $func = null)
- {
- $this->methodSortFunc = $func;
- }
-
- public function accept(DefaultVisitorInterface $visitor, PhpClass $class)
- {
- $visitor->startVisitingClass($class);
-
- $constants = $class->getConstants();
- if (!empty($constants)) {
- uksort($constants, $this->getConstantSortFunc());
-
- $visitor->startVisitingConstants();
- foreach ($constants as $name => $value) {
- $visitor->visitConstant($name, $value);
- }
- $visitor->endVisitingConstants();
- }
-
- $properties = $class->getProperties();
- if (!empty($properties)) {
- usort($properties, $this->getPropertySortFunc());
-
- $visitor->startVisitingProperties();
- foreach ($properties as $property) {
- $visitor->visitProperty($property);
- }
- $visitor->endVisitingProperties();
- }
-
- $methods = $class->getMethods();
- if (!empty($methods)) {
- usort($methods, $this->getMethodSortFunc());
-
- $visitor->startVisitingMethods();
- foreach ($methods as $method) {
- $visitor->visitMethod($method);
- }
- $visitor->endVisitingMethods();
- }
-
- $visitor->endVisitingClass($class);
- }
-
- private function getConstantSortFunc()
- {
- return $this->constantSortFunc ?: 'strcasecmp';
- }
-
- private function getMethodSortFunc()
- {
- if (null !== $this->methodSortFunc) {
- return $this->methodSortFunc;
- }
-
- static $defaultSortFunc;
- if (empty($defaultSortFunc)) {
- $defaultSortFunc = function($a, $b) {
- if ($a->isStatic() !== $isStatic = $b->isStatic()) {
- return $isStatic ? 1 : -1;
- }
-
- if (($aV = $a->getVisibility()) !== $bV = $b->getVisibility()) {
- $aV = 'public' === $aV ? 3 : ('protected' === $aV ? 2 : 1);
- $bV = 'public' === $bV ? 3 : ('protected' === $bV ? 2 : 1);
-
- return $aV > $bV ? -1 : 1;
- }
-
- $rs = strcasecmp($a->getName(), $b->getName());
- if (0 === $rs) {
- return 0;
- }
-
- return $rs > 0 ? -1 : 1;
- };
- }
-
- return $defaultSortFunc;
- }
-
- private function getPropertySortFunc()
- {
- if (null !== $this->propertySortFunc) {
- return $this->propertySortFunc;
- }
-
- static $defaultSortFunc;
- if (empty($defaultSortFunc)) {
- $defaultSortFunc = function($a, $b) {
- if (($aV = $a->getVisibility()) !== $bV = $b->getVisibility()) {
- $aV = 'public' === $aV ? 3 : ('protected' === $aV ? 2 : 1);
- $bV = 'public' === $bV ? 3 : ('protected' === $bV ? 2 : 1);
-
- return $aV > $bV ? -1 : 1;
- }
-
- $rs = strcasecmp($a->getName(), $b->getName());
- if (0 === $rs) {
- return 0;
- }
-
- return $rs > 0 ? -1 : 1;
- };
- }
-
- return $defaultSortFunc;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Generator;
-
-/**
- * The default code generation visitor.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class DefaultVisitor implements DefaultVisitorInterface
-{
- private $writer;
-
- public function __construct()
- {
- $this->writer = new Writer();
- }
-
- public function reset()
- {
- $this->writer->reset();
- }
-
- public function startVisitingClass(PhpClass $class)
- {
- if ($namespace = $class->getNamespace()) {
- $this->writer->write('namespace '.$namespace.';'."\n\n");
- }
-
- if ($files = $class->getRequiredFiles()) {
- foreach ($files as $file) {
- $this->writer->writeln('require_once '.var_export($file, true).';');
- }
-
- $this->writer->write("\n");
- }
-
- if ($useStatements = $class->getUseStatements()) {
- foreach ($useStatements as $alias => $namespace) {
- $this->writer->write('use '.$namespace);
-
- if (substr($namespace, strrpos($namespace, '\\') + 1) !== $alias) {
- $this->writer->write(' as '.$alias);
- }
-
- $this->writer->write(";\n");
- }
-
- $this->writer->write("\n");
- }
-
- if ($docblock = $class->getDocblock()) {
- $this->writer->write($docblock);
- }
-
- $this->writer->write('class '.$class->getShortName());
-
- if ($parentClassName = $class->getParentClassName()) {
- $this->writer->write(' extends '.('\\' === $parentClassName[0] ? $parentClassName : '\\'.$parentClassName));
- }
-
- $interfaceNames = $class->getInterfaceNames();
- if (!empty($interfaceNames)) {
- $interfaceNames = array_unique($interfaceNames);
-
- $interfaceNames = array_map(function($name) {
- if ('\\' === $name[0]) {
- return $name;
- }
-
- return '\\'.$name;
- }, $interfaceNames);
-
- $this->writer->write(' implements '.implode(', ', $interfaceNames));
- }
-
- $this->writer
- ->write("\n{\n")
- ->indent()
- ;
- }
-
- public function startVisitingConstants()
- {
- }
-
- public function visitConstant($name, $value)
- {
- $this->writer->writeln('const '.$name.' = '.var_export($value, true).';');
- }
-
- public function endVisitingConstants()
- {
- $this->writer->write("\n");
- }
-
- public function startVisitingProperties()
- {
- }
-
- public function visitProperty(PhpProperty $property)
- {
- $this->writer->write($property->getVisibility().' '.($property->isStatic()? 'static ' : '').'$'.$property->getName());
-
- if ($property->hasDefaultValue()) {
- $this->writer->write(' = '.var_export($property->getDefaultValue(), true));
- }
-
- $this->writer->writeln(';');
- }
-
- public function endVisitingProperties()
- {
- $this->writer->write("\n");
- }
-
- public function startVisitingMethods()
- {
- }
-
- public function visitMethod(PhpMethod $method)
- {
- if ($docblock = $method->getDocblock()) {
- $this->writer->writeln($docblock)->rtrim();
- }
-
- if ($method->isAbstract()) {
- $this->writer->write('abstract ');
- }
-
- $this->writer->write($method->getVisibility().' ');
-
- if ($method->isStatic()) {
- $this->writer->write('static ');
- }
-
- $this->writer->write('function '.$method->getName().'(');
-
- $this->writeParameters($method->getParameters());
-
- if ($method->isAbstract()) {
- $this->writer->write(");\n\n");
-
- return;
- }
-
- $this->writer
- ->writeln(")")
- ->writeln('{')
- ->indent()
- ->writeln($method->getBody())
- ->outdent()
- ->rtrim()
- ->write("}\n\n")
- ;
- }
-
- public function endVisitingMethods()
- {
- }
-
- public function endVisitingClass(PhpClass $class)
- {
- $this->writer
- ->outdent()
- ->rtrim()
- ->write('}')
- ;
- }
-
- public function visitFunction(PhpFunction $function)
- {
- if ($namespace = $function->getNamespace()) {
- $this->writer->write("namespace $namespace;\n\n");
- }
-
- $this->writer->write("function {$function->getName()}(");
- $this->writeParameters($function->getParameters());
- $this->writer
- ->write(")\n{\n")
- ->indent()
- ->writeln($function->getBody())
- ->outdent()
- ->rtrim()
- ->write('}')
- ;
- }
-
- public function getContent()
- {
- return $this->writer->getContent();
- }
-
- private function writeParameters(array $parameters)
- {
- $first = true;
- foreach ($parameters as $parameter) {
- if (!$first) {
- $this->writer->write(', ');
- }
- $first = false;
-
- if ($type = $parameter->getType()) {
- $this->writer->write(
- ('array' === $type ? 'array' : ('\\' === $type[0] ? $type : '\\'. $type))
- .' '
- );
- }
-
- if ($parameter->isPassedByReference()) {
- $this->writer->write('&');
- }
-
- $this->writer->write('$'.$parameter->getName());
-
- if ($parameter->hasDefaultValue()) {
- $this->writer->write(' = '.var_export($parameter->getDefaultValue(), true));
- }
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Generator;
-
-/**
- * The visitor interface required by the DefaultNavigator.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface DefaultVisitorInterface
-{
- /**
- * Resets the visitors internal state to allow re-using the same instance.
- *
- * @return void
- */
- function reset();
-
- function startVisitingClass(PhpClass $class);
- function startVisitingConstants();
- function visitConstant($name, $value);
- function endVisitingConstants();
- function startVisitingProperties();
- function visitProperty(PhpProperty $property);
- function endVisitingProperties();
- function startVisitingMethods();
- function visitMethod(PhpMethod $method);
- function endVisitingMethods();
- function endVisitingClass(PhpClass $class);
- function visitFunction(PhpFunction $function);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Generator;
-
-/**
- * Some Generator utils.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-abstract class GeneratorUtils
-{
- private final function __construct() {}
-
- public static function callMethod(\ReflectionMethod $method, array $params = null)
- {
- if (null === $params) {
- $params = array_map(function($p) { return '$'.$p->name; }, $method->getParameters());
- }
-
- return '\\'.$method->getDeclaringClass()->name.'::'.$method->name.'('.implode(', ', $params).')';
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Generator;
-
-use Doctrine\Common\Annotations\PhpParser;
-
-use CG\Core\ReflectionUtils;
-
-/**
- * Represents a PHP class.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class PhpClass
-{
- private static $phpParser;
-
- private $name;
- private $parentClassName;
- private $interfaceNames = array();
- private $useStatements = array();
- private $constants = array();
- private $properties = array();
- private $requiredFiles = array();
- private $methods = array();
- private $abstract = false;
- private $final = false;
- private $docblock;
-
- public static function create($name = null)
- {
- return new self($name);
- }
-
- public static function fromReflection(\ReflectionClass $ref)
- {
- $class = new static();
- $class
- ->setName($ref->name)
- ->setAbstract($ref->isAbstract())
- ->setFinal($ref->isFinal())
- ->setConstants($ref->getConstants())
- ;
-
- if (null === self::$phpParser) {
- if (!class_exists('Doctrine\Common\Annotations\PhpParser')) {
- self::$phpParser = false;
- } else {
- self::$phpParser = new PhpParser();
- }
- }
-
- if (false !== self::$phpParser) {
- $class->setUseStatements(self::$phpParser->parseClass($ref));
- }
-
- if ($docComment = $ref->getDocComment()) {
- $class->setDocblock(ReflectionUtils::getUnindentedDocComment($docComment));
- }
-
- foreach ($ref->getMethods() as $method) {
- $class->setMethod(static::createMethod($method));
- }
-
- foreach ($ref->getProperties() as $property) {
- $class->setProperty(static::createProperty($property));
- }
-
- return $class;
- }
-
- protected static function createMethod(\ReflectionMethod $method)
- {
- return PhpMethod::fromReflection($method);
- }
-
- protected static function createProperty(\ReflectionProperty $property)
- {
- return PhpProperty::fromReflection($property);
- }
-
- public function __construct($name = null)
- {
- $this->name = $name;
- }
-
- public function setName($name)
- {
- $this->name = $name;
-
- return $this;
- }
-
- public function setParentClassName($name)
- {
- $this->parentClassName = $name;
-
- return $this;
- }
-
- public function setInterfaceNames(array $names)
- {
- $this->interfaceNames = $names;
-
- return $this;
- }
-
- public function addInterfaceName($name)
- {
- $this->interfaceNames[] = $name;
-
- return $this;
- }
-
- public function setRequiredFiles(array $files)
- {
- $this->requiredFiles = $files;
-
- return $this;
- }
-
- public function addRequiredFile($file)
- {
- $this->requiredFiles[] = $file;
-
- return $this;
- }
-
- public function setUseStatements(array $useStatements)
- {
- $this->useStatements = $useStatements;
-
- return $this;
- }
-
- public function addUseStatement($namespace, $alias = null)
- {
- if (null === $alias) {
- $alias = substr($namespace, strrpos($namespace, '\\') + 1);
- }
-
- $this->useStatements[$alias] = $namespace;
-
- return $this;
- }
-
- public function setConstants(array $constants)
- {
- $this->constants = $constants;
-
- return $this;
- }
-
- public function setConstant($name, $value)
- {
- $this->constants[$name] = $value;
-
- return $this;
- }
-
- public function hasConstant($name)
- {
- return array_key_exists($this->constants, $name);
- }
-
- public function removeConstant($name)
- {
- if (!array_key_exists($name, $this->constants)) {
- throw new \InvalidArgumentException(sprintf('The constant "%s" does not exist.', $name));
- }
-
- unset($this->constants[$name]);
-
- return $this;
- }
-
- public function setProperties(array $properties)
- {
- $this->properties = $properties;
-
- return $this;
- }
-
- public function setProperty(PhpProperty $property)
- {
- $this->properties[$property->getName()] = $property;
-
- return $this;
- }
-
- public function hasProperty($property)
- {
- if ($property instanceof PhpProperty) {
- $property = $property->getName();
- }
-
- return isset($this->properties[$property]);
- }
-
- public function removeProperty($property)
- {
- if ($property instanceof PhpProperty) {
- $property = $property->getName();
- }
-
- if (!array_key_exists($property, $this->properties)) {
- throw new \InvalidArgumentException(sprintf('The property "%s" does not exist.', $property));
- }
- unset($this->properties[$property]);
-
- return $this;
- }
-
- public function setMethods(array $methods)
- {
- $this->methods = $methods;
-
- return $this;
- }
-
- public function setMethod(PhpMethod $method)
- {
- $this->methods[$method->getName()] = $method;
-
- return $this;
- }
-
- public function hasMethod($method)
- {
- if ($method instanceof PhpMethod) {
- $method = $method->getName();
- }
-
- return isset($this->methods[$method]);
- }
-
- public function removeMethod($method)
- {
- if ($method instanceof PhpMethod) {
- $method = $method->getName();
- }
-
- if (!array_key_exists($method, $this->methods)) {
- throw new \InvalidArgumentException(sprintf('The method "%s" does not exist.', $method));
- }
- unset($this->methods[$method]);
-
- return $this;
- }
-
- public function setAbstract($bool)
- {
- $this->abstract = (Boolean) $bool;
-
- return $this;
- }
-
- public function setFinal($bool)
- {
- $this->final = (Boolean) $bool;
-
- return $this;
- }
-
- public function setDocblock($block)
- {
- $this->docblock = $block;
-
- return $this;
- }
-
- public function getName()
- {
- return $this->name;
- }
-
- public function getParentClassName()
- {
- return $this->parentClassName;
- }
-
- public function getInterfaceNames()
- {
- return $this->interfaceNames;
- }
-
- public function getRequiredFiles()
- {
- return $this->requiredFiles;
- }
-
- public function getUseStatements()
- {
- return $this->useStatements;
- }
-
- public function getNamespace()
- {
- if (false === $pos = strrpos($this->name, '\\')) {
- return null;
- }
-
- return substr($this->name, 0, $pos);
- }
-
- public function getShortName()
- {
- if (false === $pos = strrpos($this->name, '\\')) {
- return $this->name;
- }
-
- return substr($this->name, $pos+1);
- }
-
- public function getConstants()
- {
- return $this->constants;
- }
-
- public function getProperties()
- {
- return $this->properties;
- }
-
- public function getMethods()
- {
- return $this->methods;
- }
-
- public function isAbstract()
- {
- return $this->abstract;
- }
-
- public function isFinal()
- {
- return $this->final;
- }
-
- public function getDocblock()
- {
- return $this->docblock;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Generator;
-
-/**
- * Represents a PHP function.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class PhpFunction
-{
- private $name;
- private $namespace;
- private $parameters = array();
- private $body = '';
- private $referenceReturned = false;
- private $docblock;
-
- public static function create($name = null)
- {
- return new static($name);
- }
-
- public function __construct($name = null)
- {
- $this->name = $name;
- }
-
- public function setName($name)
- {
- $this->name = $name;
-
- return $this;
- }
-
- public function setNamespace($namespace)
- {
- $this->namespace = $namespace;
-
- return $this;
- }
-
- public function setParameters(array $parameters)
- {
- $this->parameters = $parameters;
-
- return $this;
- }
-
- public function setReferenceReturned($bool)
- {
- $this->referenceReturned = (Boolean) $bool;
-
- return $this;
- }
-
- public function replaceParameter($position, PhpParameter $parameter)
- {
- if ($position < 0 || $position > count($this->parameters)) {
- throw new \InvalidArgumentException(sprintf('$position must be in the range [0, %d].', count($this->parameters)));
- }
-
- $this->parameters[$position] = $parameter;
-
- return $this;
- }
-
- public function addParameter(PhpParameter $parameter)
- {
- $this->parameters[] = $parameter;
-
- return $this;
- }
-
- public function removeParameter($position)
- {
- if (!isset($this->parameters[$position])) {
- throw new \InvalidArgumentException(sprintf('There is not parameter at position %d.', $position));
- }
-
- unset($this->parameters[$position]);
- $this->parameters = array_values($this->parameters);
-
- return $this;
- }
-
- public function setBody($body)
- {
- $this->body = $body;
-
- return $this;
- }
-
- public function setDocblock($docBlock)
- {
- $this->docblock = $docBlock;
-
- return $this;
- }
-
- public function getName()
- {
- return $this->name;
- }
-
- public function getNamespace()
- {
- return $this->namespace;
- }
-
- public function getParameters()
- {
- return $this->parameters;
- }
-
- public function getBody()
- {
- return $this->body;
- }
-
- public function getDocblock()
- {
- return $this->docblock;
- }
-
- public function isReferenceReturned()
- {
- return $this->referenceReturned;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Generator;
-
-use CG\Core\ReflectionUtils;
-
-/**
- * Represents a PHP method.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class PhpMethod extends AbstractPhpMember
-{
- private $final = false;
- private $abstract = false;
- private $parameters = array();
- private $referenceReturned = false;
- private $body = '';
-
- public static function create($name = null)
- {
- return new static($name);
- }
-
- public static function fromReflection(\ReflectionMethod $ref)
- {
- $method = new static();
- $method
- ->setFinal($ref->isFinal())
- ->setAbstract($ref->isAbstract())
- ->setStatic($ref->isStatic())
- ->setVisibility($ref->isPublic() ? self::VISIBILITY_PUBLIC : ($ref->isProtected() ? self::VISIBILITY_PROTECTED : self::VISIBILITY_PRIVATE))
- ->setReferenceReturned($ref->returnsReference())
- ->setName($ref->name)
- ;
-
- if ($docComment = $ref->getDocComment()) {
- $method->setDocblock(ReflectionUtils::getUnindentedDocComment($docComment));
- }
-
- foreach ($ref->getParameters() as $param) {
- $method->addParameter(static::createParameter($param));
- }
-
- // FIXME: Extract body?
-
- return $method;
- }
-
- protected static function createParameter(\ReflectionParameter $parameter)
- {
- return PhpParameter::fromReflection($parameter);
- }
-
- public function setFinal($bool)
- {
- $this->final = (Boolean) $bool;
-
- return $this;
- }
-
- public function setAbstract($bool)
- {
- $this->abstract = $bool;
-
- return $this;
- }
-
- public function setReferenceReturned($bool)
- {
- $this->referenceReturned = (Boolean) $bool;
-
- return $this;
- }
-
- public function setBody($body)
- {
- $this->body = $body;
-
- return $this;
- }
-
- public function setParameters(array $parameters)
- {
- $this->parameters = array_values($parameters);
-
- return $this;
- }
-
- public function addParameter(PhpParameter $parameter)
- {
- $this->parameters[] = $parameter;
-
- return $this;
- }
-
- public function replaceParameter($position, PhpParameter $parameter)
- {
- if ($position < 0 || $position > strlen($this->parameters)) {
- throw new \InvalidArgumentException(sprintf('The position must be in the range [0, %d].', strlen($this->parameters)));
- }
- $this->parameters[$position] = $parameter;
-
- return $this;
- }
-
- public function removeParameter($position)
- {
- if (!isset($this->parameters[$position])) {
- throw new \InvalidArgumentException(sprintf('There is no parameter at position "%d" does not exist.', $position));
- }
- unset($this->parameters[$position]);
- $this->parameters = array_values($this->parameters);
-
- return $this;
- }
-
- public function isFinal()
- {
- return $this->final;
- }
-
- public function isAbstract()
- {
- return $this->abstract;
- }
-
- public function isReferenceReturned()
- {
- return $this->referenceReturned;
- }
-
- public function getBody()
- {
- return $this->body;
- }
-
- public function getParameters()
- {
- return $this->parameters;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Generator;
-
-/**
- * Represents a PHP parameter.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class PhpParameter
-{
- private $name;
- private $defaultValue;
- private $hasDefaultValue = false;
- private $passedByReference = false;
- private $type;
-
- public static function create($name = null)
- {
- return new static($name);
- }
-
- public static function fromReflection(\ReflectionParameter $ref)
- {
- $parameter = new static();
- $parameter
- ->setName($ref->name)
- ->setPassedByReference($ref->isPassedByReference())
- ;
-
- if ($ref->isDefaultValueAvailable()) {
- $parameter->setDefaultValue($ref->getDefaultValue());
- }
-
- if ($ref->isArray()) {
- $parameter->setType('array');
- } else if ($class = $ref->getClass()) {
- $parameter->setType($class->name);
- }
-
- return $parameter;
- }
-
- public function __construct($name = null)
- {
- $this->name = $name;
- }
-
- public function setName($name)
- {
- $this->name = $name;
-
- return $this;
- }
-
- public function setDefaultValue($value)
- {
- $this->defaultValue = $value;
- $this->hasDefaultValue = true;
-
- return $this;
- }
-
- public function unsetDefaultValue()
- {
- $this->defaultValue = null;
- $this->hasDefaultValue = false;
-
- return $this;
- }
-
- public function setPassedByReference($bool)
- {
- $this->passedByReference = (Boolean) $bool;
-
- return $this;
- }
-
- public function setType($type)
- {
- $this->type = $type;
-
- return $this;
- }
-
- public function getName()
- {
- return $this->name;
- }
-
- public function getDefaultValue()
- {
- return $this->defaultValue;
- }
-
- public function hasDefaultValue()
- {
- return $this->hasDefaultValue;
- }
-
- public function isPassedByReference()
- {
- return $this->passedByReference;
- }
-
- public function getType()
- {
- return $this->type;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Generator;
-
-use CG\Core\ReflectionUtils;
-
-/**
- * Represents a PHP property.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class PhpProperty extends AbstractPhpMember
-{
- private $hasDefaultValue = false;
- private $defaultValue;
-
- public static function create($name = null)
- {
- return new static($name);
- }
-
- public static function fromReflection(\ReflectionProperty $ref)
- {
- $property = new static();
- $property
- ->setName($ref->name)
- ->setStatic($ref->isStatic())
- ->setVisibility($ref->isPublic() ? self::VISIBILITY_PUBLIC : ($ref->isProtected() ? self::VISIBILITY_PROTECTED : self::VISIBILITY_PRIVATE))
- ;
-
- if ($docComment = $ref->getDocComment()) {
- $property->setDocblock(ReflectionUtils::getUnindentedDocComment($docComment));
- }
-
- $defaultProperties = $ref->getDeclaringClass()->getDefaultProperties();
- if (isset($defaultProperties[$ref->name])) {
- $property->setDefaultValue($defaultProperties[$ref->name]);
- }
-
- return $property;
- }
-
- public function setDefaultValue($value)
- {
- $this->defaultValue = $value;
- $this->hasDefaultValue = true;
-
- return $this;
- }
-
- public function unsetDefaultValue()
- {
- $this->hasDefaultValue = false;
- $this->defaultValue = null;
-
- return $this;
- }
-
- public function hasDefaultValue()
- {
- return $this->hasDefaultValue;
- }
-
- public function getDefaultValue()
- {
- return $this->defaultValue;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Generator;
-
-/**
- * A writer implementation.
- *
- * This may be used to simplify writing well-formatted code.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class Writer
-{
- private $content = '';
- private $indentationSpaces = 4;
- private $indentationLevel = 0;
-
- public function indent()
- {
- $this->indentationLevel += 1;
-
- return $this;
- }
-
- public function outdent()
- {
- $this->indentationLevel -= 1;
-
- if ($this->indentationLevel < 0) {
- throw new \RuntimeException('The identation level cannot be less than zero.');
- }
-
- return $this;
- }
-
- public function writeln($content)
- {
- $this->write($content."\n");
-
- return $this;
- }
-
- public function write($content)
- {
- $lines = explode("\n", $content);
- for ($i=0,$c=count($lines); $i<$c; $i++) {
- if ($this->indentationLevel > 0
- && !empty($lines[$i])
- && (empty($this->content) || "\n" === substr($this->content, -1))) {
- $this->content .= str_repeat(' ', $this->indentationLevel * $this->indentationSpaces);
- }
-
- $this->content .= $lines[$i];
-
- if ($i+1 < $c) {
- $this->content .= "\n";
- }
- }
-
- return $this;
- }
-
- public function rtrim()
- {
- $addNl = "\n" === substr($this->content, -1);
- $this->content = rtrim($this->content);
-
- if ($addNl) {
- $this->content .= "\n";
- }
-
- return $this;
- }
-
- public function reset()
- {
- $this->content = '';
- $this->indentationLevel = 0;
-
- return $this;
- }
-
- public function getContent()
- {
- return $this->content;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Proxy;
-
-use CG\Core\NamingStrategyInterface;
-
-use CG\Generator\Writer;
-use CG\Generator\PhpMethod;
-use CG\Generator\PhpDocblock;
-use CG\Generator\PhpClass;
-use CG\Core\AbstractClassGenerator;
-
-/**
- * Class enhancing generator implementation.
- *
- * This class enhances existing classes by generating a proxy and leveraging
- * different generator implementation.
- *
- * There are several built-in generator such as lazy-initializing objects, or
- * a generator for creating AOP joinpoints.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class Enhancer extends AbstractClassGenerator
-{
- private $generatedClass;
- private $class;
- private $interfaces;
- private $generators;
-
- public function __construct(\ReflectionClass $class, array $interfaces = array(), array $generators = array())
- {
- if (empty($generators) && empty($interfaces)) {
- throw new \RuntimeException('Either generators, or interfaces must be given.');
- }
-
- $this->class = $class;
- $this->interfaces = $interfaces;
- $this->generators = $generators;
- }
-
- /**
- * Creates a new instance of the enhanced class.
- *
- * @param array $args
- * @return object
- */
- public function createInstance(array $args = array())
- {
- $generatedClass = $this->getClassName($this->class);
-
- if (!class_exists($generatedClass, false)) {
- eval($this->generateClass());
- }
-
- $ref = new \ReflectionClass($generatedClass);
-
- return $ref->newInstanceArgs($args);
- }
-
- public function writeClass($filename)
- {
- if (!is_dir($dir = dirname($filename))) {
- if (false === @mkdir($dir, 0777, true)) {
- throw new \RuntimeException(sprintf('Could not create directory "%s".', $dir));
- }
- }
-
- if (!is_writable($dir)) {
- throw new \RuntimeException(sprintf('The directory "%s" is not writable.', $dir));
- }
-
- file_put_contents($filename, "<?php\n\n".$this->generateClass());
- }
-
- /**
- * Creates a new enhanced class
- *
- * @return string
- */
- public final function generateClass()
- {
- static $docBlock;
- if (empty($docBlock)) {
- $writer = new Writer();
- $writer
- ->writeln('/**')
- ->writeln(' * CG library enhanced proxy class.')
- ->writeln(' *')
- ->writeln(' * This code was generated automatically by the CG library, manual changes to it')
- ->writeln(' * will be lost upon next generation.')
- ->writeln(' */')
- ;
- $docBlock = $writer->getContent();
- }
-
- $this->generatedClass = PhpClass::create()
- ->setDocblock($docBlock)
- ->setParentClassName($this->class->name)
- ;
-
- $proxyClassName = $this->getClassName($this->class);
- if (false === strpos($proxyClassName, NamingStrategyInterface::SEPARATOR)) {
- throw new \RuntimeException(sprintf('The proxy class name must be suffixed with "%s" and an optional string, but got "%s".', NamingStrategyInterface::SEPARATOR, $proxyClassName));
- }
- $this->generatedClass->setName($proxyClassName);
-
- if (!empty($this->interfaces)) {
- $this->generatedClass->setInterfaceNames(array_map(function($v) { return '\\'.$v; }, $this->interfaces));
-
- foreach ($this->getInterfaceMethods() as $method) {
- $method = PhpMethod::fromReflection($method);
- $method->setAbstract(false);
-
- $this->generatedClass->setMethod($method);
- }
- }
-
- if (!empty($this->generators)) {
- foreach ($this->generators as $generator) {
- $generator->generate($this->class, $this->generatedClass);
- }
- }
-
- return $this->generateCode($this->generatedClass);
- }
-
- /**
- * Adds stub methods for the interfaces that have been implemented.
- */
- protected function getInterfaceMethods()
- {
- $methods = array();
-
- foreach ($this->interfaces as $interface) {
- $ref = new \ReflectionClass($interface);
- $methods = array_merge($methods, $ref->getMethods());
- }
-
- return $methods;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Proxy;
-
-use CG\Generator\PhpClass;
-
-/**
- * Interface for enhancing generators.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface GeneratorInterface
-{
- /**
- * Generates the necessary changes in the class.
- *
- * @param \ReflectionClass $originalClass
- * @param PhpClass $generatedClass The generated class
- * @return void
- */
- function generate(\ReflectionClass $originalClass, PhpClass $generatedClass);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Proxy;
-
-use CG\Core\ClassUtils;
-
-use CG\Core\ReflectionUtils;
-
-use CG\Generator\PhpParameter;
-use CG\Generator\PhpProperty;
-use CG\Generator\PhpMethod;
-use CG\Generator\PhpClass;
-
-/**
- * Interception Generator.
- *
- * This generator creates joinpoints to allow for AOP advices. Right now, it only
- * supports the most powerful around advice.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class InterceptionGenerator implements GeneratorInterface
-{
- private $prefix = '__CGInterception__';
- private $filter;
- private $requiredFile;
-
- public function setRequiredFile($file)
- {
- $this->requiredFile = $file;
- }
-
- public function setPrefix($prefix)
- {
- $this->prefix = $prefix;
- }
-
- public function setFilter(\Closure $filter)
- {
- $this->filter = $filter;
- }
-
- public function generate(\ReflectionClass $originalClass, PhpClass $genClass)
- {
- $methods = ReflectionUtils::getOverrideableMethods($originalClass);
-
- if (null !== $this->filter) {
- $methods = array_filter($methods, $this->filter);
- }
-
- if (empty($methods)) {
- return;
- }
-
- if (!empty($this->requiredFile)) {
- $genClass->addRequiredFile($this->requiredFile);
- }
-
- $interceptorLoader = new PhpProperty();
- $interceptorLoader
- ->setName($this->prefix.'loader')
- ->setVisibility(PhpProperty::VISIBILITY_PRIVATE)
- ;
- $genClass->setProperty($interceptorLoader);
-
- $loaderSetter = new PhpMethod();
- $loaderSetter
- ->setName($this->prefix.'setLoader')
- ->setVisibility(PhpMethod::VISIBILITY_PUBLIC)
- ->setBody('$this->'.$this->prefix.'loader = $loader;')
- ;
- $genClass->setMethod($loaderSetter);
- $loaderParam = new PhpParameter();
- $loaderParam
- ->setName('loader')
- ->setType('CG\Proxy\InterceptorLoaderInterface')
- ;
- $loaderSetter->addParameter($loaderParam);
-
- $interceptorCode =
- '$ref = new \ReflectionMethod(%s, %s);'."\n"
- .'$interceptors = $this->'.$this->prefix.'loader->loadInterceptors($ref, $this, array(%s));'."\n"
- .'$invocation = new \CG\Proxy\MethodInvocation($ref, $this, array(%s), $interceptors);'."\n\n"
- .'return $invocation->proceed();'
- ;
-
- foreach ($methods as $method) {
- $params = array();
- foreach ($method->getParameters() as $param) {
- $params[] = '$'.$param->name;
- }
- $params = implode(', ', $params);
-
- $genMethod = PhpMethod::fromReflection($method)
- ->setBody(sprintf($interceptorCode, var_export(ClassUtils::getUserClass($method->class), true), var_export($method->name, true), $params, $params))
- ->setDocblock(null)
- ;
- $genClass->setMethod($genMethod);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Proxy;
-
-/**
- * Interception Loader.
- *
- * Implementations of this interface are responsible for loading the interceptors
- * for a certain method.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface InterceptorLoaderInterface
-{
- /**
- * Loads interceptors.
- *
- * @param \ReflectionMethod $method
- * @return array<MethodInterceptorInterface>
- */
- function loadInterceptors(\ReflectionMethod $method);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Proxy;
-
-use CG\Generator\Writer;
-use CG\Core\ReflectionUtils;
-use CG\Generator\GeneratorUtils;
-use CG\Generator\PhpParameter;
-use CG\Generator\PhpMethod;
-use CG\Generator\PhpProperty;
-use CG\Generator\PhpClass;
-
-/**
- * Generator for creating lazy-initializing instances.
- *
- * This generator enhances concrete classes to allow for them to be lazily
- * initialized upon first access.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class LazyInitializerGenerator implements GeneratorInterface
-{
- private $writer;
- private $prefix = '__CG__';
- private $markerInterface;
-
- public function __construct()
- {
- $this->writer = new Writer();
- }
-
- public function setPrefix($prefix)
- {
- $this->prefix = $prefix;
- }
-
- /**
- * Sets the marker interface which should be implemented by the
- * generated classes.
- *
- * @param string $interface The FQCN of the interface
- */
- public function setMarkerInterface($interface)
- {
- $this->markerInterface = $interface;
- }
-
- /**
- * Generates the necessary methods in the class.
- *
- * @param \ReflectionClass $originalClass
- * @param PhpClass $class
- * @return void
- */
- public function generate(\ReflectionClass $originalClass, PhpClass $class)
- {
- $methods = ReflectionUtils::getOverrideableMethods($originalClass, true);
-
- // no public, non final methods
- if (empty($methods)) {
- return;
- }
-
- if (null !== $this->markerInterface) {
- $class->setImplementedInterfaces(array_merge(
- $class->getImplementedInterfaces(),
- array($this->markerInterface)
- ));
- }
-
- $initializer = new PhpProperty();
- $initializer->setName($this->prefix.'lazyInitializer');
- $initializer->setVisibility(PhpProperty::VISIBILITY_PRIVATE);
- $class->setProperty($initializer);
-
- $initialized = new PhpProperty();
- $initialized->setName($this->prefix.'initialized');
- $initialized->setDefaultValue(false);
- $initialized->setVisibility(PhpProperty::VISIBILITY_PRIVATE);
- $class->setProperty($initialized);
-
- $initializerSetter = new PhpMethod();
- $initializerSetter->setName($this->prefix.'setLazyInitializer');
- $initializerSetter->setBody('$this->'.$this->prefix.'lazyInitializer = $initializer;');
-
- $parameter = new PhpParameter();
- $parameter->setName('initializer');
- $parameter->setType('\CG\Proxy\LazyInitializerInterface');
- $initializerSetter->addParameter($parameter);
- $class->setMethod($initializerSetter);
-
- $this->addMethods($class, $methods);
-
- $initializingMethod = new PhpMethod();
- $initializingMethod->setName($this->prefix.'initialize');
- $initializingMethod->setVisibility(PhpMethod::VISIBILITY_PRIVATE);
- $initializingMethod->setBody(
- $this->writer
- ->reset()
- ->writeln('if (null === $this->'.$this->prefix.'lazyInitializer) {')
- ->indent()
- ->writeln('throw new \RuntimeException("'.$this->prefix.'setLazyInitializer() must be called prior to any other public method on this object.");')
- ->outdent()
- ->write("}\n\n")
- ->writeln('$this->'.$this->prefix.'lazyInitializer->initializeObject($this);')
- ->writeln('$this->'.$this->prefix.'initialized = true;')
- ->getContent()
- );
- $class->setMethod($initializingMethod);
- }
-
- private function addMethods(PhpClass $class, array $methods)
- {
- foreach ($methods as $method) {
- $initializingCode = 'if (false === $this->'.$this->prefix.'initialized) {'."\n"
- .' $this->'.$this->prefix.'initialize();'."\n"
- .'}';
-
- if ($class->hasMethod($method->name)) {
- $genMethod = $class->getMethod($method->name);
- $genMethod->setBody(
- $initializingCode."\n"
- .$genMethod->getBody()
- );
-
- continue;
- }
-
- $genMethod = PhpMethod::fromReflection($method);
- $genMethod->setBody(
- $initializingCode."\n\n"
- .'return '.GeneratorUtils::callMethod($method).';'
- );
- $class->setMethod($genMethod);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Proxy;
-
-/**
- * Lazy Initializer.
- *
- * Implementations of this interface are responsible for lazily initializing
- * object instances.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface LazyInitializerInterface
-{
- /**
- * Initializes the passed object.
- *
- * @param object $object
- * @return void
- */
- function initializeObject($object);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Proxy;
-
-/**
- * Interface for Method Interceptors.
- *
- * Implementations of this interface can execute custom code before, and after the
- * invocation of the actual method. In addition, they can also catch, or throw
- * exceptions, modify the return value, or modify the arguments.
- *
- * This is also known as around advice in AOP terminology.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface MethodInterceptorInterface
-{
- /**
- * Called when intercepting a method call.
- *
- * @param MethodInvocation $invocation
- * @return mixed the return value for the method invocation
- * @throws \Exception may throw any exception
- */
- function intercept(MethodInvocation $invocation);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Proxy;
-
-/**
- * Represents a method invocation.
- *
- * This object contains information for the method invocation, such as the object
- * on which the method is invoked, and the arguments that are passed to the method.
- *
- * Before the actual method is called, first all the interceptors must call the
- * proceed() method on this class.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class MethodInvocation
-{
- public $reflection;
- public $object;
- public $arguments;
-
- private $interceptors;
- private $pointer;
-
- public function __construct(\ReflectionMethod $reflection, $object, array $arguments, array $interceptors)
- {
- $this->reflection = $reflection;
- $this->object = $object;
- $this->arguments = $arguments;
- $this->interceptors = $interceptors;
- $this->pointer = 0;
- }
-
- /**
- * Proceeds down the call-chain and eventually calls the original method.
- *
- * @return mixed
- */
- public function proceed()
- {
- if (isset($this->interceptors[$this->pointer])) {
- return $this->interceptors[$this->pointer++]->intercept($this);
- }
-
- $this->reflection->setAccessible(true);
-
- return $this->reflection->invokeArgs($this->object, $this->arguments);
- }
-
- /**
- * Returns a string representation of the method.
- *
- * This is intended for debugging purposes only.
- *
- * @return string
- */
- public function __toString()
- {
- return sprintf('%s::%s', $this->reflection->class, $this->reflection->name);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace CG\Proxy;
-
-class RegexInterceptionLoader implements InterceptorLoaderInterface
-{
- private $interceptors;
-
- public function __construct(array $interceptors = array())
- {
- $this->interceptors = $interceptors;
- }
-
- public function loadInterceptors(\ReflectionMethod $method)
- {
- $signature = $method->class.'::'.$method->name;
-
- $matchingInterceptors = array();
- foreach ($this->interceptors as $pattern => $interceptor) {
- if (preg_match('#'.$pattern.'#', $signature)) {
- $matchingInterceptors[] = $this->initializeInterceptor($interceptor);
- }
- }
-
- return $matchingInterceptors;
- }
-
- protected function initializeInterceptor($interceptor)
- {
- return $interceptor;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG;
-
-class Version
-{
- const VERSION = '1.0.0';
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Core;
-
-use CG\Core\ClassUtils;
-
-class ClassUtilsTest extends \PHPUnit_Framework_TestCase
-{
- public function testGetUserClassName()
- {
- $this->assertEquals('Foo', ClassUtils::getUserClass('Foo'));
- $this->assertEquals('Bar', ClassUtils::getUserClass('FOO\__CG__\Bar'));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Core;
-
-use CG\Core\DefaultGeneratorStrategy;
-
-use CG\Generator\PhpProperty;
-use CG\Generator\PhpMethod;
-use CG\Generator\PhpClass;
-
-class DefaultGeneratorStrategyTest extends \PHPUnit_Framework_TestCase
-{
- public function testGenerate()
- {
- $strategy = new DefaultGeneratorStrategy();
- $strategy->setConstantSortFunc(function($a, $b) {
- return strcasecmp($a, $b);
- });
- $strategy->setMethodSortFunc($func = function($a, $b) {
- return strcasecmp($a->getName(), $b->getName());
- });
- $strategy->setPropertySortFunc($func);
-
- $this->assertEquals(
- $this->getContent('GenerationTestClass_A.php'),
- $strategy->generate($this->getClass())
- );
- }
-
- public function testGenerateChangedConstantOrder()
- {
- $strategy = new DefaultGeneratorStrategy();
- $strategy->setConstantSortFunc(function($a, $b) {
- return -1 * strcasecmp($a, $b);
- });
- $strategy->setMethodSortFunc($func = function($a, $b) {
- return strcasecmp($a->getName(), $b->getName());
- });
- $strategy->setPropertySortFunc($func);
-
- $this->assertEquals(
- $this->getContent('GenerationTestClass_B.php'),
- $strategy->generate($this->getClass())
- );
- }
-
- private function getContent($file)
- {
- return file_get_contents(__DIR__.'/generated/'.$file);
- }
-
- private function getClass()
- {
- $class = PhpClass::create()
- ->setName('GenerationTestClass')
- ->setMethod(PhpMethod::create('a'))
- ->setMethod(PhpMethod::create('b'))
- ->setProperty(PhpProperty::create('a'))
- ->setProperty(PhpProperty::create('b'))
- ->setConstant('a', 'foo')
- ->setConstant('b', 'bar')
- ;
-
- return $class;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Core;
-
-use CG\Generator\Writer;
-use CG\Core\ReflectionUtils;
-
-class ReflectionUtilsTest extends \PHPUnit_Framework_TestCase
-{
- public function testGetOverridableMethods()
- {
- $ref = new \ReflectionClass('CG\Tests\Core\OverridableReflectionTest');
- $methods = ReflectionUtils::getOverrideableMethods($ref);
-
- $this->assertEquals(4, count($methods));
-
- $methods = array_map(function($v) { return $v->name; }, $methods);
- sort($methods);
- $this->assertEquals(array('a', 'd', 'e', 'h'), $methods);
- }
-
- public function testGetUnindentedDocComment()
- {
- $writer = new Writer();
- $comment = $writer
- ->writeln('/**')
- ->indent()
- ->writeln(' * Foo.')
- ->write(' */')
- ->getContent()
- ;
-
- $this->assertEquals("/**\n * Foo.\n */", ReflectionUtils::getUnindentedDocComment($comment));
- }
-}
-
-abstract class OverridableReflectionTest
-{
- public function a() { }
- public final function b() { }
- public static function c() { }
- abstract public function d();
- protected function e() { }
- protected final function f() {}
- protected static function g() { }
- abstract protected function h();
- private function i() { }
-}
\ No newline at end of file
+++ /dev/null
-class GenerationTestClass
-{
- const a = 'foo';
- const b = 'bar';
-
- public $a;
- public $b;
-
- public function a()
- {
- }
-
- public function b()
- {
- }
-}
\ No newline at end of file
+++ /dev/null
-class GenerationTestClass
-{
- const b = 'bar';
- const a = 'foo';
-
- public $a;
- public $b;
-
- public function a()
- {
- }
-
- public function b()
- {
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Generator;
-
-class AbstractPhpMemberTest extends \PHPUnit_Framework_TestCase
-{
- public function testSetGetStatic()
- {
- $member = $this->getMember();
-
- $this->assertFalse($member->isStatic());
- $this->assertSame($member, $member->setStatic(true));
- $this->assertTrue($member->isStatic());
- $this->assertSame($member, $member->setStatic(false));
- $this->assertFalse($member->isStatic());
- }
-
- public function testSetGetVisibility()
- {
- $member = $this->getMember();
-
- $this->assertEquals('public', $member->getVisibility());
- $this->assertSame($member, $member->setVisibility('private'));
- $this->assertEquals('private', $member->getVisibility());
- }
-
- /**
- * @expectedException \InvalidArgumentException
- */
- public function testSetVisibilityThrowsExOnInvalidValue()
- {
- $member = $this->getMember();
- $member->setVisibility('foo');
- }
-
- public function testSetGetName()
- {
- $member = $this->getMember();
-
- $this->assertNull($member->getName());
- $this->assertSame($member, $member->setName('foo'));
- $this->assertEquals('foo', $member->getName());
- }
-
- public function testSetGetDocblock()
- {
- $member = $this->getMember();
-
- $this->assertNull($member->getDocblock());
- $this->assertSame($member, $member->setDocblock('foo'));
- $this->assertEquals('foo', $member->getDocblock());
- }
-
- private function getMember()
- {
- return $this->getMockForAbstractClass('CG\Generator\AbstractPhpMember');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Generator;
-
-use CG\Generator\DefaultVisitor;
-use CG\Generator\PhpParameter;
-use CG\Generator\Writer;
-use CG\Generator\PhpFunction;
-
-class DefaultVisitorTest extends \PHPUnit_Framework_TestCase
-{
- public function testVisitFunction()
- {
- $writer = new Writer();
-
- $function = new PhpFunction();
- $function
- ->setName('foo')
- ->addParameter(PhpParameter::create('a'))
- ->addParameter(PhpParameter::create('b'))
- ->setBody(
- $writer
- ->writeln('if ($a === $b) {')
- ->indent()
- ->writeln('throw new \InvalidArgumentException(\'$a is not allowed to be the same as $b.\');')
- ->outdent()
- ->write("}\n\n")
- ->write('return $b;')
- ->getContent()
- )
- ;
-
- $visitor = new DefaultVisitor();
- $visitor->visitFunction($function);
-
- $this->assertEquals($this->getContent('a_b_function.php'), $visitor->getContent());
- }
-
- private function getContent($filename)
- {
- if (!is_file($path = __DIR__.'/Fixture/generated/'.$filename)) {
- throw new \InvalidArgumentException(sprintf('The file "%s" does not exist.', $path));
- }
-
- return file_get_contents($path);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Generator\Fixture;
-
-/**
- * Doc Comment.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-abstract class Entity
-{
- /**
- * @var integer
- */
- private $id;
- private $enabled = false;
-
- /**
- * Another doc comment.
- *
- * @param unknown_type $a
- * @param array $b
- * @param \stdClass $c
- * @param unknown_type $d
- */
- public final function __construct($a, array &$b, \stdClass $c, $d = 'foo')
- {
- }
-
- abstract protected function foo();
-
- private static function bar()
- {
- }
-}
\ No newline at end of file
+++ /dev/null
-function foo($a, $b)
-{
- if ($a === $b) {
- throw new \InvalidArgumentException('$a is not allowed to be the same as $b.');
- }
-
- return $b;
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Generator;
-
-use CG\Generator\PhpProperty;
-
-use CG\Generator\PhpParameter;
-use CG\Generator\PhpMethod;
-use CG\Generator\PhpClass;
-
-class PhpClassTest extends \PHPUnit_Framework_TestCase
-{
- public function testFromReflection()
- {
- $class = new PhpClass();
- $class
- ->setName('CG\Tests\Generator\Fixture\Entity')
- ->setAbstract(true)
- ->setDocblock('/**
- * Doc Comment.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */')
- ->setProperty(PhpProperty::create('id')
- ->setVisibility('private')
- ->setDocblock('/**
- * @var integer
- */')
- )
- ->setProperty(PhpProperty::create('enabled')
- ->setVisibility('private')
- ->setDefaultValue(false)
- )
- ;
-
- $method = PhpMethod::create()
- ->setName('__construct')
- ->setFinal(true)
- ->addParameter(new PhpParameter('a'))
- ->addParameter(PhpParameter::create()
- ->setName('b')
- ->setType('array')
- ->setPassedByReference(true)
- )
- ->addParameter(PhpParameter::create()
- ->setName('c')
- ->setType('stdClass')
- )
- ->addParameter(PhpParameter::create()
- ->setName('d')
- ->setDefaultValue('foo')
- )->setDocblock('/**
- * Another doc comment.
- *
- * @param unknown_type $a
- * @param array $b
- * @param \stdClass $c
- * @param unknown_type $d
- */')
- ;
- $class->setMethod($method);
-
- $class->setMethod(PhpMethod::create()
- ->setName('foo')
- ->setAbstract(true)
- ->setVisibility('protected')
- );
-
- $class->setMethod(PhpMethod::create()
- ->setName('bar')
- ->setStatic(true)
- ->setVisibility('private')
- );
-
- $this->assertEquals($class, PhpClass::fromReflection(new \ReflectionClass('CG\Tests\Generator\Fixture\Entity')));
- }
-
- public function testGetSetName()
- {
- $class = new PhpClass();
- $this->assertNull($class->getName());
-
- $class = new PhpClass('foo');
- $this->assertEquals('foo', $class->getName());
- $this->assertSame($class, $class->setName('bar'));
- $this->assertEquals('bar', $class->getName());
- }
-
- public function testSetGetConstants()
- {
- $class = new PhpClass();
-
- $this->assertEquals(array(), $class->getConstants());
- $this->assertSame($class, $class->setConstants(array('foo' => 'bar')));
- $this->assertEquals(array('foo' => 'bar'), $class->getConstants());
- $this->assertSame($class, $class->setConstant('bar', 'baz'));
- $this->assertEquals(array('foo' => 'bar', 'bar' => 'baz'), $class->getConstants());
- $this->assertSame($class, $class->removeConstant('foo'));
- $this->assertEquals(array('bar' => 'baz'), $class->getConstants());
- }
-
- /**
- * @expectedException \InvalidArgumentException
- */
- public function testRemoveConstantThrowsExceptionWhenConstantDoesNotExist()
- {
- $class = new PhpClass();
- $class->removeConstant('foo');
- }
-
- public function testSetIsAbstract()
- {
- $class = new PhpClass();
-
- $this->assertFalse($class->isAbstract());
- $this->assertSame($class, $class->setAbstract(true));
- $this->assertTrue($class->isAbstract());
- $this->assertSame($class, $class->setAbstract(false));
- $this->assertFalse($class->isAbstract());
- }
-
- public function testSetIsFinal()
- {
- $class = new PhpClass();
-
- $this->assertFalse($class->isFinal());
- $this->assertSame($class, $class->setFinal(true));
- $this->assertTrue($class->isFinal());
- $this->assertSame($class, $class->setFinal(false));
- $this->assertFalse($class->isFinal());
- }
-
- public function testSetGetParentClassName()
- {
- $class = new PhpClass();
-
- $this->assertNull($class->getParentClassName());
- $this->assertSame($class, $class->setParentClassName('stdClass'));
- $this->assertEquals('stdClass', $class->getParentClassName());
- $this->assertSame($class, $class->setParentClassName(null));
- $this->assertNull($class->getParentClassName());
- }
-
- public function testSetGetInterfaceNames()
- {
- $class = new PhpClass();
-
- $this->assertEquals(array(), $class->getInterfaceNames());
- $this->assertSame($class, $class->setInterfaceNames(array('foo', 'bar')));
- $this->assertEquals(array('foo', 'bar'), $class->getInterfaceNames());
- $this->assertSame($class, $class->addInterfaceName('stdClass'));
- $this->assertEquals(array('foo', 'bar', 'stdClass'), $class->getInterfaceNames());
- }
-
- public function testSetGetUseStatements()
- {
- $class = new PhpClass();
-
- $this->assertEquals(array(), $class->getUseStatements());
- $this->assertSame($class, $class->setUseStatements(array('foo' => 'bar')));
- $this->assertEquals(array('foo' => 'bar'), $class->getUseStatements());
- $this->assertSame($class, $class->addUseStatement('Foo\Bar'));
- $this->assertEquals(array('foo' => 'bar', 'Bar' => 'Foo\Bar'), $class->getUseStatements());
- $this->assertSame($class, $class->addUseStatement('Foo\Bar', 'Baz'));
- $this->assertEquals(array('foo' => 'bar', 'Bar' => 'Foo\Bar', 'Baz' => 'Foo\Bar'), $class->getUseStatements());
- }
-
- public function testSetGetProperties()
- {
- $class = new PhpClass();
-
- $this->assertEquals(array(), $class->getProperties());
- $this->assertSame($class, $class->setProperties($props = array('foo' => new PhpProperty())));
- $this->assertSame($props, $class->getProperties());
- $this->assertSame($class, $class->setProperty($prop = new PhpProperty('foo')));
- $this->assertSame(array('foo' => $prop), $class->getProperties());
- $this->assertTrue($class->hasProperty('foo'));
- $this->assertSame($class, $class->removeProperty('foo'));
- $this->assertEquals(array(), $class->getProperties());
- }
-
- public function testSetGetMethods()
- {
- $class = new PhpClass();
-
- $this->assertEquals(array(), $class->getMethods());
- $this->assertSame($class, $class->setMethods($methods = array('foo' => new PhpMethod())));
- $this->assertSame($methods, $class->getMethods());
- $this->assertSame($class, $class->setMethod($method = new PhpMethod('foo')));
- $this->assertSame(array('foo' => $method), $class->getMethods());
- $this->assertTrue($class->hasMethod('foo'));
- $this->assertSame($class, $class->removeMethod('foo'));
- $this->assertEquals(array(), $class->getMethods());
- }
-
- public function testSetGetDocblock()
- {
- $class = new PhpClass();
-
- $this->assertNull($class->getDocblock());
- $this->assertSame($class, $class->setDocblock('foo'));
- $this->assertEquals('foo', $class->getDocblock());
- }
-
- public function testSetGetRequiredFiles()
- {
- $class = new PhpClass();
-
- $this->assertEquals(array(), $class->getRequiredFiles());
- $this->assertSame($class, $class->setRequiredFiles(array('foo')));
- $this->assertEquals(array('foo'), $class->getRequiredFiles());
- $this->assertSame($class, $class->addRequiredFile('bar'));
- $this->assertEquals(array('foo', 'bar'), $class->getRequiredFiles());
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Generator;
-
-use CG\Generator\PhpParameter;
-
-use CG\Generator\PhpFunction;
-
-class PhpFunctionTest extends \PHPUnit_Framework_TestCase
-{
- public function testSetGetName()
- {
- $func = new PhpFunction();
-
- $this->assertNull($func->getName());
- $this->assertSame($func, $func->setName('foo'));
- $this->assertEquals('foo', $func->getName());
-
- $func = new PhpFunction('foo');
- $this->assertEquals('foo', $func->getName());
- }
-
- public function testSetGetNamespace()
- {
- $func = new PhpFunction();
-
- $this->assertNull($func->getNamespace());
- $this->assertSame($func, $func->setNamespace('foo'));
- $this->assertEquals('foo', $func->getNamespace());
- }
-
- public function testSetGetBody()
- {
- $func = new PhpFunction();
-
- $this->assertSame('', $func->getBody());
- $this->assertSame($func, $func->setBody('foo'));
- $this->assertEquals('foo', $func->getBody());
- }
-
- public function testSetGetParameters()
- {
- $func = new PhpFunction();
-
- $this->assertEquals(array(), $func->getParameters());
- $this->assertSame($func, $func->setParameters(array($param = new PhpParameter())));
- $this->assertSame(array($param), $func->getParameters());
- $this->assertSame($func, $func->addParameter($param2 = new PhpParameter()));
- $this->assertSame(array($param, $param2), $func->getParameters());
- $this->assertSame($func, $func->replaceParameter(1, $param3 = new PhpParameter()));
- $this->assertSame(array($param, $param3), $func->getParameters());
- $this->assertSame($func, $func->removeParameter(0));
- $this->assertSame(array($param3), $func->getParameters());
- }
-
- public function testSetGetDocblock()
- {
- $func = new PhpFunction();
-
- $this->assertNull($func->getDocblock());
- $this->assertSame($func, $func->setDocblock('foo'));
- $this->assertEquals('foo', $func->getDocblock());
- }
-
- public function testSetIsReferenceReturned()
- {
- $func = new PhpFunction();
-
- $this->assertFalse($func->isReferenceReturned());
- $this->assertSame($func, $func->setReferenceReturned(true));
- $this->assertTrue($func->isReferenceReturned());
- $this->assertSame($func, $func->setReferenceReturned(false));
- $this->assertFalse($func->isReferenceReturned());
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Generator;
-
-use CG\Generator\PhpParameter;
-
-use CG\Generator\PhpMethod;
-
-class PhpMethodTest extends \PHPUnit_Framework_TestCase
-{
- public function testSetIsFinal()
- {
- $method = new PhpMethod();
-
- $this->assertFalse($method->isFinal());
- $this->assertSame($method, $method->setFinal(true));
- $this->assertTrue($method->isFinal());
- $this->assertSame($method, $method->setFinal(false));
- $this->assertFalse($method->isFinal());
- }
-
- public function testSetIsAbstract()
- {
- $method = new PhpMethod();
-
- $this->assertFalse($method->isAbstract());
- $this->assertSame($method, $method->setAbstract(true));
- $this->assertTrue($method->isAbstract());
- $this->assertSame($method, $method->setAbstract(false));
- $this->assertFalse($method->isAbstract());
- }
-
- public function testSetGetParameters()
- {
- $method = new PhpMethod();
-
- $this->assertEquals(array(), $method->getParameters());
- $this->assertSame($method, $method->setParameters($params = array(new PhpParameter())));
- $this->assertSame($params, $method->getParameters());
-
- $this->assertSame($method, $method->addParameter($param = new PhpParameter()));
- $params[] = $param;
- $this->assertSame($params, $method->getParameters());
-
- $this->assertSame($method, $method->removeParameter(0));
- unset($params[0]);
- $this->assertSame(array($param), $method->getParameters());
-
- $this->assertSame($method, $method->addParameter($param = new PhpParameter()));
- $params[] = $param;
- $params = array_values($params);
- $this->assertSame($params, $method->getParameters());
- }
-
- public function testSetGetBody()
- {
- $method = new PhpMethod();
-
- $this->assertSame('', $method->getBody());
- $this->assertSame($method, $method->setBody('foo'));
- $this->assertEquals('foo', $method->getBody());
- }
-
- public function testSetIsReferenceReturned()
- {
- $method = new PhpMethod();
-
- $this->assertFalse($method->isReferenceReturned());
- $this->assertSame($method, $method->setReferenceReturned(true));
- $this->assertTrue($method->isReferenceReturned());
- $this->assertSame($method, $method->setReferenceReturned(false));
- $this->assertFalse($method->isReferenceReturned());
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Generator;
-
-use CG\Generator\PhpParameter;
-
-class PhpParameterTest extends \PHPUnit_Framework_TestCase
-{
- public function testSetGetName()
- {
- $param = new PhpParameter();
-
- $this->assertNull($param->getName());
- $this->assertSame($param, $param->setName('foo'));
- $this->assertEquals('foo', $param->getName());
- }
-
- public function testSetGetDefaultValue()
- {
- $param = new PhpParameter();
-
- $this->assertNull($param->getDefaultValue());
- $this->assertFalse($param->hasDefaultValue());
- $this->assertSame($param, $param->setDefaultValue('foo'));
- $this->assertEquals('foo', $param->getDefaultValue());
- $this->assertTrue($param->hasDefaultValue());
- $this->assertSame($param, $param->unsetDefaultValue());
- $this->assertNull($param->getDefaultValue());
- $this->assertFalse($param->hasDefaultValue());
- }
-
- public function testSetIsPassedByReference()
- {
- $param = new PhpParameter();
-
- $this->assertFalse($param->isPassedByReference());
- $this->assertSame($param, $param->setPassedByReference(true));
- $this->assertTrue($param->isPassedByReference());
- $this->assertSame($param, $param->setPassedByReference(false));
- $this->assertFalse($param->isPassedByReference());
- }
-
- public function testSetGetType()
- {
- $param = new PhpParameter();
-
- $this->assertNull($param->getType());
- $this->assertSame($param, $param->setType('array'));
- $this->assertEquals('array', $param->getType());
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Generator;
-
-use CG\Generator\PhpProperty;
-
-class PhpPropertyTest extends \PHPUnit_Framework_TestCase
-{
- public function testSetGetDefaultValue()
- {
- $prop = new PhpProperty();
-
- $this->assertNull($prop->getDefaultValue());
- $this->assertFalse($prop->hasDefaultValue());
- $this->assertSame($prop, $prop->setDefaultValue('foo'));
- $this->assertEquals('foo', $prop->getDefaultValue());
- $this->assertTrue($prop->hasDefaultValue());
- $this->assertSame($prop, $prop->unsetDefaultValue());
- $this->assertNull($prop->getDefaultValue());
- $this->assertFalse($prop->hasDefaultValue());
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Proxy;
-
-use CG\Proxy\LazyInitializerInterface;
-use CG\Proxy\InterceptionGenerator;
-use CG\Proxy\LazyInitializerGenerator;
-use CG\Proxy\Enhancer;
-use CG\Tests\Proxy\Fixture\TraceInterceptor;
-
-class EnhancerTest extends \PHPUnit_Framework_TestCase
-{
- /**
- * @dataProvider getGenerationTests
- */
- public function testGenerateClass($class, $generatedClass, array $interfaces, array $generators)
- {
- $enhancer = new Enhancer(new \ReflectionClass($class), $interfaces, $generators);
- $enhancer->setNamingStrategy($this->getNamingStrategy($generatedClass));
-
- $this->assertEquals($this->getContent(substr($generatedClass, strrpos($generatedClass, '\\') + 1)), $enhancer->generateClass());
- }
-
- public function getGenerationTests()
- {
- return array(
- array('CG\Tests\Proxy\Fixture\SimpleClass', 'CG\Tests\Proxy\Fixture\SimpleClass__CG__Enhanced', array('CG\Tests\Proxy\Fixture\MarkerInterface'), array()),
- array('CG\Tests\Proxy\Fixture\SimpleClass', 'CG\Tests\Proxy\Fixture\SimpleClass__CG__Sluggable', array('CG\Tests\Proxy\Fixture\SluggableInterface'), array()),
- array('CG\Tests\Proxy\Fixture\Entity', 'CG\Tests\Proxy\Fixture\Entity__CG__LazyInitializing', array(), array(
- new LazyInitializerGenerator(),
- ))
- );
- }
-
- public function testInterceptionGenerator()
- {
- $enhancer = new Enhancer(new \ReflectionClass('CG\Tests\Proxy\Fixture\Entity'), array(), array(
- $generator = new InterceptionGenerator()
- ));
- $enhancer->setNamingStrategy($this->getNamingStrategy('CG\Tests\Proxy\Fixture\Entity__CG__Traceable_'.sha1(microtime(true))));
- $generator->setPrefix('');
-
- $traceable = $enhancer->createInstance();
- $traceable->setLoader($this->getLoader(array(
- $interceptor1 = new TraceInterceptor(),
- $interceptor2 = new TraceInterceptor(),
- )));
-
- $this->assertEquals('foo', $traceable->getName());
- $this->assertEquals('foo', $traceable->getName());
- $this->assertEquals(2, count($interceptor1->getLog()));
- $this->assertEquals(2, count($interceptor2->getLog()));
- }
-
- public function testLazyInitializerGenerator()
- {
- $enhancer = new Enhancer(new \ReflectionClass('CG\Tests\Proxy\Fixture\Entity'), array(), array(
- $generator = new LazyInitializerGenerator(),
- ));
- $generator->setPrefix('');
-
- $entity = $enhancer->createInstance();
- $entity->setLazyInitializer($initializer = new Initializer());
- $this->assertEquals('foo', $entity->getName());
- $this->assertSame($entity, $initializer->getLastObject());
- }
-
- private function getLoader(array $interceptors)
- {
- $loader = $this->getMock('CG\Proxy\InterceptorLoaderInterface');
- $loader
- ->expects($this->any())
- ->method('loadInterceptors')
- ->will($this->returnValue($interceptors))
- ;
-
- return $loader;
- }
-
- private function getContent($file)
- {
- return file_get_contents(__DIR__.'/Fixture/generated/'.$file.'.php.gen');
- }
-
- private function getNamingStrategy($name)
- {
- $namingStrategy = $this->getMock('CG\Core\NamingStrategyInterface');
- $namingStrategy
- ->expects($this->any())
- ->method('getClassName')
- ->will($this->returnValue($name))
- ;
-
- return $namingStrategy;
- }
-}
-
-class Initializer implements LazyInitializerInterface
-{
- private $lastObject;
-
- public function initializeObject($object)
- {
- $this->lastObject = $object;
- }
-
- public function getLastObject()
- {
- return $this->lastObject;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Proxy\Fixture;
-
-class Entity
-{
- public function getName()
- {
- return 'foo';
- }
-
- public final function getBaz()
- {
- }
-
- protected function getFoo()
- {
- }
-
- private function getBar()
- {
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Proxy
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Proxy\Fixture;
-
-interface MarkerInterface
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Proxy\Fixture;
-
-class SimpleClass
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Proxy\Fixture;
-
-interface SluggableInterface
-{
- function getSlug();
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace CG\Tests\Proxy\Fixture;
-
-use CG\Proxy\MethodInvocation;
-use CG\Proxy\MethodInterceptorInterface;
-
-class TraceInterceptor implements MethodInterceptorInterface
-{
- private $log;
-
- public function getLog()
- {
- return $this->log;
- }
-
- public function intercept(MethodInvocation $method)
- {
- $message = sprintf('%s::%s(', $method->reflection->class, $method->reflection->name);
-
- $logArgs = array();
- foreach ($method->arguments as $arg) {
- $logArgs[] = var_export($arg, true);
- }
- $this->log[] = $message.implode(', ', $logArgs).')';
-
- return $method->proceed();
- }
-}
\ No newline at end of file
+++ /dev/null
-namespace CG\Tests\Proxy\Fixture;
-
-/**
- * CG library enhanced proxy class.
- *
- * This code was generated automatically by the CG library, manual changes to it
- * will be lost upon next generation.
- */
-class Entity__CG__LazyInitializing extends \CG\Tests\Proxy\Fixture\Entity
-{
- private $__CG__lazyInitializer;
- private $__CG__initialized = false;
-
- public function getName()
- {
- if (false === $this->__CG__initialized) {
- $this->__CG__initialize();
- }
-
- return \CG\Tests\Proxy\Fixture\Entity::getName();
- }
-
- public function __CG__setLazyInitializer(\CG\Proxy\LazyInitializerInterface $initializer)
- {
- $this->__CG__lazyInitializer = $initializer;
- }
-
- private function __CG__initialize()
- {
- if (null === $this->__CG__lazyInitializer) {
- throw new \RuntimeException("__CG__setLazyInitializer() must be called prior to any other public method on this object.");
- }
-
- $this->__CG__lazyInitializer->initializeObject($this);
- $this->__CG__initialized = true;
- }
-}
\ No newline at end of file
+++ /dev/null
-namespace CG\Tests\Proxy\Fixture;
-
-/**
- * CG library enhanced proxy class.
- *
- * This code was generated automatically by the CG library, manual changes to it
- * will be lost upon next generation.
- */
-class SimpleClass__CG__Enhanced extends \CG\Tests\Proxy\Fixture\SimpleClass implements \CG\Tests\Proxy\Fixture\MarkerInterface
-{
-}
\ No newline at end of file
+++ /dev/null
-namespace CG\Tests\Proxy\Fixture;
-
-/**
- * CG library enhanced proxy class.
- *
- * This code was generated automatically by the CG library, manual changes to it
- * will be lost upon next generation.
- */
-class SimpleClass__CG__Sluggable extends \CG\Tests\Proxy\Fixture\SimpleClass implements \CG\Tests\Proxy\Fixture\SluggableInterface
-{
- public function getSlug()
- {
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * This file is part of the CG library.
- *
- * (C) 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- */
-
-spl_autoload_register(function($class)
-{
- if (0 === strpos($class, 'CG\Tests\\')) {
- $path = __DIR__.'/../tests/'.strtr($class, '\\', '/').'.php';
- if (file_exists($path) && is_readable($path)) {
- require_once $path;
-
- return true;
- }
- } else if (0 === strpos($class, 'CG\\')) {
- $path = __DIR__.'/../src/'.($class = strtr($class, '\\', '/')).'.php';
- if (file_exists($path) && is_readable($path)) {
- require_once $path;
-
- return true;
- }
- } else if (0 === strpos($class, 'Zend\\')) {
- $path = __DIR__.'/../../zend-framework2/library/'.($class = strtr($class, '\\', '/')).'.php';
- if (file_exists($path) && is_readable($path)) {
- require_once $path;
-
- return true;
- }
- }
-});
-
+++ /dev/null
-<?php
-
-namespace JMS\DiExtraBundle\Annotation;
-
-/**
- * @Annotation
- * @Target("METHOD")
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-final class AfterSetup
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Annotation;
-
-use JMS\DiExtraBundle\Exception\InvalidTypeException;
-
-/**
- * @Annotation
- * @Target("CLASS")
- */
-class DoctrineListener
-{
- /** @var array<string> @Required */
- public $events;
-
- /** @var string */
- public $connection;
-
- /** @var boolean */
- public $lazy = true;
-
- /** @var integer */
- public $priority = 0;
-
- public function __construct()
- {
- if (0 === func_num_args()) {
- return;
- }
- $values = func_get_arg(0);
-
- if (!isset($values['value'])) {
- throw new InvalidTypeException('DoctrineListener', 'value', 'array or string', null);
- }
- $this->events = (array) $values['value'];
-
- if (isset($values['connection'])) {
- if (!is_string($values['connection'])) {
- throw new InvalidTypeException('DoctrineListener', 'connection', 'string', $values['connection']);
- }
- $this->connection = $values['connection'];
- }
-
- if (isset($values['lazy'])) {
- if (!is_boolean($values['lazy'])) {
- throw new InvalidTypeException('DoctrineListener', 'lazy', 'boolean', $values['lazy']);
- }
- $this->lazy = $values['lazy'];
- }
-
- if (isset($values['priority'])) {
- if (!is_integer($values['priority'])) {
- throw new InvalidTypeException('DoctrineListener', 'priority', 'integer', $values['priority']);
- }
- $this->priority = $values['priority'];
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\DiExtraBundle\Annotation;
-
-use JMS\DiExtraBundle\Exception\InvalidTypeException;
-
-/**
- * @Annotation
- * @Target("CLASS")
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-final class FormType
-{
- /** @var string */
- public $alias;
-
- public function __construct()
- {
- if (0 === func_num_args()) {
- return;
- }
- $values = func_get_arg(0);
-
- if (isset($values['value'])) {
- $values['alias'] = $values['value'];
- }
-
- if (isset($values['alias'])) {
- if (!is_string($values['alias'])) {
- throw new InvalidTypeException('FormType', 'alias', 'string', $values['alias']);
- }
-
- $this->alias = $values['alias'];
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Annotation;
-
-/**
- * @Annotation
- * @Target({"PROPERTY", "ANNOTATION"})
- */
-final class Inject extends Reference
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Annotation;
-
-use JMS\DiExtraBundle\Exception\InvalidTypeException;
-
-/**
- * @Annotation
- * @Target("METHOD")
- */
-final class InjectParams
-{
- /** @var array<JMS\DiExtraBundle\Annotation\Inject> */
- public $params = array();
-
- public function __construct()
- {
- if (0 === func_num_args()) {
- return;
- }
- $values = func_get_arg(0);
-
- if (isset($values['params'])) {
- $values['value'] = $values['params'];
- }
-
- if (isset($values['value'])) {
- if (!is_array($values['value'])) {
- throw new InvalidTypeException('InjectParams', 'value', 'array', $values['value']);
- }
-
- foreach ($values['value'] as $k => $v) {
- if (!$v instanceof Inject) {
- throw new InvalidTypeException('InjectParams', sprintf('value[%s]', $k), '@Inject', $v);
- }
-
- $this->params[$k] = $v;
- }
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Annotation;
-
-/**
- * @Annotation
- * @Target("METHOD")
- */
-final class LookupMethod extends Reference
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Annotation;
-
-use JMS\DiExtraBundle\Exception\InvalidTypeException;
-
-/**
- * @Annotation
- * @Target("METHOD")
- */
-final class Observe
-{
- /** @var string @Required */
- public $event;
-
- /** @var integer */
- public $priority = 0;
-
- public function __construct()
- {
- if (0 === func_num_args()) {
- return;
- }
- $values = func_get_arg(0);
-
- if (isset($values['event'])) {
- $values['value'] = $values['event'];
- }
-
- if (isset($values['value'])) {
- if (!is_string($values['value'])) {
- throw new InvalidTypeException('Observe', 'value', 'string', $values['value']);
- }
-
- $this->event = $values['value'];
- }
-
- if (isset($values['priority'])) {
- if (!is_numeric($values['priority'])) {
- throw new InvalidTypeException('Observe', 'priority', 'integer', $values['priority']);
- }
-
- $this->priority = $values['priority'];
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Annotation;
-
-use JMS\DiExtraBundle\Exception\InvalidTypeException;
-
-abstract class Reference
-{
- /** @var string */
- public $value;
-
- /** @var boolean */
- public $required;
-
- public final function __construct()
- {
- if (0 === func_num_args()) {
- return;
- }
- $values = func_get_arg(0);
-
- if (isset($values['value'])) {
- if (!is_string($values['value'])) {
- throw new InvalidTypeException('Inject', 'value', 'string', $values['value']);
- }
-
- $this->value = $values['value'];
- }
-
- if (isset($values['required'])) {
- if (!is_bool($values['required'])) {
- throw new InvalidTypeException('Inject', 'required', 'boolean', $values['required']);
- }
-
- $this->required = $values['required'];
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Annotation;
-
-use JMS\DiExtraBundle\Exception\InvalidTypeException;
-
-/**
- * @Annotation
- * @Target("CLASS")
- */
-final class Service
-{
- /** @var string */
- public $id;
-
- /** @var string */
- public $parent;
-
- /** @var boolean */
- public $public;
-
- /** @var string */
- public $scope;
-
- /** @var boolean */
- public $abstract;
-
- public function __construct()
- {
- if (0 === func_num_args()) {
- return;
- }
- $values = func_get_arg(0);
-
- if (isset($values['value'])) {
- if (!is_string($values['value'])) {
- throw new InvalidTypeException('Service', 'value', 'string', $values['value']);
- }
-
- $this->id = $values['value'];
- }
- if (isset($values['parent'])) {
- if (!is_string($values['parent'])) {
- throw new InvalidTypeException('Service', 'parent', 'string', $values['parent']);
- }
-
- $this->parent = $values['parent'];
- }
- if (isset($values['public'])) {
- if (!is_bool($values['public'])) {
- throw new InvalidTypeException('Service', 'public', 'boolean', $values['public']);
- }
-
- $this->public = $values['public'];
- }
- if (isset($values['scope'])) {
- if (!is_string($values['scope'])) {
- throw new InvalidTypeException('Service', 'scope', 'string', $values['scope']);
- }
-
- $this->scope = $values['scope'];
- }
- if (isset($values['abstract'])) {
- if (!is_bool($values['abstract'])) {
- throw new InvalidTypeException('Service', 'abstract', 'boolean', $values['abstract']);
- }
-
- $this->abstract = $values['abstract'];
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Annotation;
-
-use JMS\DiExtraBundle\Exception\InvalidArgumentException;
-use JMS\DiExtraBundle\Exception\InvalidTypeException;
-
-/**
- * @Annotation
- * @Target("CLASS")
- */
-final class Tag
-{
- /** @var string @Required */
- public $name;
-
- /** @var array */
- public $attributes = array();
-
- public function __construct()
- {
- if (0 === func_num_args()) {
- return;
- }
- $values = func_get_arg(0);
-
- if (!isset($values['value'])) {
- throw new InvalidArgumentException('A value must be given for annotation "@Tag".');
- }
- if (!is_string($values['value'])) {
- throw new InvalidTypeException('Tag', 'value', 'string', $values['value']);
- }
-
- $this->name = $values['value'];
-
- if (isset($values['attributes'])) {
- if (!is_array($values['attributes'])) {
- throw new InvalidTypeException('Tag', 'attributes', 'array', $values['attributes']);
- }
-
- $this->attributes = $values['attributes'];
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Annotation;
-
-use JMS\DiExtraBundle\Exception\InvalidTypeException;
-
-/**
- * @Annotation
- * @Target("CLASS")
- */
-final class Validator
-{
- /** @var string @Required */
- public $alias;
-
- public function __construct()
- {
- if (0 === func_num_args()) {
- return;
- }
- $values = func_get_arg(0);
-
- if (isset($values['alias'])) {
- $values['value'] = $values['alias'];
- }
-
- if (!isset($values['value'])) {
- throw new \InvalidArgumentException('A value must be given for @Validator annotations.');
- }
- if (!is_string($values['value'])) {
- throw new InvalidTypeException('Validator', 'value', 'string', $values['value']);
- }
- $this->alias = $values['value'];
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Config;
-
-use JMS\DiExtraBundle\Finder\PatternFinder;
-
-use Symfony\Component\Config\Resource\ResourceInterface;
-
-class FastDirectoriesResource implements ResourceInterface
-{
- private $finder;
-
- private $directories;
- private $filePattern;
- private $files = array();
-
- public function __construct(array $directories, $filePattern = null)
- {
- $this->finder = new PatternFinder('.*', '*.php');
- $this->finder->setRegexPattern(true);
-
- $this->directories = $directories;
- $this->filePattern = $filePattern ?: '*';
- }
-
- public function __toString()
- {
- return implode(', ', $this->directories);
- }
-
- public function getResource()
- {
- return $this->directories;
- }
-
- public function update()
- {
- $this->files = $this->getFiles();
- }
-
- public function isFresh($timestamp)
- {
- $files = $this->getFiles();
-
- if (array_diff($this->files, $files) || array_diff($files, $this->files)) {
- return false;
- }
-
- foreach ($files as $file) {
- if (filemtime($file) > $timestamp) {
- return false;
- }
- }
-
- return true;
- }
-
- private function getFiles()
- {
- return $this->finder->findFiles($this->directories);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Config;
-
-use JMS\DiExtraBundle\Finder\PatternFinder;
-use Symfony\Component\Config\Resource\ResourceInterface;
-
-class ServiceFilesResource implements ResourceInterface
-{
- private $files;
- private $dirs;
-
- public function __construct(array $files, array $dirs)
- {
- $this->files = $files;
- $this->dirs = $dirs;
- }
-
- public function isFresh($timestamp)
- {
- $finder = new PatternFinder('JMS\DiExtraBundle\Annotation');
- $files = $finder->findFiles($this->dirs);
-
- return !array_diff($files, $this->files) && !array_diff($this->files, $files);
- }
-
- public function __toString()
- {
- return implode(', ', $this->files);
- }
-
- public function getResource()
- {
- return array($this->files, $this->dirs);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\DependencyInjection\Compiler;
-
-use Symfony\Component\DependencyInjection\Alias;
-use JMS\DiExtraBundle\Exception\RuntimeException;
-use JMS\DiExtraBundle\Config\ServiceFilesResource;
-use Symfony\Component\Config\Resource\FileResource;
-use Symfony\Component\DependencyInjection\DefinitionDecorator;
-use Symfony\Component\DependencyInjection\Definition;
-use JMS\DiExtraBundle\Finder\PatternFinder;
-use Symfony\Component\HttpKernel\KernelInterface;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
-
-class AnnotationConfigurationPass implements CompilerPassInterface
-{
- private $kernel;
- private $finder;
-
- public function __construct(KernelInterface $kernel)
- {
- $this->kernel = $kernel;
- $this->finder = new PatternFinder('JMS\DiExtraBundle\Annotation');
- }
-
- public function process(ContainerBuilder $container)
- {
- $reader = $container->get('annotation_reader');
- $factory = $container->get('jms_di_extra.metadata.metadata_factory');
- $converter = $container->get('jms_di_extra.metadata.converter');
-
- $directories = $this->getScanDirectories($container);
- if (!$directories) {
- $container->getCompiler()->addLogMessage('No directories configured for AnnotationConfigurationPass.');
- return;
- }
-
- $files = $this->finder->findFiles($directories);
- $container->addResource(new ServiceFilesResource($files, $directories));
- foreach ($files as $file) {
- $container->addResource(new FileResource($file));
- require_once $file;
-
- $className = $this->getClassName($file);
-
- if (null === $metadata = $factory->getMetadataForClass($className)) {
- continue;
- }
- if (null === $metadata->getOutsideClassMetadata()->id) {
- continue;
- }
-
- foreach ($converter->convert($metadata) as $id => $definition) {
- $container->setDefinition($id, $definition);
- }
- }
- }
-
- private function getScanDirectories(ContainerBuilder $c)
- {
- $bundles = $this->kernel->getBundles();
- $scanBundles = $c->getParameter('jms_di_extra.bundles');
- $scanAllBundles = $c->getParameter('jms_di_extra.all_bundles');
-
- $directories = $c->getParameter('jms_di_extra.directories');
- foreach ($bundles as $name => $bundle) {
- if (!$scanAllBundles && !in_array($name, $scanBundles, true)) {
- continue;
- }
-
- if ('JMSDiExtraBundle' === $name) {
- continue;
- }
-
- $directories[] = $bundle->getPath();
- }
-
- return $directories;
- }
-
- /**
- * Only supports one namespaced class per file
- *
- * @throws \RuntimeException if the class name cannot be extracted
- * @param string $filename
- * @return string the fully qualified class name
- */
- private function getClassName($filename)
- {
- $src = file_get_contents($filename);
-
- if (!preg_match('/\bnamespace\s+([^;]+);/s', $src, $match)) {
- throw new RuntimeException(sprintf('Namespace could not be determined for file "%s".', $filename));
- }
- $namespace = $match[1];
-
- if (!preg_match('/\bclass\s+([^\s]+)\s+(?:extends|implements|{)/s', $src, $match)) {
- throw new RuntimeException(sprintf('Could not extract class name from file "%s".', $filename));
- }
-
- return $namespace.'\\'.$match[1];
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\DependencyInjection\Compiler;
-
-use Symfony\Component\DependencyInjection\Alias;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
-
-/**
- * Integrates the bundle with external code.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class IntegrationPass implements CompilerPassInterface
-{
- public function process(ContainerBuilder $container)
- {
- // replace Symfony2's default controller resolver
- $container->setAlias('controller_resolver', new Alias('jms_di_extra.controller_resolver', false));
-
- // replace SensioFrameworkExtraBundle's default template listener
- if ($container->hasDefinition('sensio_framework_extra.view.listener')) {
- $def = $container->getDefinition('sensio_framework_extra.view.listener');
-
- // only overwrite if it has the default class otherwise the user has to do the integration manually
- if ('%sensio_framework_extra.view.listener.class%' === $def->getClass()) {
- $def->setClass('%jms_di_extra.template_listener.class%');
- }
- }
-
- if ($container->hasDefinition('sensio_framework_extra.controller.listener')) {
- $def = $container->getDefinition('sensio_framework_extra.controller.listener');
-
- if ('%sensio_framework_extra.controller.listener.class%' === $def->getClass()) {
- $def->setClass('%jms_di_extra.controller_listener.class%');
- }
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\DependencyInjection\Compiler;
-
-use JMS\DiExtraBundle\Config\FastDirectoriesResource;
-
-use Symfony\Component\Config\Resource\DirectoryResource;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
-
-class ResourceOptimizationPass implements CompilerPassInterface
-{
- public function process(ContainerBuilder $container)
- {
- $resources = $directories = array();
-
- $ref = new \ReflectionProperty('Symfony\Component\Config\Resource\DirectoryResource', 'pattern');
- $ref->setAccessible(true);
-
- foreach ($container->getResources() as $resource) {
- if ($resource instanceof DirectoryResource) {
- if (null === $pattern = $ref->getValue($resource)) {
- $pattern = '*';
- }
-
- $directories[$pattern][] = $resource->getResource();
-
- continue;
- }
-
- $resources[] = $resource;
- }
-
- $sortFunc = function($a, $b) {
- return strlen($a) - strlen($b);
- };
-
- foreach ($directories as $pattern => $pDirectories) {
- $newResources = array();
-
- usort($pDirectories, $sortFunc);
- foreach ($pDirectories as $a) {
- foreach ($newResources as $b) {
- if (0 === strpos($a, $b)) {
- continue 2;
- }
- }
-
- $newResources[] = $a;
- }
-
- $directories[$pattern] = $newResources;
- }
-
- foreach ($directories as $pattern => $pDirectories) {
- $newResource = new FastDirectoriesResource($pDirectories, $pattern);
- $newResource->update();
- $resources[] = $newResource;
- }
-
- $ref = new \ReflectionProperty('Symfony\Component\DependencyInjection\ContainerBuilder', 'resources');
- $ref->setAccessible(true);
- $ref->setValue($container, $resources);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\DependencyInjection;
-
-use Symfony\Component\Config\Definition\Builder\TreeBuilder;
-use Symfony\Component\Config\Definition\ConfigurationInterface;
-
-class Configuration implements ConfigurationInterface
-{
- public function getConfigTreeBuilder()
- {
- $tb = new TreeBuilder();
-
- $tb
- ->root('jms_di_extra', 'array')
- ->children()
- ->arrayNode('locations')
- ->addDefaultsIfNotSet()
- ->children()
- ->booleanNode('all_bundles')->defaultFalse()->end()
- ->arrayNode('bundles')
- ->beforeNormalization()
- ->ifString()
- ->then(function($v) {
- return preg_split('/\s*,\s*/', $v);
- })
- ->end()
- ->prototype('scalar')->end()
- ->end()
- ->arrayNode('directories')
- ->beforeNormalization()
- ->ifString()
- ->then(function($v) {
- return preg_split('/\s*,\s*/', $v);
- })
- ->end()
- ->prototype('scalar')->end()
- ->end()
- ->end()
- ->end()
- ->scalarNode('cache_dir')->defaultValue('%kernel.cache_dir%/diextra')->end()
- ->arrayNode('metadata')
- ->addDefaultsIfNotSet()
- ->children()
- ->scalarNode('cache')->defaultValue('file')->cannotBeEmpty()->end()
- ->end()
- ->end()
- ->end()
- ->end();
-
- return $tb;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\DependencyInjection;
-
-use JMS\DiExtraBundle\Exception\RuntimeException;
-use Symfony\Component\DependencyInjection\Alias;
-use Symfony\Component\Config\FileLocator;
-use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
-use Symfony\Component\Config\Definition\Processor;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\HttpKernel\DependencyInjection\Extension;
-
-class JMSDiExtraExtension extends Extension
-{
- public function load(array $configs, ContainerBuilder $container)
- {
- $config = $this->mergeConfigs($configs);
-
- $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
- $loader->load('services.xml');
-
- $container->setParameter('jms_di_extra.all_bundles', $config['locations']['all_bundles']);
- $container->setParameter('jms_di_extra.bundles', $config['locations']['bundles']);
- $container->setParameter('jms_di_extra.directories', $config['locations']['directories']);
- $container->setParameter('jms_di_extra.cache_dir', $config['cache_dir']);
-
- $this->configureMetadata($config['metadata'], $container, $config['cache_dir'].'/metadata');
-
- $this->addClassesToCompile(array(
- 'JMS\\DiExtraBundle\\HttpKernel\ControllerResolver',
- ));
- }
-
- private function configureMetadata(array $config, $container, $cacheDir)
- {
- if ('none' === $config['cache']) {
- $container->removeAlias('jms_di_extra.metadata.cache');
- return;
- }
-
- if ('file' === $config['cache']) {
- $cacheDir = $container->getParameterBag()->resolveValue($cacheDir);
- if (!file_exists($cacheDir)) {
- if (false === @mkdir($cacheDir, 0777, true)) {
- throw new RuntimeException(sprintf('The cache dir "%s" could not be created.', $cacheDir));
- }
- }
- if (!is_writable($cacheDir)) {
- throw new RuntimeException(sprintf('The cache dir "%s" is not writable.', $cacheDir));
- }
-
- $container
- ->getDefinition('jms_di_extra.metadata.cache.file_cache')
- ->replaceArgument(0, $cacheDir)
- ;
- } else {
- $container->setAlias('jms_di_extra.metadata.cache', new Alias($config['cache'], false));
- }
- }
-
- private function mergeConfigs(array $configs)
- {
- $processor = new Processor();
- $configuration = new Configuration();
-
- return $processor->process($configuration->getConfigTreeBuilder()->buildTree(), $configs);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\DependencyInjection;
-
-interface LookupMethodClassInterface
-{
- function __jmsDiExtra_getOriginalClassName();
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\EventListener;
-
-use Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener as BaseControllerListener;
-use CG\Core\ClassUtils;
-use Doctrine\Common\Annotations\Reader;
-use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface;
-
-/**
- * The ControllerListener class parses annotation blocks located in
- * controller classes.
- *
- * @author Fabien Potencier <fabien@symfony.com>
- */
-class ControllerListener extends BaseControllerListener
-{
- /**
- * Modifies the Request object to apply configuration information found in
- * controllers annotations like the template to render or HTTP caching
- * configuration.
- *
- * @param FilterControllerEvent $event A FilterControllerEvent instance
- */
- public function onKernelController(FilterControllerEvent $event)
- {
- if (!is_array($controller = $event->getController())) {
- return;
- }
-
- $object = new \ReflectionClass(ClassUtils::getUserClass(get_class($controller[0])));
- $method = $object->getMethod($controller[1]);
-
- $request = $event->getRequest();
- foreach ($this->reader->getMethodAnnotations($method) as $configuration) {
- if ($configuration instanceof ConfigurationInterface) {
- $request->attributes->set('_'.$configuration->getAliasName(), $configuration);
- }
- }
- }
-}
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\EventListener;
-
-use CG\Core\ClassUtils;
-use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
-use Symfony\Component\HttpFoundation\Request;
-use JMS\DiExtraBundle\DependencyInjection\LookupMethodClassInterface;
-use Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener as FrameworkExtraTemplateListener;
-
-class TemplateListener extends FrameworkExtraTemplateListener
-{
- protected function guessTemplateName($controller, Request $request, $engine = 'twig')
- {
- $controllerClass = get_class($controller[0]);
- $userClass = ClassUtils::getUserClass($controllerClass);
-
- if ($controllerClass === $userClass) {
- return parent::guessTemplateName($controller, $request, $engine);
- }
-
- if (!preg_match('/Controller\\\(.+)Controller$/', $userClass, $matchController)) {
- throw new \InvalidArgumentException(sprintf('The "%s" class does not look like a controller class (it must be in a "Controller" sub-namespace and the class name must end with "Controller")', $userClass));
- }
-
- if (!preg_match('/^(.+)Action$/', $controller[1], $matchAction)) {
- throw new \InvalidArgumentException(sprintf('The "%s" method does not look like an action method (it does not end with Action)', $controller[1]));
- }
-
- $bundle = $this->getBundleForClass($userClass);
-
- return new TemplateReference($bundle->getName(), $matchController[1], $matchAction[1], $request->getRequestFormat(), $engine);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Exception;
-
-/**
- * Base exception for the DiExtraBundle.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface Exception
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Exception;
-
-/**
- * InvalidArgumentException for the DiExtraBundle.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class InvalidArgumentException extends \InvalidArgumentException implements Exception
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Exception;
-
-class InvalidTypeException extends InvalidArgumentException
-{
- public function __construct($annotName, $attrName, $expected, $actual)
- {
- $msg = sprintf('The attribute "%s" on annotation "@%s" is expected to be of type %s, but got %s.', $attrName, $annotName, $expected, gettype($actual));
-
- parent::__construct($msg);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Exception;
-
-/**
- * RuntimeException for the DiExtraBundle.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class RuntimeException extends \RuntimeException implements Exception
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Finder;
-
-use JMS\DiExtraBundle\Exception\RuntimeException;
-use Symfony\Component\Finder\Finder;
-use Symfony\Component\Process\ExecutableFinder;
-
-class PatternFinder
-{
- const METHOD_GREP = 1;
- const METHOD_FINDSTR = 2;
- const METHOD_FINDER = 3;
-
- private static $method;
- private static $grepPath;
-
- private $pattern;
- private $filePattern;
- private $recursive = true;
- private $regexPattern = false;
-
- public function __construct($pattern, $filePattern = '*.php')
- {
- if (null === self::$method) {
- self::determineMethod();
- }
-
- $this->pattern = $pattern;
- $this->filePattern = $filePattern;
- }
-
- public function setRecursive($bool)
- {
- $this->recursive = (Boolean) $bool;
- }
-
- public function setRegexPattern($bool)
- {
- $this->regexPattern = (Boolean) $bool;
- }
-
- public function findFiles(array $dirs)
- {
- // check for grep availability
- if (self::METHOD_GREP === self::$method) {
- return $this->findUsingGrep($dirs);
- }
-
- // use FINDSTR on Windows
- if (self::METHOD_FINDSTR === self::$method) {
- return $this->findUsingFindstr($dirs);
- }
-
- // this should really be avoided at all costs since it is damn slow
- return $this->findUsingFinder($dirs);
- }
-
- private function findUsingFindstr(array $dirs)
- {
- $cmd = 'FINDSTR /M /S /P';
-
- if (!$this->recursive) {
- $cmd .= ' /L';
- }
-
- $cmd .= ' /D:'.escapeshellarg(implode(';', $dirs));
- $cmd .= ' '.escapeshellarg($this->pattern);
- $cmd .= ' '.$this->filePattern;
-
- exec($cmd, $lines, $exitCode);
-
- if (1 === $exitCode) {
- return array();
- }
-
- if (0 !== $exitCode) {
- throw new RuntimeException(sprintf('Command "%s" exited with non-successful status code. "%d".', $cmd, $exitCode));
- }
-
- // Looks like FINDSTR has different versions with different output formats.
- //
- // Supported format #1:
- // C:\matched\dir1:
- // Relative\Path\To\File1.php
- // Relative\Path\To\File2.php
- // C:\matched\dir2:
- // Relative\Path\To\File3.php
- // Relative\Path\To\File4.php
- //
- // Supported format #2:
- // C:\matched\dir1\Relative\Path\To\File1.php
- // C:\matched\dir1\Relative\Path\To\File2.php
- // C:\matched\dir2\Relative\Path\To\File3.php
- // C:\matched\dir2\Relative\Path\To\File4.php
-
- $files = array();
- $currentDir = '';
- foreach ($lines as $line) {
- if (':' === substr($line, -1)) {
- $currentDir = trim($line, ' :/').'/';
- continue;
- }
-
- $files[] = $currentDir.$line;
- }
-
- return $files;
- }
-
- private function findUsingGrep(array $dirs)
- {
- $cmd = self::$grepPath;
-
- if (!$this->regexPattern) {
- $cmd .= ' --fixed-strings';
- } else {
- $cmd .= ' --extended-regexp';
- }
-
- if ($this->recursive) {
- $cmd .= ' --directories=recurse';
- } else {
- $cmd .= ' --directories=skip';
- }
-
- $cmd .= ' --devices=skip --files-with-matches --with-filename --max-count=1 --color=never --include='.$this->filePattern;
- $cmd .= ' '.escapeshellarg($this->pattern);
-
- foreach ($dirs as $dir) {
- $cmd .= ' '.escapeshellarg($dir);
- }
- exec($cmd, $files, $exitCode);
-
- if (1 === $exitCode) {
- return array();
- }
-
- if (0 !== $exitCode) {
- throw new RuntimeException(sprintf('Command "%s" exited with non-successful status code "%d".', $cmd, $exitCode));
- }
-
- return $files;
- }
-
- private function findUsingFinder(array $dirs)
- {
- $finder = new Finder();
- $pattern = $this->pattern;
- $regex = $this->regexPattern;
- $finder
- ->files()
- ->name($this->filePattern)
- ->in($dirs)
- ->ignoreVCS(true)
- ->filter(function($file) use ($pattern, $regex) {
- if (!$regex) {
- return false !== strpos(file_get_contents($file->getPathName()), $pattern);
- }
-
- return 0 < preg_match('#'.$pattern.'#', file_get_contents($file->getPathName()));
- })
- ;
-
- if (!$this->recursive) {
- $finder->depth('<= 0');
- }
-
- return array_keys(iterator_to_array($finder));
- }
-
- private static function determineMethod()
- {
- $finder = new ExecutableFinder();
- $isWindows = 0 === stripos(PHP_OS, 'win');
-
- if (!$isWindows && self::$grepPath = $finder->find('grep')) {
- self::$method = self::METHOD_GREP;
- } else if ($isWindows) {
- self::$method = self::METHOD_FINDSTR;
- } else {
- self::$method = self::METHOD_FINDER;
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Generator;
-
-use CG\Generator\Writer;
-use Symfony\Component\DependencyInjection\Parameter;
-use Symfony\Component\DependencyInjection\Reference;
-use Symfony\Component\DependencyInjection\Definition;
-
-/**
- * Generates lightweight code for injecting a single definition.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class DefinitionInjectorGenerator
-{
- private $nameGenerator;
- private $inlinedDefinitions;
-
- public function __construct()
- {
- $this->nameGenerator = new NameGenerator();
- $this->inlinedDefinitions = new \SplObjectStorage();
- }
-
- public function generate(Definition $def)
- {
- $writer = new Writer();
-
- $writer
- ->writeln('<?php')
- ->writeln('/**')
- ->writeln(' * This code has been auto-generated by the JMSDiExtraBundle.')
- ->writeln(' *')
- ->writeln(' * Manual changes to it will be lost.')
- ->writeln(' */')
- ->writeln('return function($container) {')
- ->indent()
- ;
-
- if ($file = $def->getFile()) {
- $writer->writeln('require_once '.var_export($file, true).';');
-
- require_once $file;
- }
-
- foreach ($this->getInlineDefinitions($def) as $inlineDef) {
- $name = $this->nameGenerator->nextName();
- $this->inlinedDefinitions[$inlineDef] = $name;
-
- $writer->writeln('$'.$name.' = new \\'.$inlineDef->getClass().$this->dumpArguments($inlineDef->getArguments()).';');
- }
-
- $writer->writeln('$instance = new \\'.$def->getClass().$this->dumpArguments($def->getArguments()).';');
-
- foreach ($def->getMethodCalls() as $call) {
- list($method, $arguments) = $call;
- $writer->writeln('$instance->'.$method.$this->dumpArguments($arguments).';');
- }
-
- $ref = new \ReflectionClass($def->getClass());
- foreach ($def->getProperties() as $property => $value) {
- $refProperty = $this->getReflectionProperty($ref, $property);
-
- if ($refProperty->isPublic()) {
- $writer->writeln('$instance->'.$property.' = '.$this->dumpValue($value).';');
- } else {
- $writer
- ->writeln(sprintf("\$refProperty = new \ReflectionProperty(%s, %s);", var_export($refProperty->getDeclaringClass()->getName(), true), var_export($property, true)))
- ->writeln('$refProperty->setAccessible(true);')
- ->writeln('$refProperty->setValue($instance, '.$this->dumpValue($value).');')
- ;
- }
- }
-
- if (method_exists($def, 'getInitMethod') && $def->getInitMethod()) {
- $writer->writeln('$instance->'.$def->getInitMethod().'();');
- }
-
- $writer
- ->writeln('return $instance;')
- ->outdent()
- ->writeln('};')
- ;
-
- return $writer->getContent();
- }
-
- private function getReflectionProperty($ref, $property)
- {
- $origClass = $ref->getName();
- while (!$ref->hasProperty($property) && false !== $ref = $ref->getParentClass());
-
- if (!$ref->hasProperty($property)) {
- throw new \RuntimeException(sprintf('Could not find property "%s" anywhere in class "%s" or one of its parents.', $property, $origName));
- }
-
- return $ref->getProperty($property);
- }
-
- private function getInlineDefinitions(Definition $def)
- {
- $defs = new \SplObjectStorage();
- $this->getDefinitionsFromArray($def->getArguments(), $defs);
- $this->getDefinitionsFromArray($def->getMethodCalls(), $defs);
- $this->getDefinitionsFromArray($def->getProperties(), $defs);
-
- return $defs;
- }
-
- private function getDefinitionsFromArray(array $a, \SplObjectStorage $defs)
- {
- foreach ($a as $k => $v) {
- if ($v instanceof Definition) {
- $defs->attach($v);
- } else if (is_array($v)) {
- $this->getDefinitionsFromArray($v, $defs);
- }
- }
- }
-
- private function dumpArguments(array $arguments)
- {
- $code = '(';
-
- $first = true;
- foreach ($arguments as $argument) {
- if (!$first) {
- $code .= ', ';
- }
- $first = false;
-
- $code .= $this->dumpValue($argument);
- }
-
- return $code.')';
- }
-
- private function dumpValue($value)
- {
- if (is_array($value)) {
- $code = 'array(';
-
- $first = true;
- foreach ($value as $k => $v) {
- if (!$first) {
- $code .= ', ';
- }
- $first = false;
-
- $code .= sprintf('%s => %s', var_export($k, true), $this->dumpValue($v));
- }
-
- return $code.')';
- } else if ($value instanceof Reference) {
- if ('service_container' === (string) $value) {
- return '$container';
- }
-
- return sprintf('$container->get(%s, %d)', var_export((string) $value, true), $value->getInvalidBehavior());
- } else if ($value instanceof Parameter) {
- return sprintf('$container->getParameter(%s)', var_export((string) $value, true));
- } else if (is_scalar($value) || null === $value) {
- // we do not support embedded parameters
- if (is_string($value) && '%' === $value[0] && '%' !== $value[1]) {
- return sprintf('$container->getParameter(%s)', var_export(substr($value, 1, -1), true));
- }
-
- return var_export($value, true);
- } else if ($value instanceof Definition) {
- return sprintf('$%s', $this->inlinedDefinitions[$value]);
- }
-
- throw new \RuntimeException(sprintf('Found unsupported value of type %s during definition injector generation: "%s"', gettype($value), json_encode($value)));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Generator;
-
-use Metadata\ClassHierarchyMetadata;
-use CG\Generator\PhpParameter;
-use CG\Generator\PhpMethod;
-use CG\Generator\PhpProperty;
-use CG\Generator\PhpClass;
-use CG\Proxy\GeneratorInterface;
-use Symfony\Component\DependencyInjection\Parameter;
-use Symfony\Component\DependencyInjection\Reference;
-
-class LookupMethodClassGenerator implements GeneratorInterface
-{
- const PREFIX = '__jmsDiExtra_';
-
- private $metadata;
- private $requiredFile;
-
- public function __construct(ClassHierarchyMetadata $metadata)
- {
- $this->metadata = $metadata;
- }
-
- public function setRequiredFile($file)
- {
- $this->requiredFile = $file;
- }
-
- public function generate(\ReflectionClass $class, PhpClass $genClass)
- {
- if (!empty($this->requiredFile)) {
- $genClass->addRequiredFile($this->requiredFile);
- }
-
- $genClass->setProperty(PhpProperty::create()
- ->setName(self::PREFIX.'container')
- ->setVisibility('private')
- );
-
- $genClass->setMethod(PhpMethod::create()
- ->setName(self::PREFIX.'setContainer')
- ->addParameter(PhpParameter::create()
- ->setName('container')
- ->setType('Symfony\Component\DependencyInjection\ContainerInterface')
- )
- ->setBody('$this->'.self::PREFIX.'container = $container;')
- );
-
- $genClass->addInterfaceName('JMS\DiExtraBundle\DependencyInjection\LookupMethodClassInterface');
- $genClass->setMethod(PhpMethod::create()
- ->setName(self::PREFIX.'getOriginalClassName')
- ->setFinal(true)
- ->setBody('return '.var_export($class->name, true).';')
- );
-
- foreach ($this->getLookupMethods() as $name => $value) {
- $genClass->setMethod(PhpMethod::fromReflection($class->getMethod($name))
- ->setAbstract(false)
- ->setBody('return '.$this->dumpValue($value).';')
- ->setDocblock(null)
- );
- }
- }
-
- private function getLookupMethods()
- {
- $outerClass = $this->metadata->getOutsideClassMetadata()->reflection;
- $lookupMethods = array();
- foreach ($this->metadata->classMetadata as $classMetadata) {
- if (!$classMetadata->lookupMethods) {
- continue;
- }
-
- foreach ($classMetadata->lookupMethods as $name => $value) {
- // check if method has been overridden
- if ($outerClass->getMethod($name)->class !== $classMetadata->reflection->name) {
- continue;
- }
-
- $lookupMethods[$name] = $value;
- }
- }
-
- return $lookupMethods;
- }
-
- private function dumpValue($value)
- {
- if ($value instanceof Parameter) {
- return '$this->'.self::PREFIX.'container->getParameter('.var_export((string) $value, true).')';
- } else if ($value instanceof Reference) {
- return '$this->'.self::PREFIX.'container->get('.var_export((string) $value, true).', '.var_export($value->getInvalidBehavior(), true).')';
- } else if (is_string($value) && '%' === $value[0]) {
- return '$this->'.self::PREFIX.'container->getParameter('.var_export(substr($value, 1, -1), true).')';
- } else if (is_array($value) || is_scalar($value) || null === $value) {
- return var_export($value, true);
- }
-
- throw new \RuntimeException(sprintf('Invalid value for lookup method: %s', json_encode($value)));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Generator;
-
-class NameGenerator
-{
- private $count = 0;
- private $firstChars = 'abcdefghijklmnopqrstuvwxyz';
- private $firstCharsLength = 26;
- private $nonFirstChars = 'abcdefghijklmnopqrstuvwxyz0123456789_';
- private $nonFirstCharsLength = 37;
- private $reservedNames = array();
-
- public function addReservedName($name)
- {
- $this->reservedNames[$name] = true;
- }
-
- public function setFirstChars($chars)
- {
- $this->firstChars = $chars;
- $this->firstCharsLength = strlen($chars);
- }
-
- public function setNonFirstChars($chars)
- {
- $this->nonFirstChars = $chars;
- $this->nonFirstCharsLength = strlen($chars);
- }
-
- public function reset()
- {
- $this->count = 0;
- }
-
- public function nextName()
- {
- while (true) {
- $name = '';
- $i = $this->count;
-
- if ('' === $name) {
- $name .= $this->firstChars[$i%$this->firstCharsLength];
- $i = intval($i/$this->firstCharsLength);
- }
-
- while ($i > 0) {
- $i -= 1;
- $name .= $this->nonFirstChars[$i%$this->nonFirstCharsLength];
- $i = intval($i/$this->nonFirstCharsLength);
- }
-
- $this->count += 1;
-
- // check that the name is not reserved
- if (isset($this->reservedNames[$name])) {
- continue;
- }
-
- return $name;
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\HttpKernel;
-
-use Metadata\ClassHierarchyMetadata;
-use JMS\DiExtraBundle\Metadata\ClassMetadata;
-use CG\Core\DefaultNamingStrategy;
-use CG\Proxy\Enhancer;
-use JMS\AopBundle\DependencyInjection\Compiler\PointcutMatchingPass;
-use JMS\DiExtraBundle\Generator\DefinitionInjectorGenerator;
-use JMS\DiExtraBundle\Generator\LookupMethodClassGenerator;
-use JMS\DiExtraBundle\DependencyInjection\Dumper\PhpDumper;
-use Metadata\MetadataFactory;
-use Symfony\Component\DependencyInjection\Compiler\InlineServiceDefinitionsPass;
-use Symfony\Component\DependencyInjection\ContainerAwareInterface;
-use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
-use Symfony\Component\DependencyInjection\Parameter;
-use Symfony\Component\DependencyInjection\Reference;
-use Symfony\Component\DependencyInjection\Definition;
-use Symfony\Component\Config\Resource\FileResource;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\Config\ConfigCache;
-use Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver as BaseControllerResolver;
-
-class ControllerResolver extends BaseControllerResolver
-{
- protected function createController($controller)
- {
- if (false === $pos = strpos($controller, '::')) {
- $count = substr_count($controller, ':');
- if (2 == $count) {
- // controller in the a:b:c notation then
- $controller = $this->parser->parse($controller);
- $pos = strpos($controller, '::');
- } elseif (1 == $count) {
- // controller in the service:method notation
- list($service, $method) = explode(':', $controller);
-
- return array($this->container->get($service), $method);
- } else {
- throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller));
- }
- }
-
- $class = substr($controller, 0, $pos);
- $method = substr($controller, $pos+2);
-
- if (!class_exists($class)) {
- throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
- }
-
- $filename = $this->container->getParameter('jms_di_extra.cache_dir').'/controller_injectors/'.str_replace('\\', '', $class).'.php';
- $cache = new ConfigCache($filename, $this->container->getParameter('kernel.debug'));
-
- if (!$cache->isFresh()) {
- $metadata = $this->container->get('jms_di_extra.metadata.metadata_factory')->getMetadataForClass($class);
- if (null === $metadata) {
- $metadata = new ClassHierarchyMetadata();
- $metadata->addClassMetadata(new ClassMetadata($class));
- }
-
- $this->prepareContainer($cache, $filename, $metadata);
- }
-
- $inject = require $filename;
- $controller = $inject($this->container);
-
- if ($controller instanceof ContainerAwareInterface) {
- $controller->setContainer($this->container);
- }
-
- return array($controller, $method);
- }
-
- private function prepareContainer($cache, $containerFilename, $metadata)
- {
- $container = new ContainerBuilder();
- $container->setParameter('jms_aop.cache_dir', $this->container->getParameter('jms_di_extra.cache_dir'));
- $def = $container
- ->register('jms_aop.interceptor_loader', 'JMS\AopBundle\Aop\InterceptorLoader')
- ->addArgument(new Reference('service_container'))
- ->setPublic(false)
- ;
-
- // add resources
- $ref = $metadata->getOutsideClassMetadata()->reflection;
- while ($ref && false !== $filename = $ref->getFilename()) {
- $container->addResource(new FileResource($filename));
- $ref = $ref->getParentClass();
- }
-
- // add definitions
- $definitions = $this->container->get('jms_di_extra.metadata.converter')->convert($metadata);
- $serviceIds = $parameters = array();
-
- $controllerDef = array_pop($definitions);
- $container->setDefinition('controller', $controllerDef);
-
- foreach ($definitions as $id => $def) {
- $container->setDefinition($id, $def);
- }
-
- $this->generateLookupMethods($controllerDef, $metadata);
-
- $config = $container->getCompilerPassConfig();
- $config->setOptimizationPasses(array());
- $config->setRemovingPasses(array());
- $config->addPass(new ResolveDefinitionTemplatesPass());
- $config->addPass(new PointcutMatchingPass($this->container->get('jms_aop.pointcut_container')->getPointcuts()));
- $config->addPass(new InlineServiceDefinitionsPass());
- $container->compile();
-
- if (!file_exists($dir = dirname($containerFilename))) {
- if (false === @mkdir($dir, 0777, true)) {
- throw new \RuntimeException(sprintf('Could not create directory "%s".', $dir));
- }
- }
-
- static $generator;
- if (null === $generator) {
- $generator = new DefinitionInjectorGenerator();
- }
-
- $cache->write($generator->generate($container->getDefinition('controller')), $container->getResources());
- }
-
- private function generateLookupMethods($def, $metadata)
- {
- $found = false;
- foreach ($metadata->classMetadata as $cMetadata) {
- if (!empty($cMetadata->lookupMethods)) {
- $found = true;
- break;
- }
- }
-
- if (!$found) {
- return;
- }
-
- $generator = new LookupMethodClassGenerator($metadata);
- $outerClass = $metadata->getOutsideClassMetadata()->reflection;
-
- if ($file = $def->getFile()) {
- $generator->setRequiredFile($file);
- }
-
- $enhancer = new Enhancer(
- $outerClass,
- array(),
- array(
- $generator,
- )
- );
-
- $filename = $this->container->getParameter('jms_di_extra.cache_dir').'/lookup_method_classes/'.str_replace('\\', '-', $outerClass->name).'.php';
- $enhancer->writeClass($filename);
-
- $def->setFile($filename);
- $def->setClass($enhancer->getClassName($outerClass));
- $def->addMethodCall('__jmsDiExtra_setContainer', array(new Reference('service_container')));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle;
-
-use JMS\DiExtraBundle\DependencyInjection\Compiler\ResourceOptimizationPass;
-use JMS\DiExtraBundle\DependencyInjection\Compiler\IntegrationPass;
-use Symfony\Component\HttpKernel\KernelInterface;
-use Symfony\Component\DependencyInjection\Compiler\PassConfig;
-use JMS\DiExtraBundle\DependencyInjection\Compiler\AnnotationConfigurationPass;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\HttpKernel\Bundle\Bundle;
-
-class JMSDiExtraBundle extends Bundle
-{
- const VERSION = '1.0.1';
-
- private $kernel;
-
- public function __construct(KernelInterface $kernel)
- {
- $this->kernel = $kernel;
- }
-
- public function build(ContainerBuilder $container)
- {
- $config = $container->getCompiler()->getPassConfig();
- $passes = $config->getBeforeOptimizationPasses();
- array_unshift($passes, new AnnotationConfigurationPass($this->kernel));
- $config->setBeforeOptimizationPasses($passes);
-
- $container->addCompilerPass(new IntegrationPass());
- $container->addCompilerPass(new ResourceOptimizationPass(), PassConfig::TYPE_AFTER_REMOVING);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Metadata;
-
-use Metadata\ClassMetadata as BaseClassMetadata;
-
-class ClassMetadata extends BaseClassMetadata
-{
- public $id;
- public $parent;
- public $scope;
- public $public;
- public $abstract;
- public $tags = array();
- public $arguments;
- public $methodCalls = array();
- public $lookupMethods = array();
- public $properties = array();
- public $initMethod;
-
- public function serialize()
- {
- return serialize(array(
- $this->id,
- $this->parent,
- $this->scope,
- $this->public,
- $this->abstract,
- $this->tags,
- $this->arguments,
- $this->methodCalls,
- $this->lookupMethods,
- $this->properties,
- $this->initMethod,
- parent::serialize(),
- ));
- }
-
- public function unserialize($str)
- {
- list(
- $this->id,
- $this->parent,
- $this->scope,
- $this->public,
- $this->abstract,
- $this->tags,
- $this->arguments,
- $this->methodCalls,
- $this->lookupMethods,
- $this->properties,
- $this->initMethod,
- $parentStr
- ) = unserialize($str);
-
- parent::unserialize($parentStr);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Metadata\Driver;
-
-use JMS\DiExtraBundle\Annotation\AfterSetup;
-
-use JMS\DiExtraBundle\Annotation\FormType;
-
-use JMS\DiExtraBundle\Annotation\DoctrineListener;
-use JMS\DiExtraBundle\Annotation\Reference as AnnotReference;
-use JMS\DiExtraBundle\Annotation\LookupMethod;
-use JMS\DiExtraBundle\Annotation\Validator;
-use JMS\DiExtraBundle\Annotation\InjectParams;
-use JMS\DiExtraBundle\Exception\InvalidTypeException;
-use JMS\DiExtraBundle\Annotation\Observe;
-use Doctrine\Common\Annotations\Reader;
-use JMS\DiExtraBundle\Annotation\Inject;
-use JMS\DiExtraBundle\Annotation\Service;
-use JMS\DiExtraBundle\Annotation\Tag;
-use JMS\DiExtraBundle\Metadata\ClassMetadata;
-use Metadata\Driver\DriverInterface;
-use Symfony\Component\DependencyInjection\ContainerInterface;
-use Symfony\Component\DependencyInjection\Reference;
-
-class AnnotationDriver implements DriverInterface
-{
- private $reader;
-
- public function __construct(Reader $reader)
- {
- $this->reader = $reader;
- }
-
- public function loadMetadataForClass(\ReflectionClass $class)
- {
- $metadata = new ClassMetadata($className = $class->getName());
- if (false !== $filename = $class->getFilename()) {
- $metadata->fileResources[] = $filename;
- }
-
- // this is a bit of a hack, but avoids any timeout issues when a class
- // is moved into one of the compiled classes files, and Doctrine
- // Common 2.1 is used.
- if (false !== strpos($filename, '/classes.php')
- || false !== strpos($filename, '/bootstrap.php')) {
- return null;
- }
-
- foreach ($this->reader->getClassAnnotations($class) as $annot) {
- if ($annot instanceof Service) {
- if (null === $annot->id) {
- $metadata->id = $this->generateId($className);
- } else {
- $metadata->id = $annot->id;
- }
-
- $metadata->parent = $annot->parent;
- $metadata->public = $annot->public;
- $metadata->scope = $annot->scope;
- $metadata->abstract = $annot->abstract;
- } else if ($annot instanceof Tag) {
- $metadata->tags[$annot->name][] = $annot->attributes;
- } else if ($annot instanceof Validator) {
- // automatically register as service if not done explicitly
- if (null === $metadata->id) {
- $metadata->id = $this->generateId($className);
- }
-
- $metadata->tags['validator.constraint_validator'][] = array(
- 'alias' => $annot->alias,
- );
- } else if ($annot instanceof DoctrineListener) {
- if (null === $metadata->id) {
- $metadata->id = $this->generateId($className);
- }
-
- foreach ($annot->events as $event) {
- $metadata->tags['doctrine.event_listener'][] = array(
- 'event' => $event,
- 'connection' => $annot->connection ?: 'default',
- 'lazy' => $annot->lazy,
- 'priority' => $annot->priority,
- );
- }
- } else if ($annot instanceof FormType) {
- if (null === $metadata->id) {
- $metadata->id = $this->generateId($className);
- }
-
- $alias = $annot->alias;
-
- // try to extract it from the class itself
- if (null === $alias) {
- $instance = unserialize(sprintf('O:%d:"%s":0:{}', strlen($className), $className));
- $alias = $instance->getName();
- }
-
- $metadata->tags['form.type'][] = array(
- 'alias' => $alias,
- );
- }
- }
-
- $hasInjection = false;
- foreach ($class->getProperties() as $property) {
- if ($property->getDeclaringClass()->getName() !== $className) {
- continue;
- }
- $name = $property->getName();
-
- foreach ($this->reader->getPropertyAnnotations($property) as $annot) {
- if ($annot instanceof Inject) {
- $hasInjection = true;
- $metadata->properties[$name] = $this->convertReferenceValue($name, $annot);
- }
- }
- }
-
- foreach ($class->getMethods() as $method) {
- if ($method->getDeclaringClass()->getName() !== $className) {
- continue;
- }
- $name = $method->getName();
-
- foreach ($this->reader->getMethodAnnotations($method) as $annot) {
- if ($annot instanceof Observe) {
- $metadata->tags['kernel.event_listener'][] = array(
- 'event' => $annot->event,
- 'method' => $name,
- 'priority' => $annot->priority,
- );
- } else if ($annot instanceof InjectParams) {
- $params = array();
- foreach ($method->getParameters() as $param) {
- if (!isset($annot->params[$paramName = $param->getName()])) {
- $params[] = $this->convertReferenceValue($paramName, new Inject(array('value' => null)));
- continue;
- }
-
- $params[] = $this->convertReferenceValue($paramName, $annot->params[$paramName]);
- }
-
- if (!$params) {
- continue;
- }
-
- $hasInjection = true;
-
- if ('__construct' === $name) {
- $metadata->arguments = $params;
- } else {
- $metadata->methodCalls[] = array($name, $params);
- }
- } else if ($annot instanceof LookupMethod) {
- $hasInjection = true;
-
- if ($method->isFinal()) {
- throw new \RuntimeException(sprintf('The method "%s::%s" is marked as final and cannot be declared as lookup-method.', $className, $name));
- }
- if ($method->isPrivate()) {
- throw new \RuntimeException(sprintf('The method "%s::%s" is marked as private and cannot be declared as lookup-method.', $className, $name));
- }
- if ($method->getParameters()) {
- throw new \RuntimeException(sprintf('The method "%s::%s" must have a no-arguments signature if you want to use it as lookup-method.', $className, $name));
- }
-
- $metadata->lookupMethods[$name] = $this->convertReferenceValue('get' === substr($name, 0, 3) ? substr($name, 3) : $name, $annot);
- } else if ($annot instanceof AfterSetup) {
- if (!$method->isPublic()) {
- throw new \RuntimeException(sprintf('The init method "%s::%s" must be public.', $method->class, $method->name));
- }
-
- $metadata->initMethod = $method->name;
- }
- }
- }
-
- if (null == $metadata->id && !$hasInjection) {
- return null;
- }
-
- return $metadata;
- }
-
- private function convertReferenceValue($name, AnnotReference $annot)
- {
- if (null === $annot->value) {
- return new Reference($this->generateId($name), false !== $annot->required ? ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE : ContainerInterface::NULL_ON_INVALID_REFERENCE);
- }
-
- if (false === strpos($annot->value, '%')) {
- return new Reference($annot->value, false !== $annot->required ? ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE : ContainerInterface::NULL_ON_INVALID_REFERENCE);
- }
-
- return $annot->value;
- }
-
- private function generateId($name)
- {
- $name = preg_replace('/(?<=[a-zA-Z0-9])[A-Z]/', '_\\0', $name);
-
- return strtolower(strtr($name, '\\', '.'));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Metadata;
-
-use Symfony\Component\DependencyInjection\Reference;
-use Symfony\Component\DependencyInjection\DefinitionDecorator;
-use Symfony\Component\DependencyInjection\Definition;
-use Metadata\ClassHierarchyMetadata;
-
-class MetadataConverter
-{
- /**
- * Converts class hierarchy metadata to definition instances.
- *
- * @param ClassHierarchyMetadata $metadata
- * @return array an array of Definition instances
- */
- public function convert(ClassHierarchyMetadata $metadata)
- {
- static $count = 0;
- $definitions = array();
-
- $previous = null;
- foreach ($metadata->classMetadata as $classMetadata) {
- if (null === $previous && null === $classMetadata->parent) {
- $definition = new Definition();
- } else {
- $definition = new DefinitionDecorator(
- $classMetadata->parent ?: $previous->id
- );
- }
-
- $definition->setClass($classMetadata->name);
- if (null !== $classMetadata->scope) {
- $definition->setScope($classMetadata->scope);
- }
- if (null !== $classMetadata->public) {
- $definition->setPublic($classMetadata->public);
- }
- if (null !== $classMetadata->abstract) {
- $definition->setAbstract($classMetadata->abstract);
- }
- if (null !== $classMetadata->arguments) {
- $definition->setArguments($classMetadata->arguments);
- }
-
- $definition->setMethodCalls($classMetadata->methodCalls);
- $definition->setTags($classMetadata->tags);
- $definition->setProperties($classMetadata->properties);
-
- if (null === $classMetadata->id) {
- $classMetadata->id = '_jms_di_extra.unnamed.service_'.$count++;
- }
-
- if ($classMetadata->initMethod) {
- if (!method_exists($definition, 'setInitMethod')) {
- throw new \RuntimeException(sprintf('@AfterSetup is not available on your Symfony version.'));
- }
-
- $definition->setInitMethod($classMetadata->initMethod);
- }
-
- $definitions[$classMetadata->id] = $definition;
- $previous = $classMetadata;
- }
-
- return $definitions;
- }
-}
\ No newline at end of file
+++ /dev/null
-For documentation, see:
-
- Resources/doc
-
-
-For license, see:
-
- Resources/meta/LICENSE
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-
-<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">
-
- <parameters>
- <parameter key="jms_di_extra.metadata.driver.annotation_driver.class">JMS\DiExtraBundle\Metadata\Driver\AnnotationDriver</parameter>
-
- <parameter key="jms_di_extra.metadata.metadata_factory.class">Metadata\MetadataFactory</parameter>
- <parameter key="jms_di_extra.metadata.cache.file_cache.class">Metadata\Cache\FileCache</parameter>
-
- <parameter key="jms_di_extra.metadata.converter.class">JMS\DiExtraBundle\Metadata\MetadataConverter</parameter>
- <parameter key="jms_di_extra.controller_resolver.class">JMS\DiExtraBundle\HttpKernel\ControllerResolver</parameter>
-
- <parameter key="jms_di_extra.template_listener.class">JMS\DiExtraBundle\EventListener\TemplateListener</parameter>
- <parameter key="jms_di_extra.controller_listener.class">JMS\DiExtraBundle\EventListener\ControllerListener</parameter>
- </parameters>
-
- <services>
- <!-- Metadata Drivers -->
- <service id="jms_di_extra.metadata.driver.annotation_driver" class="%jms_di_extra.metadata.driver.annotation_driver.class%" public="false">
- <argument type="service" id="annotation_reader" />
- </service>
- <service id="jms_di_extra.metadata_driver" alias="jms_di_extra.metadata.driver.annotation_driver" public="false" />
-
- <!-- Metadata Factory -->
- <service id="jms_di_extra.metadata.cache.file_cache" class="%jms_di_extra.metadata.cache.file_cache.class%" public="false">
- <argument /><!-- Directory -->
- </service>
- <service id="jms_di_extra.metadata.cache" alias="jms_di_extra.metadata.cache.file_cache" public="false" />
- <service id="jms_di_extra.metadata.metadata_factory" class="%jms_di_extra.metadata.metadata_factory.class%">
- <argument type="service" id="jms_di_extra.metadata_driver" />
- <argument>Metadata\ClassHierarchyMetadata</argument>
- <argument>%kernel.debug%</argument>
- <call method="setCache">
- <argument type="service" id="jms_di_extra.metadata.cache" on-invalid="ignore" />
- </call>
- </service>
-
- <service id="jms_di_extra.metadata.converter" class="%jms_di_extra.metadata.converter.class%" />
-
- <service id="jms_di_extra.controller_resolver" class="%jms_di_extra.controller_resolver.class%" public="false">
- <tag name="monolog.logger" channel="request" />
- <argument type="service" id="service_container" />
- <argument type="service" id="controller_name_converter" />
- <argument type="service" id="logger" on-invalid="ignore" />
- </service>
- </services>
-</container>
\ No newline at end of file
+++ /dev/null
-========
-Overview
-========
-
-This bundle allows you to configure dependency injection using annotations.
-
-Installation
-------------
-Add the following to your ``deps`` file::
-
- [JMSDiExtraBundle]
- git=https://github.com/schmittjoh/JMSDiExtraBundle.git
- target=/bundles/JMS/DiExtraBundle
-
- ; Dependencies:
- ;--------------
- [metadata]
- git=https://github.com/schmittjoh/metadata.git
- version=1.1.0 ; <- make sure to get 1.1, not 1.0
-
-Then register the bundle with your kernel::
-
- // in AppKernel::registerBundles()
- $bundles = array(
- // ...
- new JMS\DiExtraBundle\JMSDiExtraBundle($this),
- // ...
- );
-
-In addition, this bundle also requires the JMSAopBundle. See its documentation for
-installation instructions::
-
- https://github.com/schmittjoh/JMSAopBundle/blob/master/Resources/doc/index.rst
-
-
-Make sure that you also register the namespaces with the autoloader::
-
- // app/autoload.php
- $loader->registerNamespaces(array(
- // ...
- 'JMS' => __DIR__.'/../vendor/bundles',
- 'Metadata' => __DIR__.'/../vendor/metadata/src',
- // ...
- ));
-
-
-Configuration
--------------
-For optimal development performance (in production there is no difference either way),
-it is recommended to explicitly configure the directories which should be scanned for
-service classes (by default no directory is scanned)::
-
- jms_di_extra:
- locations:
- all_bundles: false
- bundles: [FooBundle, AcmeBlogBundle, etc.]
- directories: [%kernel.root_dir%/../src, some/other/dir]
-
-Usage
------
-
-Non-Controller Classes
-~~~~~~~~~~~~~~~~~~~~~~
-
-Non-controller classes are configured, and managed by Symfony's DIC just like any
-other service that you configure using YML, XML, or PHP. The only difference is
-that you can do it via annotations which is a lot more convenient.
-
-You can use these annotations on services (for examples, see below):
-@Service, @Inject, @InjectParams, @Observe, @Tag
-
-Note that you cannot use the @Inject annotation on private, or protected properties.
-Likewise, the @InjectParams annotation does not work on protected, or private methods.
-
-
-Controllers
-~~~~~~~~~~~
-
-Controllers are a special type of class which is also treated specially by this
-bundle. The most notable difference is that you do not need to define these
-classes as services. Yes, no services, but don't worry you can still use all of
-the DIC's features, and even some more.
-
-- Constructor/Setter Injection::
-
- <?php
-
- use JMS\DiExtraBundle\Annotation as DI;
-
- class Controller
- {
- private $em;
- private $session;
-
- /**
- * @DI\InjectParams({
- * "em" = @DI\Inject("doctrine.orm.entity_manager"),
- * "session" = @DI\Inject("session")
- * })
- */
- public function __construct($em, $session)
- {
- $this->em = $em;
- $this->session = $session;
- }
- // ... some actions
- }
-
- **Note:** Constructor Injection is not possible when a parent definition
- also defines a constructor which is configured for injection.
-
-- Property Injection::
-
- <?php
-
- use JMS\DiExtraBundle\Annotation as DI;
-
- class Controller
- {
- /** @DI\Inject("doctrine.orm.entity_manager")
- private $em;
-
- /** @DI\Inject("session")
- private $session;
- }
-
-- Method/Getter Injection::
-
- <?php
-
- use JMS\DiExtraBundle\Annotation as DI;
-
- class Controller
- {
- public function myAction()
- {
- // ...
- if ($condition) {
- $mailer = $this->getMailer();
- }
- }
-
- /** @DI\LookupMethod("mailer") */
- protected function getMailer() { /* empty body here */ }
- }
-
-You can use this type of injection if you have a dependency that you do not
-always need in the controller, and which is costly to initialize, like the
-mailer in the example above.
-
-
-Annotations
------------
-
-@Inject
-~~~~~~~~~
-This marks a property, or parameter for injection::
-
- use JMS\DiExtraBundle\Annotation\Inject;
-
- class Controller
- {
- /**
- * @Inject("security.context", required = false)
- */
- private $securityContext;
-
- /**
- * @Inject("%kernel.cache_dir%")
- */
- private $cacheDir;
-
- /**
- * @Inject
- */
- private $session;
- }
-
-If you do not specify the service explicitly, we will try to guess it based on the name
-of the property or the parameter.
-
-@InjectParams
-~~~~~~~~~~~~~~~
-This marks the parameters of a method for injection::
-
- use JMS\DiExtraBundle\Annotation\Inject;
- use JMS\DiExtraBundle\Annotation\InjectParams;
- use JMS\DiExtraBundle\Annotation\Service;
-
- /**
- * @Service
- */
- class Listener
- {
- /**
- * @InjectParams({
- * "em" = @Inject("doctrine.entity_manager")
- * })
- */
- public function __construct(EntityManager $em, Session $session)
- {
- // ...
- }
- }
-
-If you don't define all parameters in the param map, we will try to guess which services
-should be injected into the remaining parameters based on their name.
-
-@Service
-~~~~~~~~
-Marks a class as service::
-
- use JMS\DiExtraBundle\Annotation\Service;
-
- /**
- * @Service("some.service.id", parent="another.service.id", public=false)
- */
- class Listener
- {
- }
-
-If you do not explicitly define a service id, then we will generated a sensible default
-based on the fully qualified class name for you.
-
-@Tag
-~~~~
-Adds a tag to the service::
-
- use JMS\DiExtraBundle\Annotation\Service;
- use JMS\DiExtraBundle\Annotation\Tag;
-
- /**
- * @Service
- * @Tag("doctrine.event_listener", attributes = {"event" = "postGenerateSchema", lazy=true})
- */
- class Listener
- {
- // ...
- }
-
-@Observe
-~~~~~~~~
-Automatically registers a method as listener to a certain event::
-
- use JMS\DiExtraBundle\Annotation\Observe;
- use JMS\DiExtraBundle\Annotation\Service;
-
- /**
- * @Service
- */
- class RequestListener
- {
- /**
- * @Observe("kernel.request", priority = 255)
- */
- public function onKernelRequest()
- {
- // ...
- }
- }
-
-@Validator
-~~~~~~~~~~
-Automatically registers the given class as constraint validator for the Validator component::
-
- use JMS\DiExtraBundle\Annotation\Validator;
- use Symfony\Component\Validator\Constraint;
- use Symfony\Component\Validator\ConstraintValidator;
-
- /**
- * @Validator("my_alias")
- */
- class MyValidator extends ConstraintValidator
- {
- // ...
- }
-
- class MyConstraint extends Constraint
- {
- // ...
- public function validatedBy()
- {
- return 'my_alias';
- }
- }
-
-The @Validator annotation also implies the @Service annotation if you do not specify it explicitly.
-The alias which is passed to the @Validator annotation must match the string that is returned from
-the ``validatedBy`` method of your constraint.
-
+++ /dev/null
- Apache License\r
- Version 2.0, January 2004\r
- http://www.apache.org/licenses/\r
-\r
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\r
-\r
- 1. Definitions.\r
-\r
- "License" shall mean the terms and conditions for use, reproduction,\r
- and distribution as defined by Sections 1 through 9 of this document.\r
-\r
- "Licensor" shall mean the copyright owner or entity authorized by\r
- the copyright owner that is granting the License.\r
-\r
- "Legal Entity" shall mean the union of the acting entity and all\r
- other entities that control, are controlled by, or are under common\r
- control with that entity. For the purposes of this definition,\r
- "control" means (i) the power, direct or indirect, to cause the\r
- direction or management of such entity, whether by contract or\r
- otherwise, or (ii) ownership of fifty percent (50%) or more of the\r
- outstanding shares, or (iii) beneficial ownership of such entity.\r
-\r
- "You" (or "Your") shall mean an individual or Legal Entity\r
- exercising permissions granted by this License.\r
-\r
- "Source" form shall mean the preferred form for making modifications,\r
- including but not limited to software source code, documentation\r
- source, and configuration files.\r
-\r
- "Object" form shall mean any form resulting from mechanical\r
- transformation or translation of a Source form, including but\r
- not limited to compiled object code, generated documentation,\r
- and conversions to other media types.\r
-\r
- "Work" shall mean the work of authorship, whether in Source or\r
- Object form, made available under the License, as indicated by a\r
- copyright notice that is included in or attached to the work\r
- (an example is provided in the Appendix below).\r
-\r
- "Derivative Works" shall mean any work, whether in Source or Object\r
- form, that is based on (or derived from) the Work and for which the\r
- editorial revisions, annotations, elaborations, or other modifications\r
- represent, as a whole, an original work of authorship. For the purposes\r
- of this License, Derivative Works shall not include works that remain\r
- separable from, or merely link (or bind by name) to the interfaces of,\r
- the Work and Derivative Works thereof.\r
-\r
- "Contribution" shall mean any work of authorship, including\r
- the original version of the Work and any modifications or additions\r
- to that Work or Derivative Works thereof, that is intentionally\r
- submitted to Licensor for inclusion in the Work by the copyright owner\r
- or by an individual or Legal Entity authorized to submit on behalf of\r
- the copyright owner. For the purposes of this definition, "submitted"\r
- means any form of electronic, verbal, or written communication sent\r
- to the Licensor or its representatives, including but not limited to\r
- communication on electronic mailing lists, source code control systems,\r
- and issue tracking systems that are managed by, or on behalf of, the\r
- Licensor for the purpose of discussing and improving the Work, but\r
- excluding communication that is conspicuously marked or otherwise\r
- designated in writing by the copyright owner as "Not a Contribution."\r
-\r
- "Contributor" shall mean Licensor and any individual or Legal Entity\r
- on behalf of whom a Contribution has been received by Licensor and\r
- subsequently incorporated within the Work.\r
-\r
- 2. Grant of Copyright License. Subject to the terms and conditions of\r
- this License, each Contributor hereby grants to You a perpetual,\r
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable\r
- copyright license to reproduce, prepare Derivative Works of,\r
- publicly display, publicly perform, sublicense, and distribute the\r
- Work and such Derivative Works in Source or Object form.\r
-\r
- 3. Grant of Patent License. Subject to the terms and conditions of\r
- this License, each Contributor hereby grants to You a perpetual,\r
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable\r
- (except as stated in this section) patent license to make, have made,\r
- use, offer to sell, sell, import, and otherwise transfer the Work,\r
- where such license applies only to those patent claims licensable\r
- by such Contributor that are necessarily infringed by their\r
- Contribution(s) alone or by combination of their Contribution(s)\r
- with the Work to which such Contribution(s) was submitted. If You\r
- institute patent litigation against any entity (including a\r
- cross-claim or counterclaim in a lawsuit) alleging that the Work\r
- or a Contribution incorporated within the Work constitutes direct\r
- or contributory patent infringement, then any patent licenses\r
- granted to You under this License for that Work shall terminate\r
- as of the date such litigation is filed.\r
-\r
- 4. Redistribution. You may reproduce and distribute copies of the\r
- Work or Derivative Works thereof in any medium, with or without\r
- modifications, and in Source or Object form, provided that You\r
- meet the following conditions:\r
-\r
- (a) You must give any other recipients of the Work or\r
- Derivative Works a copy of this License; and\r
-\r
- (b) You must cause any modified files to carry prominent notices\r
- stating that You changed the files; and\r
-\r
- (c) You must retain, in the Source form of any Derivative Works\r
- that You distribute, all copyright, patent, trademark, and\r
- attribution notices from the Source form of the Work,\r
- excluding those notices that do not pertain to any part of\r
- the Derivative Works; and\r
-\r
- (d) If the Work includes a "NOTICE" text file as part of its\r
- distribution, then any Derivative Works that You distribute must\r
- include a readable copy of the attribution notices contained\r
- within such NOTICE file, excluding those notices that do not\r
- pertain to any part of the Derivative Works, in at least one\r
- of the following places: within a NOTICE text file distributed\r
- as part of the Derivative Works; within the Source form or\r
- documentation, if provided along with the Derivative Works; or,\r
- within a display generated by the Derivative Works, if and\r
- wherever such third-party notices normally appear. The contents\r
- of the NOTICE file are for informational purposes only and\r
- do not modify the License. You may add Your own attribution\r
- notices within Derivative Works that You distribute, alongside\r
- or as an addendum to the NOTICE text from the Work, provided\r
- that such additional attribution notices cannot be construed\r
- as modifying the License.\r
-\r
- You may add Your own copyright statement to Your modifications and\r
- may provide additional or different license terms and conditions\r
- for use, reproduction, or distribution of Your modifications, or\r
- for any such Derivative Works as a whole, provided Your use,\r
- reproduction, and distribution of the Work otherwise complies with\r
- the conditions stated in this License.\r
-\r
- 5. Submission of Contributions. Unless You explicitly state otherwise,\r
- any Contribution intentionally submitted for inclusion in the Work\r
- by You to the Licensor shall be under the terms and conditions of\r
- this License, without any additional terms or conditions.\r
- Notwithstanding the above, nothing herein shall supersede or modify\r
- the terms of any separate license agreement you may have executed\r
- with Licensor regarding such Contributions.\r
-\r
- 6. Trademarks. This License does not grant permission to use the trade\r
- names, trademarks, service marks, or product names of the Licensor,\r
- except as required for reasonable and customary use in describing the\r
- origin of the Work and reproducing the content of the NOTICE file.\r
-\r
- 7. Disclaimer of Warranty. Unless required by applicable law or\r
- agreed to in writing, Licensor provides the Work (and each\r
- Contributor provides its Contributions) on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\r
- implied, including, without limitation, any warranties or conditions\r
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\r
- PARTICULAR PURPOSE. You are solely responsible for determining the\r
- appropriateness of using or redistributing the Work and assume any\r
- risks associated with Your exercise of permissions under this License.\r
-\r
- 8. Limitation of Liability. In no event and under no legal theory,\r
- whether in tort (including negligence), contract, or otherwise,\r
- unless required by applicable law (such as deliberate and grossly\r
- negligent acts) or agreed to in writing, shall any Contributor be\r
- liable to You for damages, including any direct, indirect, special,\r
- incidental, or consequential damages of any character arising as a\r
- result of this License or out of the use or inability to use the\r
- Work (including but not limited to damages for loss of goodwill,\r
- work stoppage, computer failure or malfunction, or any and all\r
- other commercial damages or losses), even if such Contributor\r
- has been advised of the possibility of such damages.\r
-\r
- 9. Accepting Warranty or Additional Liability. While redistributing\r
- the Work or Derivative Works thereof, You may choose to offer,\r
- and charge a fee for, acceptance of support, warranty, indemnity,\r
- or other liability obligations and/or rights consistent with this\r
- License. However, in accepting such obligations, You may act only\r
- on Your own behalf and on Your sole responsibility, not on behalf\r
- of any other Contributor, and only if You agree to indemnify,\r
- defend, and hold each Contributor harmless for any liability\r
- incurred by, or claims asserted against, such Contributor by reason\r
- of your accepting any such warranty or additional liability.\r
-\r
- END OF TERMS AND CONDITIONS\r
-\r
- APPENDIX: How to apply the Apache License to your work.\r
-\r
- To apply the Apache License to your work, attach the following\r
- boilerplate notice, with the fields enclosed by brackets "[]"\r
- replaced with your own identifying information. (Don't include\r
- the brackets!) The text should be enclosed in the appropriate\r
- comment syntax for the file format. We also recommend that a\r
- file or class name and description of purpose be included on the\r
- same "printed page" as the copyright notice for easier\r
- identification within third-party archives.\r
-\r
- Copyright [yyyy] [name of copyright owner]\r
-\r
- Licensed under the Apache License, Version 2.0 (the "License");\r
- you may not use this file except in compliance with the License.\r
- You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\DependencyInjection\Compiler;
-
-use Symfony\Component\DependencyInjection\Reference;
-
-use Symfony\Component\DependencyInjection\DefinitionDecorator;
-
-use Doctrine\Common\Annotations\AnnotationReader;
-use JMS\DiExtraBundle\DependencyInjection\JMSDiExtraExtension;
-use Symfony\Component\HttpKernel\KernelInterface;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use JMS\DiExtraBundle\DependencyInjection\Compiler\AnnotationConfigurationPass;
-
-class AnnotationConfigurationPassTest extends \PHPUnit_Framework_TestCase
-{
- public function testProcess()
- {
- $container = $this->getContainer(array(), array(
- __DIR__.'/../../Fixture/',
- ));
- $container->set('doctrine.entity_manager', $em = new \stdClass);
- $container->set('session', $session = new \stdClass);
- $container->set('database_connection', $dbCon = new \stdClass);
- $container->set('router', $router = new \stdClass);
- $container->setParameter('table_name', 'foo');
- $this->process($container);
-
- $this->assertTrue($container->hasDefinition('j_m_s.di_extra_bundle.tests.fixture.request_listener'));
- $service = $container->get('j_m_s.di_extra_bundle.tests.fixture.request_listener');
- $this->assertAttributeEquals($em, 'em', $service);
- $this->assertAttributeEquals($session, 'session', $service);
- $this->assertAttributeEquals($dbCon, 'con', $service);
- $this->assertAttributeEquals($router, 'router', $service);
- $this->assertAttributeEquals('foo', 'table', $service);
- }
-
- public function testProcessValidator()
- {
- $container = $this->getContainer(array(), array(
- __DIR__.'/../../Fixture/Validator',
- ));
- $container->set('foo', $foo = new \stdClass);
- $this->process($container);
-
- $this->assertTrue($container->hasDefinition('j_m_s.di_extra_bundle.tests.fixture.validator.validator'));
-
- $def = $container->getDefinition('j_m_s.di_extra_bundle.tests.fixture.validator.validator');
- $this->assertEquals(array(
- 'validator.constraint_validator' => array(
- array('alias' => 'foobar'),
- )
- ), $def->getTags());
-
- $v = $container->get('j_m_s.di_extra_bundle.tests.fixture.validator.validator');
- $this->assertAttributeEquals($foo, 'foo', $v);
- }
-
- public function testConstructorWithInheritance()
- {
- $container = $this->getContainer(array(), array(
- __DIR__.'/../../Functional/Bundle/TestBundle/Inheritance',
- ));
- $container->set('foo', $foo = new \stdClass);
- $container->set('bar', $bar = new \stdClass);
- $this->process($container);
-
- $this->assertTrue($container->hasDefinition('concrete_class'));
- $this->assertTrue($container->hasDefinition('abstract_class'));
-
- $def = new DefinitionDecorator('abstract_class');
- $def->setClass('JMS\DiExtraBundle\Tests\Functional\Bundle\TestBundle\Inheritance\ConcreteClass');
- $def->addArgument(new Reference('foo'));
- $def->addArgument(new Reference('bar'));
-
- $this->assertEquals($def, $container->getDefinition('concrete_class'));
- }
-
- private function getContainer(array $bundles = array(), array $directories = array())
- {
- $container = new ContainerBuilder();
- $container->set('annotation_reader', new AnnotationReader());
- $container->setParameter('kernel.debug', false);
-
- $extension = new JMSDiExtraExtension();
- $extension->load(array(array(
- 'locations' => array(
- 'bundles' => $bundles,
- 'directories' => $directories,
- ),
- 'metadata' => array(
- 'cache' => 'none',
- )
- )), $container);
-
- return $container;
- }
-
- private function process(ContainerBuilder $container, array $bundles = array())
- {
- $kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
- $kernel
- ->expects($this->once())
- ->method('getBundles')
- ->will($this->returnValue($bundles))
- ;
-
- $pass = new AnnotationConfigurationPass($kernel);
- $pass->process($container);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\DependencyInjection\Compiler;
-
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use JMS\DiExtraBundle\DependencyInjection\Compiler\ResourceOptimizationPass;
-use Symfony\Component\Config\Resource\DirectoryResource;
-
-class ResourceOptimizationPassTest extends \PHPUnit_Framework_TestCase
-{
- public function testProcess()
- {
- $container = new ContainerBuilder();
- $container->addResource(new DirectoryResource(__DIR__.'/Fixtures/a'));
- $container->addResource(new DirectoryResource(__DIR__.'/Fixtures/a/b'));
- $container->addResource(new DirectoryResource(__DIR__.'/Fixtures/c'));
- $this->process($container);
-
- $resources = $container->getResources();
- $this->assertEquals(1, count($resources));
- $this->assertInstanceOf('JMS\DiExtraBundle\Config\FastDirectoriesResource', $resources[0]);
- $this->assertEquals(array(
- __DIR__.'/Fixtures/a',
- __DIR__.'/Fixtures/c'
- ), $resources[0]->getResource());
- $this->assertAttributeEquals('*', 'filePattern', $resources[0]);
- }
-
- private function process(ContainerBuilder $container)
- {
- $pass = new ResourceOptimizationPass();
- $pass->process($container);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Finder;
-
-use JMS\DiExtraBundle\Finder\PatternFinder;
-use Symfony\Component\Process\ExecutableFinder;
-
-abstract class AbstractPatternFinderTest extends \PHPUnit_Framework_TestCase
-{
- public function testFindFiles()
- {
- $finder = $this->getFinder();
-
- $expectedFiles = array(
- realpath(__DIR__.'/../Fixture/NonEmptyDirectory/Service1.php'),
- realpath(__DIR__.'/../Fixture/NonEmptyDirectory/SubDir1/Service2.php'),
- realpath(__DIR__.'/../Fixture/NonEmptyDirectory/SubDir2/Service3.php'),
- );
-
- $foundFiles = $finder->findFiles(array(__DIR__.'/../Fixture/NonEmptyDirectory'));
- $foundFiles = array_map('realpath', $foundFiles);
-
- $this->assertEquals(array(), array_diff($expectedFiles, $foundFiles));
- $this->assertEquals(array(), array_diff($foundFiles, $expectedFiles));
- }
-
- public function testFindFilesUsingGrepReturnsEmptyArrayWhenNoMatchesAreFound()
- {
- $finder = $this->getFinder();
- $this->assertEquals(array(), $finder->findFiles(array(__DIR__.'/../Fixture/EmptyDirectory')));
- }
-
- abstract protected function getFinder();
-}
\ No newline at end of file
+++ /dev/null
-<?php\r
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Finder;\r
-\r
-use JMS\DiExtraBundle\Finder\PatternFinder;
-\r
-class FindstrPatternFinderTest extends AbstractPatternFinderTest\r
-{\r
- protected function getFinder()\r
- {\r
- if (0 !== stripos(PHP_OS, 'win')) {\r
- $this->markTestSkipped('FINDSTR is only available on Windows.');\r
- }\r
-\r
- $finder = new PatternFinder('JMS\DiExtraBundle\Annotation');\r
- $ref = new \ReflectionProperty($finder, 'method');\r
- $ref->setAccessible(true);\r
- $ref->setValue($finder, PatternFinder::METHOD_FINDSTR);\r
-\r
- return $finder;\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-<?php\r
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Finder;\r
-\r
-use JMS\DiExtraBundle\Finder\PatternFinder;
-\r
-class GrepPatternFinderTest extends AbstractPatternFinderTest\r
-{\r
- protected function getFinder()\r
- {\r
- $finder = new PatternFinder('JMS\DiExtraBundle\Annotation');\r
-\r
- $ref = new \ReflectionProperty($finder, 'grepPath');\r
- $ref->setAccessible(true);\r
- if (null === $v = $ref->getValue($finder)) {\r
- $this->markTestSkipped('grep is not available on your system.');\r
- }\r
-\r
- return $finder;\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-<?php\r
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Finder;\r
-\r
-use JMS\DiExtraBundle\Finder\PatternFinder;
-\r
-class PhpPatternFinderTest extends AbstractPatternFinderTest\r
-{\r
- protected function getFinder()\r
- {\r
- $finder = new PatternFinder('JMS\DiExtraBundle\Annotation');\r
- $ref = new \ReflectionProperty($finder, 'method');\r
- $ref->setAccessible(true);\r
- $ref->setValue($finder, PatternFinder::METHOD_FINDER);\r
-\r
- return $finder;\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Fixture;
-
-use JMS\DiExtraBundle\Annotation\Inject;
-
-/**
- * Login Controller.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class LoginController
-{
- /**
- * @Inject("form.csrf_provider")
- */
- private $csrfProvider;
-
- /**
- * @Inject
- */
- private $rememberMeServices;
-
- /**
- * @Inject("security.context")
- */
- private $securityContext;
-
- /**
- * @Inject("security.authentication.trust_resolver")
- */
- private $trustResolver;
-
- public function loginAction()
- {
- }
-
- public function getCsrfProvider()
- {
- return $this->csrfProvider;
- }
-
- public function getRememberMeServices()
- {
- return $this->rememberMeServices;
- }
-
- public function getSecurityContext()
- {
- return $this->securityContext;
- }
-
- public function getTrustResolver()
- {
- return $this->trustResolver;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php\r
-\r
-// just nothing in here
\ No newline at end of file
+++ /dev/null
-<?php\r
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Fixture\NonEmptyDirectory;\r
-\r
-use JMS\DiExtraBundle\Annotation as DI;\r
-\r
-/** @DI\Service */\r
-class Service1\r
-{\r
-}
\ No newline at end of file
+++ /dev/null
-<?php\r
-\r
-namespace FooBar;\r
-\r
-use JMS\DiExtraBundle\Annotation\Service;\r
-\r
-/** @Service */\r
-class Foo\r
-{\r
-}
\ No newline at end of file
+++ /dev/null
-<?php\r
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Fixture\NonEmptyDirectory\SubDir1;\r
-\r
-use JMS\DiExtraBundle\Annotation\Service;\r
-\r
-/** @Service */\r
-class Service2\r
-{\r
-}
\ No newline at end of file
+++ /dev/null
-<?php\r
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Fixture\NonEmptyDirectory\SubDir2;\r
-\r
-use JMS\DiExtraBundle\Annotation as DI;\r
-\r
-/** @DI\Service */\r
-class Service1\r
-{\r
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Fixture;
-
-use JMS\DiExtraBundle\Annotation as DI;
-
-/**
- * @DI\Service
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class RequestListener
-{
- private $router;
- private $session;
- private $em;
- private $con;
- private $table;
-
- /**
- * @DI\InjectParams({
- * "em" = @DI\Inject("doctrine.entity_manager")
- * })
- */
- public function __construct($router, $session, $em)
- {
- $this->router = $router;
- $this->session = $session;
- $this->em = $em;
- }
-
- /**
- * @DI\InjectParams({
- * "table" = @DI\Inject("%table_name%")
- * })
- */
- public function setConnection($databaseConnection, $table)
- {
- $this->con = $databaseConnection;
- $this->table = $table;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Fixture\Validator;
-
-use JMS\DiExtraBundle\Annotation\InjectParams;
-use JMS\DiExtraBundle\Annotation\Validator as ValidatorAnnot;
-use Symfony\Component\Validator\Constraint;
-use Symfony\Component\Validator\ConstraintValidator;
-
-/**
- * @ValidatorAnnot("foobar")
- */
-class Validator extends ConstraintValidator
-{
- private $foo;
-
- /**
- * @InjectParams
- */
- public function __construct($foo)
- {
- $this->foo = $foo;
- }
-
- public function isValid($value, Constraint $constraint)
- {
- return true;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Functional;
-
-require_once __DIR__.'/../bootstrap.php';
-
-use Symfony\Component\HttpKernel\Util\Filesystem;
-use Symfony\Component\Config\Loader\LoaderInterface;
-use Symfony\Component\HttpKernel\Kernel;
-
-class AppKernel extends Kernel
-{
- private $config;
-
- public function __construct($config)
- {
- parent::__construct('test', true);
-
- $fs = new Filesystem();
- if (!$fs->isAbsolutePath($config)) {
- $config = __DIR__.'/config/'.$config;
- }
-
- if (!file_exists($config)) {
- throw new \RuntimeException(sprintf('The config file "%s" does not exist.', $config));
- }
-
- $this->config = $config;
- }
-
- public function registerBundles()
- {
- return array(
- new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
- new \Symfony\Bundle\SecurityBundle\SecurityBundle(),
- new \Symfony\Bundle\TwigBundle\TwigBundle(),
- new \Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
- new \JMS\AopBundle\JMSAopBundle(),
- new \JMS\DiExtraBundle\Tests\Functional\Bundle\TestBundle\JMSDiExtraTestBundle(),
- new \JMS\DiExtraBundle\JMSDiExtraBundle($this),
- new \JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
- );
- }
-
- public function registerContainerConfiguration(LoaderInterface $loader)
- {
- $loader->load($this->config);
- }
-
- public function getCacheDir()
- {
- return sys_get_temp_dir().'/JMSDiExtraBundle';
- }
-
- public function serialize()
- {
- return $this->config;
- }
-
- public function unserialize($config)
- {
- $this->__construct($config);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Functional;
-
-use Symfony\Component\HttpKernel\Util\Filesystem;
-
-use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
-
-class BaseTestCase extends WebTestCase
-{
- static protected function createKernel(array $options = array())
- {
- return new AppKernel(
- isset($options['config']) ? $options['config'] : 'default.yml'
- );
- }
-
- protected function tearDown()
- {
- $this->cleanTmpDir();
- }
-
- protected function setUp()
- {
- $this->cleanTmpDir();
- }
-
- private function cleanTmpDir()
- {
- $fs = new Filesystem();
- $fs->remove(sys_get_temp_dir().'/JMSDiExtraBundle');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Functional\Bundle\TestBundle\Controller;
-
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
-use JMS\SecurityExtraBundle\Annotation\Secure;
-use JMS\DiExtraBundle\Annotation as DI;
-
-/**
- * Secured Controller.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class AnotherSecuredController
-{
- /**
- * @Route("/secure-action")
- * @Secure("ROLE_FOO")
- */
- public function secureAction()
- {
- throw new \Exception('Should never be called');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Functional\Bundle\TestBundle\Controller;
-
-use Symfony\Component\HttpFoundation\Response;
-use JMS\DiExtraBundle\Annotation as DI;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
-
-/**
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-abstract class RegisterController
-{
- /**
- * @Route("/register")
- */
- public function registerAction()
- {
- $mailer = $this->getMailer();
-
- return new Response($mailer->getFromMail(), 200, array('Content-Type' => 'text/plain'));
- }
-
- /** @DI\LookupMethod("test_mailer") */
- abstract protected function getMailer();
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Functional\Bundle\TestBundle\Controller;
-
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
-use JMS\SecurityExtraBundle\Annotation\Secure;
-use JMS\DiExtraBundle\Annotation as DI;
-
-/**
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-abstract class SecuredController
-{
- /**
- * @Route("/lookup-method-and-aop")
- * @Secure("ROLE_FOO")
- */
- public function secureAction()
- {
- throw new \Exception('Should never be called');
- }
-
- /** @DI\LookupMethod */
- abstract protected function getTestMailer();
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\DiExtraBundle\Tests\Functional\Bundle\TestBundle\Inheritance;
-
-use Symfony\Component\Templating\EngineInterface;
-use JMS\DiExtraBundle\Annotation as DI;
-
-/**
- * @DI\Service("abstract_class")
- *
- * @author johannes
- */
-abstract class AbstractClass
-{
- private $templating;
-
- /**
- * @DI\InjectParams
- *
- * @param EngineInterface $templating
- */
- public function setTemplating(EngineInterface $templating)
- {
- $this->templating = $templating;
- }
-
- public function getTemplating()
- {
- return $this->templating;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\DiExtraBundle\Tests\Functional\Bundle\TestBundle\Inheritance;
-
-use JMS\DiExtraBundle\Annotation as DI;
-
-/**
- * @DI\Service("concrete_class")
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class ConcreteClass extends AbstractClass
-{
- private $foo;
- private $bar;
-
- /**
- * @DI\InjectParams
- *
- * @param stdClass $foo
- * @param stdClass $bar
- */
- public function __construct($foo, $bar)
- {
- $this->foo = $foo;
- $this->bar = $bar;
- }
-
- public function getFoo()
- {
- return $this->foo;
- }
-
- public function getBar()
- {
- return $this->bar;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Functional\Bundle\TestBundle;
-
-use Symfony\Component\HttpKernel\Bundle\Bundle;
-
-class JMSDiExtraTestBundle extends Bundle
-{
-}
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Functional\Bundle\TestBundle\Mailer;
-
-use JMS\DiExtraBundle\Annotation as DI;
-
-/**
- * @DI\Service("test_mailer")
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class TestMailer
-{
- public function getFromMail()
- {
- return 'foo@bar.de';
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Functional;
-
-class ControllerResolverTest extends BaseTestCase
-{
- public function testLookupMethodIsCorrectlyImplemented()
- {
- $client = $this->createClient();
- $client->request('GET', '/register');
-
- $this->assertEquals('foo@bar.de', $client->getResponse()->getContent());
- }
-
- public function testLookupMethodAndAopProxy()
- {
- $client = $this->createClient();
- $client->request('GET', '/lookup-method-and-aop');
-
- $this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'), substr((string) $client->getResponse(), 0, 512));
-
- $client->insulate();
- $client->request('GET', '/lookup-method-and-aop');
- $this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'), substr((string) $client->getResponse(), 0, 512));
- }
-
- public function testAopProxyWhenNoDiMetadata()
- {
- $client = $this->createClient();
- $client->request('GET', '/secure-action');
-
- $this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\DiExtraBundle\Tests\Functional;
-
-class Issue11Test extends BaseTestCase
-{
- public function testConstructorInjectionWithInheritance()
- {
- $this->createClient();
-
- $container = self::$kernel->getContainer();
- $foo = $container->get('foo');
- $bar = $container->get('bar');
- $templating = $container->get('templating');
-
- $concreteService = $container->get('concrete_class');
- $this->assertSame($templating, $concreteService->getTemplating());
- $this->assertSame($foo, $concreteService->getFoo());
- $this->assertSame($bar, $concreteService->getBar());
- }
-}
\ No newline at end of file
+++ /dev/null
-imports:
- - { resource: framework.yml }
- - { resource: twig.yml }
- - { resource: security.yml }
-
-jms_di_extra:
- locations:
- bundles: [JMSDiExtraTestBundle]
-
-services:
- foo: { class: stdClass }
- bar: { class: stdClass }
\ No newline at end of file
+++ /dev/null
-framework:
- secret: test
- test: ~
- session:
- storage_id: session.storage.filesystem
- form: true
- csrf_protection: true
- validation:
- enabled: true
- enable_annotations: true
- router:
- resource: %kernel.root_dir%/config/routing.yml
-
-services:
- logger:
- class: Symfony\Component\HttpKernel\Log\NullLogger
\ No newline at end of file
+++ /dev/null
-TestBundle:
- type: annotation
- resource: @JMSDiExtraTestBundle/Controller/
\ No newline at end of file
+++ /dev/null
-security:
- providers:
- in_memory:
- users:
- johannes: { password: login }
-
- encoders:
- Symfony\Component\Security\Core\User\UserInterface: plaintext
-
- firewalls:
- default:
- form_login: ~
- anonymous: ~
+++ /dev/null
-framework:
- templating:
- engines: [twig, php]
-
-twig:
- debug: %kernel.debug%
- strict_variables: %kernel.debug%
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests\Metadata;
-
-use JMS\DiExtraBundle\Metadata\ClassMetadata;
-
-class ClassMetadataTest extends \PHPUnit_Framework_TestCase
-{
- public function testSerializeUnserialize()
- {
- $classMetadata = new ClassMetadata('JMS\DiExtraBundle\Tests\Fixture\LoginController');
- $classMetadata->arguments = array('foo', 'bar');
- $classMetadata->abstract = true;
- $classMetadata->public = false;
- $classMetadata->id = 'foo';
-
- $this->assertEquals($classMetadata, unserialize(serialize($classMetadata)));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\DiExtraBundle\Tests\Metadata\Driver;
-
-use Doctrine\Common\Annotations\AnnotationReader;
-use JMS\DiExtraBundle\Metadata\Driver\AnnotationDriver;
-
-class AnnotationDriverTest extends \PHPUnit_Framework_TestCase
-{
- public function testFormType()
- {
- $metadata = $this->getDriver()->loadMetadataForClass(new \ReflectionClass('JMS\DiExtraBundle\Tests\Metadata\Driver\Fixture\LoginType'));
-
- $this->assertEquals('j_m_s.di_extra_bundle.tests.metadata.driver.fixture.login_type', $metadata->id);
- $this->assertEquals(array(
- 'form.type' => array(
- array('alias' => 'login'),
- )
- ), $metadata->tags);
- }
-
- public function testFormTypeWithExplicitAlias()
- {
- $metadata = $this->getDriver()->loadMetadataForClass(new \ReflectionClass('JMS\DiExtraBundle\Tests\Metadata\Driver\Fixture\SignUpType'));
-
- $this->assertEquals(array(
- 'form.type' => array(
- array('alias' => 'foo'),
- )
- ), $metadata->tags);
- }
-
- private function getDriver()
- {
- return new AnnotationDriver(new AnnotationReader());
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\DiExtraBundle\Tests\Metadata\Driver\Fixture;
-
-use Security\SecurityContext;
-use Symfony\Component\Form\AbstractType;
-use JMS\DiExtraBundle as DI; // Use this alias in order to not have this class picked up by the finder
-
-/**
- * @DI\Annotation\FormType
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class LoginType extends AbstractType
-{
- private $securityContext;
-
- public function __construct(SecurityContext $context)
- {
- $this->securityContext = $context;
- }
-
- public function getName()
- {
- return 'login';
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\DiExtraBundle\Tests\Metadata\Driver\Fixture;
-
-use Symfony\Component\Form\AbstractType;
-use JMS\DiExtraBundle as DI;
-
-/**
- * @DI\Annotation\FormType("foo")
- *
- * @author johannes
- */
-class SignUpType extends AbstractType
-{
- public function getName()
- {
- return 'sign_up';
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\DiExtraBundle\Tests;
-
-use Symfony\Bundle\TwigBundle\TwigBundle;
-use Symfony\Bundle\DoctrineBundle\DoctrineBundle;
-use JMS\DiExtraBundle\JMSDiExtraBundle;
-use JMS\SecurityExtraBundle\JMSSecurityExtraBundle;
-use Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle;
-use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension;
-use Symfony\Bundle\AsseticBundle\AsseticBundle;
-use Symfony\Bundle\MonologBundle\MonologBundle;
-use Symfony\Bundle\SecurityBundle\SecurityBundle;
-use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
-use JMS\DiExtraBundle\Finder\ServiceFinder;
-
-/**
- * @group performance
- */
-class PerformanceTest extends \PHPUnit_Framework_TestCase
-{
- /**
- * @dataProvider getFinderMethods
- */
- public function testServiceFinder($method)
- {
- $finder = new ServiceFinder();
- $ref = new \ReflectionMethod($finder, $method);
- $ref->setAccessible(true);
-
- $bundles = array(
- new FrameworkBundle(),
- new SecurityBundle(),
- new MonologBundle(),
- new AsseticBundle(),
- new DoctrineBundle(),
- new TwigBundle(),
- new SensioFrameworkExtraBundle(),
- new JMSSecurityExtraBundle(),
- );
- $bundles = array_map(function($v) {
- return $v->getPath();
- }, $bundles);
-
- $bundles[] = __DIR__.'/../';
-
- $time = microtime(true);
- for ($i=0,$c=5; $i<$c; $i++) {
- $ref->invoke($finder, $bundles);
- }
- $time = microtime(true) - $time;
- $this->printResults('service finder ('.$method.')', $time, $c);
- }
-
- public function getFinderMethods()
- {
- return array(
- array('findUsingGrep'),
- array('findUsingFinder'),
- );
- }
-
- private function printResults($test, $time, $iterations)
- {
- if (0 == $iterations) {
- throw new InvalidArgumentException('$iterations cannot be zero.');
- }
-
- $title = $test." results:\n";
- $iterationsText = sprintf("Iterations: %d\n", $iterations);
- $totalTime = sprintf("Total Time: %.3f s\n", $time);
- $iterationTime = sprintf("Time per iteration: %.3f ms\n", $time/$iterations * 1000);
-
- $max = max(strlen($title), strlen($iterationTime)) - 1;
-
- echo "\n".str_repeat('-', $max)."\n";
- echo $title;
- echo str_repeat('=', $max)."\n";
- echo $iterationsText;
- echo $totalTime;
- echo $iterationTime;
- echo str_repeat('-', $max)."\n";
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-// this file searches for the autoload file of your project, and includes it
-$dir = __DIR__;
-$lastDir = null;
-while (($dir = dirname($dir)) && $dir !== $lastDir) {
- $lastDir = $dir;
-
- if (file_exists($file = $dir.'/app/bootstrap.php.cache')) {
- require_once $file;
- return;
- }
-}
-
-throw new RuntimeException('Could not locate the project\'s bootstrap.php.cache. If your bundle is not inside a project, you need to replace this bootstrap file.');
\ No newline at end of file
+++ /dev/null
-{
- "name": "jms/di-extra-bundle",
- "description": "Allows to configure dependency injection using annotations",
- "keywords": ["annotations","dependency injection"],
- "type": "symfony-bundle",
- "license": "Apache",
- "authors": [
- {
- "name": "Johannes M. Schmitt",
- "email": "schmittjoh@gmail.com"
- }
- ],
- "require": {
- "symfony/framework-bundle": "2.*",
- "jms/metadata": "1.1.*"
- },
- "autoload": {
- "psr-0": { "JMS\\DiExtraBundle": "" }
- },
- "target-dir": "JMS/DiExtraBundle"
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-\r
-<phpunit backupGlobals="false"\r
- backupStaticAttributes="false"\r
- colors="true"\r
- convertErrorsToExceptions="true"\r
- convertNoticesToExceptions="true"\r
- convertWarningsToExceptions="true"\r
- processIsolation="false"\r
- stopOnFailure="false"\r
- syntaxCheck="false"\r
- bootstrap="./Tests/bootstrap.php"\r
->\r
- \r
- <testsuites>\r
- <testsuite name="DiExtraBundle Test Suite">\r
- <directory>./Tests</directory>\r
- </testsuite>\r
- </testsuites>\r
- \r
- <groups>\r
- <exclude>\r
- <group>performance</group>\r
- </exclude>\r
- </groups>\r
-</phpunit>\r
+++ /dev/null
-CHANGELOG
-=========
-
-This changelog references all relevant changes:
-
-To get the diff between the two last versions, go to
-https://github.com/schmittjoh/metadata/compare/1.0.0...1.1.0
-
-* 1.1.0 (2011-10-04)
-
- * added support for metadata on interfaces
- * added support for non annotation-based drivers
- * added support for merging metadata
-
-This release is fully backwards compatible with the 1.0.0 release. Therefore,
-the 1.0.x branch has been discontinued.
-
-* 1.0.0 (2011-07-09)
+++ /dev/null
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
\ No newline at end of file
+++ /dev/null
-Metadata is a library for class/method/property metadata management in PHP
-==========================================================================
-
-Overview
---------
-
-This library provides some commonly needed base classes for managing metadata
-for classes, methods and properties. The metadata can come from many different
-sources (annotations, YAML/XML/PHP configuration files).
-
-The metadata classes are used to abstract away that source and provide a common
-interface for all of them.
-
-Usage
------
-
-The library provides three classes that you can extend to add your application
-specific properties, and flags: ``ClassMetadata``, ``MethodMetadata``, and
-``PropertyMetadata``
-
-After you have added, your properties in sub-classes, you also need to add
-``DriverInterface`` implementations which know how to populate these classes
-from the different metadata sources.
-
-Finally, you can use the ``MetadataFactory`` to retrieve the metadata::
-
- <?php
-
- use Metadata\MetadataFactory;
- use Metadata\Driver\DriverChain;
-
- $driver = new DriverChain(array(
- /** Annotation, YAML, XML, PHP, ... drivers */
- ));
- $factory = new MetadataFactory($driver);
- $metadata = $factory->getMetadataForClass('MyNamespace\MyObject');
-
+++ /dev/null
-{
- "name": "jms/metadata",
- "description": "Class/method/property metadata management in PHP",
- "keywords": ["annotations","metadata","yaml","xml"],
- "type": "library",
- "license": "Apache",
- "authors": [
- {
- "name": "Johannes M. Schmitt",
- "email": "schmittjoh@gmail.com"
- }
- ],
- "require": {
- "php": ">=5.3.0"
- },
- "autoload": {
- "psr-0": { "Metadata\\": "src/" }
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-
-<phpunit backupGlobals="false"
- backupStaticAttributes="false"
- colors="true"
- convertErrorsToExceptions="true"
- convertNoticesToExceptions="true"
- convertWarningsToExceptions="true"
- processIsolation="false"
- stopOnFailure="false"
- syntaxCheck="false"
- bootstrap="tests/bootstrap.php"
->
- <testsuites>
- <testsuite name="Metadata Test Suite">
- <directory>./tests/Metadata/</directory>
- </testsuite>
- </testsuites>
-
- <groups>
- <exclude>
- <group>performance</group>
- </exclude>
- </groups>
-</phpunit>
+++ /dev/null
-<?php
-
-namespace Metadata\Cache;
-
-use Metadata\ClassMetadata;
-
-interface CacheInterface
-{
- /**
- * Loads a class metadata instance from the cache
- *
- * @param \ReflectionClass $class
- *
- * @return ClassMetadata
- */
- function loadClassMetadataFromCache(\ReflectionClass $class);
-
- /**
- * Puts a class metadata instance into the cache
- *
- * @param ClassMetadata $metadata
- *
- * @return void
- */
- function putClassMetadataInCache(ClassMetadata $metadata);
-
- /**
- * Evicts the class metadata for the given class from the cache.
- *
- * @param \ReflectionClass $class
- *
- * @return void
- */
- function evictClassMetadataFromCache(\ReflectionClass $class);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Cache;
-
-use Metadata\ClassMetadata;
-
-class FileCache implements CacheInterface
-{
- private $dir;
-
- public function __construct($dir)
- {
- if (!is_dir($dir)) {
- throw new \InvalidArgumentException(sprintf('The directory "%s" does not exist.', $dir));
- }
- if (!is_writable($dir)) {
- throw new \InvalidArgumentException(sprintf('The directory "%s" is not writable.', $dir));
- }
-
- $this->dir = rtrim($dir, '\\/');
- }
-
- public function loadClassMetadataFromCache(\ReflectionClass $class)
- {
- $path = $this->dir.'/'.strtr($class->getName(), '\\', '-').'.cache.php';
- if (!file_exists($path)) {
- return null;
- }
-
- return include $path;
- }
-
- public function putClassMetadataInCache(ClassMetadata $metadata)
- {
- $path = $this->dir.'/'.strtr($metadata->name, '\\', '-').'.cache.php';
- file_put_contents($path, '<?php return unserialize('.var_export(serialize($metadata), true).');');
- }
-
- public function evictClassMetadataFromCache(\ReflectionClass $class)
- {
- $path = $this->dir.'/'.strtr($class->getName(), '\\', '-').'.cache.php';
- if (file_exists($path)) {
- unlink($path);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace Metadata;
-
-/**
- * Represents the metadata for the entire class hierarchy.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class ClassHierarchyMetadata
-{
- public $classMetadata = array();
-
- public function addClassMetadata(ClassMetadata $metadata)
- {
- $this->classMetadata[$metadata->name] = $metadata;
- }
-
- public function getRootClassMetadata()
- {
- return reset($this->classMetadata);
- }
-
- public function getOutsideClassMetadata()
- {
- return end($this->classMetadata);
- }
-
- public function isFresh($timestamp)
- {
- foreach ($this->classMetadata as $metadata) {
- if (!$metadata->isFresh($timestamp)) {
- return false;
- }
- }
-
- return true;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace Metadata;
-
-/**
- * Base class for class metadata.
- *
- * This class is intended to be extended to add your own application specific
- * properties, and flags.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class ClassMetadata implements \Serializable
-{
- public $name;
- public $reflection;
- public $methodMetadata = array();
- public $propertyMetadata = array();
- public $fileResources = array();
- public $createdAt;
-
- public function __construct($name)
- {
- $this->name = $name;
-
- $this->reflection = new \ReflectionClass($name);
- $this->createdAt = time();
- }
-
- public function addMethodMetadata(MethodMetadata $metadata)
- {
- $this->methodMetadata[$metadata->name] = $metadata;
- }
-
- public function addPropertyMetadata(PropertyMetadata $metadata)
- {
- $this->propertyMetadata[$metadata->name] = $metadata;
- }
-
- public function isFresh($timestamp = null)
- {
- if (null === $timestamp) {
- $timestamp = $this->createdAt;
- }
-
- foreach ($this->fileResources as $filepath) {
- if (!file_exists($filepath)) {
- return false;
- }
-
- if ($timestamp < filemtime($filepath)) {
- return false;
- }
- }
-
- return true;
- }
-
- public function serialize()
- {
- return serialize(array(
- $this->name,
- $this->methodMetadata,
- $this->propertyMetadata,
- $this->fileResources,
- $this->createdAt,
- ));
- }
-
- public function unserialize($str)
- {
- list(
- $this->name,
- $this->methodMetadata,
- $this->propertyMetadata,
- $this->fileResources,
- $this->createdAt
- ) = unserialize($str);
-
- $this->reflection = new \ReflectionClass($this->name);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Driver;
-
-/**
- * Base file driver implementation.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-abstract class AbstractFileDriver implements DriverInterface
-{
- private $locator;
-
- public function __construct(FileLocatorInterface $locator)
- {
- $this->locator = $locator;
- }
-
- public function loadMetadataForClass(\ReflectionClass $class)
- {
- if (null === $path = $this->locator->findFileForClass($class, $this->getExtension())) {
- return null;
- }
-
- return $this->loadMetadataFromFile($class, $path);
- }
-
- /**
- * Parses the content of the file, and converts it to the desired metadata.
- *
- * @param string $file
- * @return ClassMetadata|null
- */
- abstract protected function loadMetadataFromFile(\ReflectionClass $class, $file);
-
- /**
- * Returns the extension of the file.
- *
- * @return string
- */
- abstract protected function getExtension();
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace Metadata\Driver;
-
-final class DriverChain implements DriverInterface
-{
- private $drivers;
-
- public function __construct(array $drivers)
- {
- $this->drivers = $drivers;
- }
-
- public function loadMetadataForClass(\ReflectionClass $class)
- {
- foreach ($this->drivers as $driver) {
- if (null !== $metadata = $driver->loadMetadataForClass($class)) {
- return $metadata;
- }
- }
-
- return null;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace Metadata\Driver;
-
-interface DriverInterface
-{
- function loadMetadataForClass(\ReflectionClass $class);
-}
+++ /dev/null
-<?php
-
-namespace Metadata\Driver;
-
-class FileLocator implements FileLocatorInterface
-{
- private $dirs;
-
- public function __construct(array $dirs)
- {
- $this->dirs = $dirs;
- }
-
- public function findFileForClass(\ReflectionClass $class, $extension)
- {
- foreach ($this->dirs as $prefix => $dir) {
- if (0 !== strpos($class->getNamespaceName(), $prefix)) {
- continue;
- }
-
- $path = $dir.'/'.str_replace('\\', '.', substr($class->getName(), strlen($prefix)+1)).'.'.$extension;
- if (file_exists($path)) {
- return $path;
- }
- }
-
- return null;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Driver;
-
-interface FileLocatorInterface
-{
- function findFileForClass(\ReflectionClass $class, $extension);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Driver;
-
-use Symfony\Component\DependencyInjection\ContainerInterface;
-
-class LazyLoadingDriver implements DriverInterface
-{
- private $container;
- private $realDriverId;
-
- public function __construct(ContainerInterface $container, $realDriverId)
- {
- $this->container = $container;
- $this->realDriverId = $realDriverId;
- }
-
- public function loadMetadataForClass(\ReflectionClass $class)
- {
- return $this->container->get($this->realDriverId)->loadMetadataForClass($class);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata;
-
-class MergeableClassMetadata extends ClassMetadata implements MergeableInterface
-{
- public function merge(MergeableInterface $object)
- {
- if (!$object instanceof MergeableClassMetadata) {
- throw new \InvalidArgumentException('$object must be an instance of MergeableClassMetadata.');
- }
-
- $this->name = $object->name;
- $this->reflection = $object->reflection;
- $this->methodMetadata = array_merge($this->methodMetadata, $object->methodMetadata);
- $this->propertyMetadata = array_merge($this->propertyMetadata, $object->propertyMetadata);
- $this->fileResources = array_merge($this->fileResources, $object->fileResources);
-
- if ($object->createdAt < $this->createdAt) {
- $this->createdAt = $object->createdAt;
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata;
-
-interface MergeableInterface
-{
- function merge(MergeableInterface $object);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace Metadata;
-
-use Metadata\Driver\DriverInterface;
-use Metadata\Cache\CacheInterface;
-
-final class MetadataFactory implements MetadataFactoryInterface
-{
- private $driver;
- private $cache;
- private $loadedMetadata = array();
- private $loadedClassMetadata = array();
- private $hierarchyMetadataClass;
- private $includeInterfaces = false;
- private $debug;
-
- public function __construct(DriverInterface $driver, $hierarchyMetadataClass = 'Metadata\ClassHierarchyMetadata', $debug = false)
- {
- $this->driver = $driver;
- $this->hierarchyMetadataClass = $hierarchyMetadataClass;
- $this->debug = $debug;
- }
-
- public function setIncludeInterfaces($bool)
- {
- $this->includeInterfaces = (Boolean) $bool;
- }
-
- public function setCache(CacheInterface $cache)
- {
- $this->cache = $cache;
- }
-
- public function getMetadataForClass($className)
- {
- if (isset($this->loadedMetadata[$className])) {
- return $this->loadedMetadata[$className];
- }
-
- $metadata = null;
- foreach ($this->getClassHierarchy($className) as $class) {
- if (isset($this->loadedClassMetadata[$name = $class->getName()])) {
- $this->addClassMetadata($metadata, $this->loadedClassMetadata[$name]);
- continue;
- }
-
- // check the cache
- if (null !== $this->cache
- && (null !== $classMetadata = $this->cache->loadClassMetadataFromCache($class))) {
- if ($this->debug && !$classMetadata->isFresh()) {
- $this->cache->evictClassMetadataFromCache($classMetadata->reflection);
- } else {
- $this->loadedClassMetadata[$name] = $classMetadata;
- $this->addClassMetadata($metadata, $classMetadata);
- continue;
- }
- }
-
- // load from source
- if (null !== $classMetadata = $this->driver->loadMetadataForClass($class)) {
- $this->loadedClassMetadata[$name] = $classMetadata;
- $this->addClassMetadata($metadata, $classMetadata);
-
- if (null !== $this->cache) {
- $this->cache->putClassMetadataInCache($classMetadata);
- }
-
- continue;
- }
- }
-
- return $this->loadedMetadata[$className] = $metadata;
- }
-
- private function addClassMetadata(&$metadata, $toAdd)
- {
- if ($toAdd instanceof MergeableInterface) {
- if (null === $metadata) {
- $metadata = clone $toAdd;
- } else {
- $metadata->merge($toAdd);
- }
- } else {
- if (null === $metadata) {
- $metadata = new $this->hierarchyMetadataClass;
- }
-
- $metadata->addClassMetadata($toAdd);
- }
- }
-
- private function getClassHierarchy($class)
- {
- $classes = array();
- $refl = new \ReflectionClass($class);
-
- do {
- $classes[] = $refl;
- } while (false !== $refl = $refl->getParentClass());
-
- $classes = array_reverse($classes, false);
-
- if (!$this->includeInterfaces) {
- return $classes;
- }
-
- $addedInterfaces = array();
- $newHierarchy = array();
-
- foreach ($classes as $class) {
- foreach ($class->getInterfaces() as $interface) {
- if (isset($addedInterfaces[$interface->getName()])) {
- continue;
- }
- $addedInterfaces[$interface->getName()] = true;
-
- $newHierarchy[] = $interface;
- }
-
- $newHierarchy[] = $class;
- }
-
- return $newHierarchy;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace Metadata;
-
-interface MetadataFactoryInterface
-{
- function getMetadataForClass($className);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace Metadata;
-
-/**
- * Base class for method metadata.
- *
- * This class is intended to be extended to add your application specific
- * properties, and flags.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class MethodMetadata implements \Serializable
-{
- public $class;
- public $name;
- public $reflection;
-
- public function __construct($class, $name)
- {
- $this->class = $class;
- $this->name = $name;
-
- $this->reflection = new \ReflectionMethod($class, $name);
- $this->reflection->setAccessible(true);
- }
-
- public function invoke($obj, array $args = array())
- {
- return $this->reflection->invokeArgs($obj, $args);
- }
-
- public function serialize()
- {
- return serialize(array($this->class, $this->name));
- }
-
- public function unserialize($str)
- {
- list($this->class, $this->name) = unserialize($str);
-
- $this->reflection = new \ReflectionMethod($this->class, $this->name);
- $this->reflection->setAccessible(true);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace Metadata;
-
-/**
- * Base class for property metadata.
- *
- * This class is intended to be extended to add your application specific
- * properties, and flags.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class PropertyMetadata implements \Serializable
-{
- public $class;
- public $name;
- public $reflection;
-
- public function __construct($class, $name)
- {
- $this->class = $class;
- $this->name = $name;
-
- $this->reflection = new \ReflectionProperty($class, $name);
- $this->reflection->setAccessible(true);
- }
-
- public function getValue($obj)
- {
- return $this->reflection->getValue($obj);
- }
-
- public function setValue($obj, $value)
- {
- $this->reflection->setValue($obj, $value);
- }
-
- public function serialize()
- {
- return serialize(array(
- $this->class,
- $this->name,
- ));
- }
-
- public function unserialize($str)
- {
- list($this->class, $this->name) = unserialize($str);
-
- $this->reflection = new \ReflectionProperty($this->class, $this->name);
- $this->reflection->setAccessible(true);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace Metadata;
-
-final class Version
-{
- const VERSION = '1.1.1';
-}
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Cache;
-
-use Metadata\ClassMetadata;
-
-use Metadata\Cache\FileCache;
-
-class FileCacheTest extends \PHPUnit_Framework_TestCase
-{
- public function testLoadEvictPutClassMetadataFromInCache()
- {
- $cache = new FileCache(sys_get_temp_dir());
-
- $this->assertNull($cache->loadClassMetadataFromCache($refl = new \ReflectionClass('Metadata\Tests\Fixtures\TestObject')));
- $cache->putClassMetadataInCache($metadata = new ClassMetadata('Metadata\Tests\Fixtures\TestObject'));
-
- $this->assertEquals($metadata, $cache->loadClassMetadataFromCache($refl));
-
- $cache->evictClassMetadataFromCache($refl);
- $this->assertNull($cache->loadClassMetadataFromCache($refl));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests;
-
-use Metadata\ClassMetadata;
-
-class ClassMetadataTest extends \PHPUnit_Framework_TestCase
-{
- public function testConstructor()
- {
- $metadata = new ClassMetadata('Metadata\Tests\Fixtures\TestObject');
-
- $this->assertEquals('Metadata\Tests\Fixtures\TestObject', $metadata->name);
- $this->assertEquals('Metadata\Tests\Fixtures\TestObject', $metadata->reflection->getName());
- }
-
- public function testSerializeUnserialize()
- {
- $metadata = new ClassMetadata('Metadata\Tests\Fixtures\TestObject');
-
- $this->assertEquals($metadata, unserialize(serialize($metadata)));
- }
-
- public function testIsFresh()
- {
- $ref = new \ReflectionClass('Metadata\Tests\Fixtures\TestObject');
- touch($ref->getFilename());
- sleep(2);
-
- $metadata = new ClassMetadata($ref->getName());
- $metadata->fileResources[] = $ref->getFilename();
- $this->assertTrue($metadata->isFresh());
-
- sleep(2);
- clearstatcache($ref->getFilename());
- touch($ref->getFilename());
- $this->assertFalse($metadata->isFresh());
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Driver;
-
-use Metadata\ClassMetadata;
-use Metadata\Driver\DriverChain;
-
-class DriverChainTest extends \PHPUnit_Framework_TestCase
-{
- public function testLoadMetadataForClass()
- {
- $driver = $this->getMock('Metadata\\Driver\\DriverInterface');
- $driver
- ->expects($this->once())
- ->method('loadMetadataForClass')
- ->will($this->returnValue($metadata = new ClassMetadata('\stdClass')))
- ;
- $chain = new DriverChain(array($driver));
-
- $this->assertSame($metadata, $chain->loadMetadataForClass(new \ReflectionClass('\stdClass')));
- }
-
- public function testLoadMetadataForClassReturnsNullWhenNoMetadataIsFound()
- {
- $driver = new DriverChain(array());
- $this->assertNull($driver->loadMetadataForClass(new \ReflectionClass('\stdClass')));
-
- $driver = $this->getMock('Metadata\\Driver\\DriverInterface');
- $driver
- ->expects($this->once())
- ->method('loadMetadataForClass')
- ->will($this->returnValue(null))
- ;
- $driverChain = new DriverChain(array($driver));
- $this->assertNull($driver->loadMetadataForClass(new \ReflectionClass('\stdClass')));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Driver;
-
-use Metadata\Driver\FileLocator;
-
-class FileLocatorTest extends \PHPUnit_Framework_TestCase
-{
- public function testFindFileForClass()
- {
- $locator = new FileLocator(array(
- 'Metadata\Tests\Driver\Fixture\A' => __DIR__.'/Fixture/A',
- 'Metadata\Tests\Driver\Fixture\B' => __DIR__.'/Fixture/B',
- 'Metadata\Tests\Driver\Fixture\C' => __DIR__.'/Fixture/C',
- ));
-
- $ref = new \ReflectionClass('Metadata\Tests\Driver\Fixture\A\A');
- $this->assertEquals(realpath(__DIR__.'/Fixture/A/A.xml'), realpath($locator->findFileForClass($ref, 'xml')));
-
- $ref = new \ReflectionClass('Metadata\Tests\Driver\Fixture\B\B');
- $this->assertNull($locator->findFileForClass($ref, 'xml'));
-
- $ref = new \ReflectionClass('Metadata\Tests\Driver\Fixture\C\SubDir\C');
- $this->assertEquals(realpath(__DIR__.'/Fixture/C/SubDir.C.yml'), realpath($locator->findFileForClass($ref, 'yml')));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Driver\Fixture\A;
-
-class A {}
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Driver\Fixture\B;
-
-class B { }
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Driver\Fixture\C\SubDir;
-
-class C { }
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Fixtures\ComplexHierarchy;
-
-abstract class BaseClass implements InterfaceA
-{
- private $foo;
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Fixtures\ComplexHierarchy;
-
-interface InterfaceA
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Fixtures\ComplexHierarchy;
-
-interface InterfaceB
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Fixtures\ComplexHierarchy;
-
-class SubClassA extends BaseClass implements InterfaceA, InterfaceB
-{
- private $bar;
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Fixtures\ComplexHierarchy;
-
-class SubClassB extends BaseClass
-{
- private $baz;
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Fixtures;
-
-class TestObject
-{
- private $foo;
-
- public function getFoo()
- {
- return $this->foo;
- }
-
- private function setFoo($foo)
- {
- $this->foo = $foo;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests\Fixtures;
-
-class TestParent extends TestObject
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests;
-
-use Metadata\MergeableClassMetadata;
-use Metadata\ClassMetadata;
-
-class MergeableClassMetadataTest extends \PHPUnit_Framework_TestCase
-{
- public function testMerge()
- {
- $parentMetadata = new MergeableClassMetadata('Metadata\Tests\Fixtures\TestParent');
- $parentMetadata->propertyMetadata['foo'] = 'bar';
- $parentMetadata->propertyMetadata['baz'] = 'baz';
- $parentMetadata->methodMetadata['foo'] = 'bar';
- $parentMetadata->createdAt = 2;
- $parentMetadata->fileResources[] = 'foo';
-
- $childMetadata = new MergeableClassMetadata('Metadata\Tests\Fixtures\TestObject');
- $childMetadata->propertyMetadata['foo'] = 'baz';
- $childMetadata->methodMetadata['foo'] = 'baz';
- $childMetadata->createdAt = 1;
- $childMetadata->fileResources[] = 'bar';
-
- $parentMetadata->merge($childMetadata);
- $this->assertEquals('Metadata\Tests\Fixtures\TestObject', $parentMetadata->name);
- $this->assertEquals('Metadata\Tests\Fixtures\TestObject', $parentMetadata->reflection->getName());
- $this->assertEquals(array('foo' => 'baz', 'baz' => 'baz',), $parentMetadata->propertyMetadata);
- $this->assertEquals(array('foo' => 'baz',), $parentMetadata->methodMetadata);
- $this->assertEquals(1, $parentMetadata->createdAt);
- $this->assertEquals(array('foo', 'bar'), $parentMetadata->fileResources);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests;
-
-use Metadata\PropertyMetadata;
-
-use Metadata\MergeableClassMetadata;
-
-use Metadata\ClassMetadata;
-use Metadata\MetadataFactory;
-
-class MetadataFactoryTest extends \PHPUnit_Framework_TestCase
-{
- public function testGetMetadataForClass()
- {
- $driver = $this->getMock('Metadata\Driver\DriverInterface');
-
- $driver
- ->expects($this->at(0))
- ->method('loadMetadataForClass')
- ->with($this->equalTo(new \ReflectionClass('Metadata\Tests\Fixtures\TestObject')))
- ->will($this->returnCallback(function($class) {
- return new ClassMetadata($class->getName());
- }))
- ;
- $driver
- ->expects($this->at(1))
- ->method('loadMetadataForClass')
- ->with($this->equalTo(new \ReflectionClass('Metadata\Tests\Fixtures\TestParent')))
- ->will($this->returnCallback(function($class) {
- return new ClassMetadata($class->getName());
- }))
- ;
-
- $factory = new MetadataFactory($driver);
- $metadata = $factory->getMetadataForClass('Metadata\Tests\Fixtures\TestParent');
-
- $this->assertInstanceOf('Metadata\ClassHierarchyMetadata', $metadata);
- $this->assertEquals(2, count($metadata->classMetadata));
- }
-
- public function testGetMetadataForClassWhenMergeable()
- {
- $driver = $this->getMock('Metadata\Driver\DriverInterface');
-
- $driver
- ->expects($this->at(0))
- ->method('loadMetadataForClass')
- ->with($this->equalTo(new \ReflectionClass('Metadata\Tests\Fixtures\TestObject')))
- ->will($this->returnCallback(function($class) {
- return new MergeableClassMetadata($class->getName());
- }))
- ;
- $driver
- ->expects($this->at(1))
- ->method('loadMetadataForClass')
- ->with($this->equalTo(new \ReflectionClass('Metadata\Tests\Fixtures\TestParent')))
- ->will($this->returnCallback(function($class) {
- return new MergeableClassMetadata($class->getName());
- }))
- ;
-
- $factory = new MetadataFactory($driver);
- $metadata = $factory->getMetadataForClass('Metadata\Tests\Fixtures\TestParent');
-
- $this->assertInstanceOf('Metadata\MergeableClassMetadata', $metadata);
- $this->assertEquals('Metadata\Tests\Fixtures\TestParent', $metadata->name);
- }
-
- public function testGetMetadataWithComplexHierarchy()
- {
- $driver = $this->getMock('Metadata\Driver\DriverInterface');
-
- $driver
- ->expects($this->any())
- ->method('loadMetadataForClass')
- ->will($this->returnCallback(function($class) {
- $metadata = new MergeableClassMetadata($class->name);
-
- switch ($class->name) {
- case 'Metadata\Tests\Fixtures\ComplexHierarchy\BaseClass':
- $metadata->propertyMetadata['foo'] = new PropertyMetadata($class->name, 'foo');
- break;
-
- case 'Metadata\Tests\Fixtures\ComplexHierarchy\SubClassA':
- $metadata->propertyMetadata['bar'] = new PropertyMetadata($class->name, 'bar');
- break;
-
- case 'Metadata\Tests\Fixtures\ComplexHierarchy\SubClassB':
- $metadata->propertyMetadata['baz'] = new PropertyMetadata($class->name, 'baz');
- break;
-
- default:
- throw new \RuntimeException(sprintf('Unsupported class "%s".', $class->name));
- }
-
- return $metadata;
- }))
- ;
-
- $factory = new MetadataFactory($driver);
-
- $subClassA = $factory->getMetadataForClass('Metadata\Tests\Fixtures\ComplexHierarchy\SubClassA');
- $this->assertInstanceOf('Metadata\MergeableClassMetadata', $subClassA);
- $this->assertEquals(array('foo', 'bar'), array_keys($subClassA->propertyMetadata));
-
- $subClassB = $factory->getMetadataForClass('Metadata\Tests\Fixtures\ComplexHierarchy\SubClassB');
- $this->assertInstanceOf('Metadata\MergeableClassMetadata', $subClassB);
- $this->assertEquals(array('foo', 'baz'), array_keys($subClassB->propertyMetadata));
- }
-
- public function testGetMetadataWithCache()
- {
- $driver = $this->getMock('Metadata\Driver\DriverInterface');
- $driver
- ->expects($this->once())
- ->method('loadMetadataForClass')
- ->will($this->returnValue($metadata = new ClassMetadata('Metadata\Tests\Fixtures\TestObject')))
- ;
-
- $factory = new MetadataFactory($driver);
-
- $cache = $this->getMock('Metadata\Cache\CacheInterface');
- $cache
- ->expects($this->once())
- ->method('loadClassMetadataFromCache')
- ->with($this->equalTo(new \ReflectionClass('Metadata\Tests\Fixtures\TestObject')))
- ->will($this->returnValue(null))
- ;
- $cache
- ->expects($this->once())
- ->method('putClassMetadataInCache')
- ->with($this->equalTo($metadata))
- ;
- $factory->setCache($cache);
-
- $this->assertSame($metadata, reset($factory->getMetadataForClass('Metadata\Tests\Fixtures\TestObject')->classMetadata));
- }
-
- public function testGetMetadataReturnsNullIfNoMetadataIsFound()
- {
- $driver = $this->getMock('Metadata\Driver\DriverInterface');
- $driver
- ->expects($this->once())
- ->method('loadMetadataForClass')
- ->will($this->returnValue(null))
- ;
-
- $factory = new MetadataFactory($driver);
-
- $this->assertNull($factory->getMetadataForClass('stdClass'));
- }
-
- public function testGetMetadataWithInterfaces()
- {
- $driver = $this->getMock('Metadata\Driver\DriverInterface');
-
- $driver
- ->expects($this->at(3))
- ->method('loadMetadataForClass')
- ->with($this->equalTo(new \ReflectionClass('Metadata\Tests\Fixtures\ComplexHierarchy\SubClassA')))
- ;
- $driver
- ->expects($this->at(2))
- ->method('loadMetadataForClass')
- ->with($this->equalTo(new \ReflectionClass('Metadata\Tests\Fixtures\ComplexHierarchy\InterfaceB')))
- ;
- $driver
- ->expects($this->at(1))
- ->method('loadMetadataForClass')
- ->with($this->equalTo(new \ReflectionClass('Metadata\Tests\Fixtures\ComplexHierarchy\BaseClass')))
- ;
- $driver
- ->expects($this->at(0))
- ->method('loadMetadataForClass')
- ->with($this->equalTo(new \ReflectionClass('Metadata\Tests\Fixtures\ComplexHierarchy\InterfaceA')))
- ;
-
- $factory = new MetadataFactory($driver);
- $factory->setIncludeInterfaces(true);
-
- $factory->getMetadataForClass('Metadata\Tests\Fixtures\ComplexHierarchy\SubClassA');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests;
-
-use Metadata\Tests\Fixtures\TestObject;
-
-use Metadata\MethodMetadata;
-
-class MethodMetadataTest extends \PHPUnit_Framework_TestCase
-{
- public function testConstructor()
- {
- $metadata = new MethodMetadata('Metadata\Tests\Fixtures\TestObject', 'setFoo');
-
- $this->assertEquals('Metadata\Tests\Fixtures\TestObject', $metadata->class);
- $this->assertEquals('setFoo', $metadata->name);
- $this->assertEquals(new \ReflectionMethod('Metadata\Tests\Fixtures\TestObject', 'setFoo'), $metadata->reflection);
- }
-
- public function testSerializeUnserialize()
- {
- $metadata = new MethodMetadata('Metadata\Tests\Fixtures\TestObject', 'setFoo');
-
- $this->assertEquals($metadata, unserialize(serialize($metadata)));
- }
-
- public function testInvoke()
- {
- $obj = new TestObject();
- $metadata = new MethodMetadata('Metadata\Tests\Fixtures\TestObject', 'setFoo');
-
- $this->assertNull($obj->getFoo());
- $metadata->invoke($obj, array('foo'));
- $this->assertEquals('foo', $obj->getFoo());
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace Metadata\Tests;
-
-use Metadata\Tests\Fixtures\TestObject;
-
-use Metadata\PropertyMetadata;
-
-class PropertyMetadataTest extends \PHPUnit_Framework_TestCase
-{
- public function testConstructor()
- {
- $metadata = new PropertyMetadata('Metadata\Tests\Fixtures\TestObject', 'foo');
-
- $this->assertEquals('Metadata\Tests\Fixtures\TestObject', $metadata->class);
- $this->assertEquals('foo', $metadata->name);
- $this->assertEquals(new \ReflectionProperty('Metadata\Tests\Fixtures\TestObject', 'foo'), $metadata->reflection);
- }
-
- public function testSerializeUnserialize()
- {
- $metadata = new PropertyMetadata('Metadata\Tests\Fixtures\TestObject', 'foo');
-
- $this->assertEquals($metadata, unserialize(serialize($metadata)));
- }
-
- public function testSetGetValue()
- {
- $obj = new TestObject();
- $metadata = new PropertyMetadata('Metadata\Tests\Fixtures\TestObject', 'foo');
-
- $this->assertNull($metadata->getValue($obj));
- $metadata->setValue($obj, 'foo');
- $this->assertEquals('foo', $metadata->getValue($obj));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * This file is part of the Metadata library.
- *
- * (C) 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- */
-
-spl_autoload_register(function($class)
-{
- if (0 === strpos($class, 'Metadata\Tests\\')) {
- $path = __DIR__.'/../tests/'.strtr($class, '\\', '/').'.php';
- if (file_exists($path) && is_readable($path)) {
- require_once $path;
-
- return true;
- }
- } else if (0 === strpos($class, 'Metadata\\')) {
- $path = __DIR__.'/../src/'.($class = strtr($class, '\\', '/')).'.php';
- if (file_exists($path) && is_readable($path)) {
- require_once $path;
-
- return true;
- }
- } else if (0 === strpos($class, 'Symfony\\')) {
- $path = __DIR__.'/../../symfony/src/'.strtr($class, '\\', '/').'.php';
-
- if (file_exists($path) && is_readable($path)) {
- require_once $path;
-
- return true;
- }
- }
-});
-
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Annotation;
-
-use JMS\SecurityExtraBundle\Exception\InvalidArgumentException;
-
-/**
- * Annotation for expression-based access control.
- *
- * @Annotation
- * @Target("METHOD")
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-final class PreAuthorize
-{
- /**
- * @Required
- * @var string
- */
- public $expr;
-
- public function __construct()
- {
- if (0 === func_num_args()) {
- return;
- }
- $values = func_get_arg(0);
-
- if (isset($values['value'])) {
- $values['expr'] = $values['value'];
- }
- if (!isset($values['expr'])) {
- throw new InvalidArgumentException('The "expr" attribute must be set for annotation @PreAuthorize.');
- }
-
- if (!is_string($values['expr'])) {
- throw new InvalidArgumentException(sprintf('The "expr" attribute of annotation @PreAuthorize must be a string, but got "%s".', gettype($values['expr'])));
- }
-
- $this->expr = $values['expr'];
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Annotation;
-
-use JMS\SecurityExtraBundle\Exception\InvalidArgumentException;
-
-/**
- * @Annotation
- * @Target("METHOD")
- */
-final class RunAs
-{
- public $roles;
-
- public function __construct(array $values)
- {
- if (isset($values['value'])) {
- $values['roles'] = $values['value'];
- }
- if (!isset($values['roles'])) {
- throw new InvalidArgumentException('"roles" must be defined for RunAs annotation.');
- }
-
- $this->roles = array_map('trim', explode(',', $values['roles']));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Annotation;
-
-/**
- * This must be declared on classes which inherit from classes that have
- * requested method invocation securing capabilities.
- *
- * It indicates to the analyzer that the developer is aware of these security
- * restrictions, and has applied them to the root class in an appropriate
- * fashion.
- *
- * We cannot do this automatically without properly analyzing the control flow,
- * and in some cases it is not possible at all. See the following example:
- *
- * <code>
- * // child class
- * public function editComment($commentId)
- * {
- * // retrieve comment from database
- * $comment = $this->entityManager->find($commentId);
- *
- * return parent::editComment($comment);
- * }
- *
- * // base class which is inherited from
- * /**
- * * @SecureParam(name="comment", permissions="EDIT")
- * *\/
- * public function editComment(Comment $comment)
- * {
- * // do some supposedly secure action
- * }
- * <code>
- *
- * The above example can be rewritten so that we can apply security checks
- * automatically:
- *
- * <code>
- * // child class
- * public function editComment($commentId)
- * {
- * // retrieve comment from database
- * $comment = $this->entityManager->find($commentId);
- *
- * return $this->doEditComment($comment);
- * }
- *
- * // base class which is inherited from
- * /**
- * * @SecureParam(name="comment", permissions="EDIT")
- * *\/
- * protected function doEditComment(Comment $comment)
- * {
- * // do some secure action
- * }
- * </code>
- *
- * @Annotation
- * @Target("METHOD")
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-final class SatisfiesParentSecurityPolicy
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Annotation;
-
-use JMS\SecurityExtraBundle\Exception\InvalidArgumentException;
-
-/**
- * Represents a @Secure annotation.
- *
- * @Annotation
- * @Target("METHOD")
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-final class Secure
-{
- public $roles;
-
- public function __construct(array $values)
- {
- if (isset($values['value'])) {
- $values['roles'] = $values['value'];
- }
- if (!isset($values['roles'])) {
- throw new InvalidArgumentException('You must define a "roles" attribute for each Secure annotation.');
- }
-
- $this->roles = array_map('trim', explode(',', $values['roles']));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Annotation;
-
-use JMS\SecurityExtraBundle\Exception\InvalidArgumentException;
-
-/**
- * Represents a @SecureParam annotation.
- *
- * @Annotation
- * @Target("METHOD")
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-final class SecureParam
-{
- public $name;
- public $permissions;
-
- public function __construct(array $values)
- {
- if (!isset($values['name'])) {
- throw new InvalidArgumentException('You must define a "name" attribute for each SecureParam annotation.');
- }
- if (!isset($values['permissions'])) {
- throw new InvalidArgumentException('You must define a "permissions" attribute for each SecureParam annotation.');
- }
-
- $this->name = $values['name'];
-
- $this->permissions = array_map('trim', explode(',', $values['permissions']));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Annotation;
-
-use JMS\SecurityExtraBundle\Exception\InvalidArgumentException;
-
-/**
- * Represents a @SecureReturn annotation.
- *
- * @Annotation
- * @Target("METHOD")
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-final class SecureReturn
-{
- public $permissions;
-
- public function __construct(array $values)
- {
- if (isset($values['value'])) {
- $values['permissions'] = $values['value'];
- }
- if (!isset($values['permissions'])) {
- throw new InvalidArgumentException('You must define a "permissions" attribute for each SecureReturn annotation.');
- }
-
- $this->permissions = array_map('trim', explode(',', $values['permissions']));
- }
-}
\ No newline at end of file
+++ /dev/null
-This document details all changes from JMSSecurityExtraBundle 1.0.x to 1.1:
-
-- The configuration option "secure_controllers" has been removed. This setting is
- now automatically enabled, but it requires the JMSDiExtraBundle.
-
-- The dependencies of this bundle have changed:
-
- * The metadata library 1.1 version is now required instead of the 1.0 version
- (if you are using the Standard Edition, just change the "version=origin/1.0.x"
- line from your deps file to "version=1.1.0").
- * The JMSAopBundle is now required. For installation instructions, please see
- https://github.com/schmittjoh/JMSAopBundle
- * The JMSDiExtraBundle is now required if you want to secure your non-service
- controllers (if you only have service controllers, you don't need it). For
- installation instructions, see https://github.com/schmittjoh/JMSDiExtraBundle
-
-- The attribute "IS_IDDQD" has been renamed to "ROLE_IDDQD"
-
-- A powerful expression-based authorization language has been added which works
- in combination with the existing voting system. Since it is much more powerful
- than the built-in voters, and also much faster, you are highly encouraged to
- migrate your existing authorization rules to expressions, and eventually disable
- the built-in voters entirely. Some examples for how to convert simple attributes
- to their equivalent expressions are listed below:
-
- * IS_AUTHENTICATED_ANONYMOUSLY -> "permitAll"
- * IS_AUTHENTICATED_REMEMBERED -> "isAuthenticated()"
- * IS_AUTHENTICATED_FULLY -> "isFullyAuthenticated()"
- * ROLE_FOO -> "hasRole('ROLE_FOO')"
-
-- The ability to configure method access control (e.g. for controller actions)
- in the DI configuration has been added. Note that for non-service controllers
- the JMSDiExtraBundle is required.
-
-- The "is_expr_granted" Twig function has been added if you want to check an
- expression from a Twig template.
-
-
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\DependencyInjection;
-
-use Symfony\Component\Config\Definition\ConfigurationInterface;
-
-use Symfony\Component\HttpKernel\Kernel;
-
-use Symfony\Bundle\SecurityBundle\DependencyInjection\MainConfiguration as BaseConfiguration;
-use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AbstractFactory;
-use Symfony\Component\Config\Definition\Builder\TreeBuilder;
-use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
-
-/**
- * Enhances the access_control section configuration.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class AccessControlConfiguration implements ConfigurationInterface
-{
- /**
- * Generates the configuration tree builder.
- *
- * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
- */
- public function getConfigTreeBuilder()
- {
- $tb = new TreeBuilder();
- $rootNode = $tb->root('security');
-
- $rootNode
- ->ignoreExtraKeys()
- ->fixXmlConfig('rule', 'access_control')
- ->children()
- ->arrayNode('access_control')
- ->cannotBeOverwritten()
- ->prototype('array')
- ->fixXmlConfig('role')
- ->validate()
- ->always(function($v) {
- if (!empty($v['roles']) && isset($v['access'])) {
- throw new \Exception('"roles", and "access" cannot be set at the same time.');
- }
-
- if (empty($v['roles'])) {
- unset($v['roles']);
- }
-
- return $v;
- })
- ->end()
- ->children()
- ->scalarNode('requires_channel')->defaultNull()->end()
- ->scalarNode('path')->defaultNull()->end()
- ->scalarNode('host')->defaultNull()->end()
- ->scalarNode('ip')->defaultNull()->end()
- ->arrayNode('methods')
- ->beforeNormalization()->ifString()->then(function($v) { return preg_split('/\s*,\s*/', $v); })->end()
- ->prototype('scalar')->end()
- ->end()
- ->arrayNode('roles')
- ->beforeNormalization()->ifString()->then(function($v) { return preg_split('/\s*,\s*/', $v); })->end()
- ->prototype('scalar')->end()
- ->end()
- ->scalarNode('access')->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ;
-
- return $tb;
- }
-}
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\DependencyInjection\Compiler;
-
-use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Reference;
-
-/**
- * Collects after invocation providers.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class AddAfterInvocationProvidersPass implements CompilerPassInterface
-{
- public function process(ContainerBuilder $container)
- {
- if (!$container->hasDefinition('security.access.after_invocation_manager')) {
- return;
- }
-
- $providers = array();
- foreach (array_keys($container->findTaggedServiceIds('security.after_invocation.provider')) as $id) {
- if ('security.access.after_invocation.acl_provider' === $id && !$container->has('security.acl.provider')) {
- continue;
- }
-
- $providers[] = new Reference($id);
- }
-
- $container
- ->getDefinition('security.access.after_invocation_manager')
- ->setArguments(array($providers))
- ;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\DependencyInjection\Compiler;
-
-use JMS\SecurityExtraBundle\Exception\RuntimeException;
-use Symfony\Component\DependencyInjection\Reference;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
-
-class AddExpressionCompilersPass implements CompilerPassInterface
-{
- public function process(ContainerBuilder $container)
- {
- if (!$container->hasDefinition('security.expressions.compiler')) {
- return;
- }
-
- $compilerDef = $container->getDefinition('security.expressions.compiler');
- foreach ($container->findTaggedServiceIds('security.expressions.function_compiler')
- as $id => $attr) {
- $compilerDef->addMethodCall('addFunctionCompiler', array(new Reference($id)));
- }
-
- foreach ($container->findTaggedServiceIds('security.expressions.type_compiler')
- as $id => $attr) {
- $compilerDef->addMethodCall('addTypeCompiler', array(new Reference($id)));
- }
-
- $serviceMap = $parameterMap = array();
- foreach ($container->findTaggedServiceIds('security.expressions.variable') as $id => $attributes) {
- foreach ($attributes as $attr) {
- if (!isset($attr['variable']) || (!isset($attr['service']) && !isset($attr['parameter']))) {
- throw new RuntimeException(sprintf('"variable", and either "service" or "parameter" must be given for tag "security.expressions.variable" for service id "%s".', $id));
- }
-
- if (isset($attr['service'])) {
- $serviceMap[$attr['variable']] = $attr['service'];
- $container
- ->findDefinition($attr['service'])
- ->setPublic(true)
- ;
- } else {
- $parameterMap[$attr['variable']] = $attr['parameter'];
- }
- }
- }
- $container->getDefinition('security.expressions.variable_compiler')
- ->addMethodCall('setMaps', array($serviceMap, $parameterMap));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\DependencyInjection\Compiler;
-
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
-
-/**
- * Collects secured services.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class CollectSecuredServicesPass implements CompilerPassInterface
-{
- public function process(ContainerBuilder $container)
- {
- $securedClasses = array();
- foreach ($container->findTaggedServiceIds('security.secure_service') as $id => $attr) {
- $securedClasses[] = $container->getDefinition($id)->getClass();
- }
-
- $container
- ->getDefinition('security.access.pointcut')
- ->addMethodCall('setSecuredClasses', array($securedClasses))
- ;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\DependencyInjection\Compiler;
-
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
-
-class DisableVotersPass implements CompilerPassInterface
-{
- public function process(ContainerBuilder $container)
- {
- if ($container->getParameter('security.role_voter.disabled')) {
- $container->removeDefinition('security.access.role_hierarchy_voter');
- $container->removeDefinition('security.access.simple_role_voter');
- }
-
- if ($container->getParameter('security.authenticated_voter.disabled')) {
- $container->removeDefinition('security.access.authenticated_voter');
- }
-
- if ($container->hasDefinition('security.acl.voter.basic_permissions')) {
- if ($container->getParameter('security.acl_voter.disabled')) {
- $container->removeDefinition('security.acl.voter.basic_permissions');
- } else {
- $container->getDefinition('security.acl.voter.basic_permissions')
- ->setClass('JMS\SecurityExtraBundle\Security\Acl\Voter\AclVoter');
- }
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\DependencyInjection\Compiler;
-
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
-
-class IntegrationPass implements CompilerPassInterface
-{
- public function process(ContainerBuilder $container)
- {
- if (!$container->hasAlias('security.acl.provider')
- && !$container->hasDefinition('security.acl.provider')) {
- $container->removeDefinition('security.acl.permission_evaluator');
- }
-
- if ($container->hasDefinition('security.role_hierarchy')) {
- $container->getDefinition('security.role_hierarchy')
- ->setPublic(true);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\DependencyInjection;
-
-use Symfony\Component\Config\Definition\Builder\TreeBuilder;
-use Symfony\Component\Config\Definition\ConfigurationInterface;
-
-class Configuration implements ConfigurationInterface
-{
- public function getConfigTreeBuilder()
- {
- $tb = new TreeBuilder();
- $tb
- ->root('jms_security_extra')
- ->validate()
- ->always(function($v) {
- if ($v['method_access_control'] && !$v['expressions']) {
- throw new \Exception('You need to enable expressions if you want to configure method access via the DI config.');
- }
-
- return $v;
- })
- ->end()
- ->children()
- ->booleanNode('secure_all_services')->defaultFalse()->end()
- ->booleanNode('enable_iddqd_attribute')->defaultFalse()->end()
- ->scalarNode('cache_dir')->cannotBeEmpty()->defaultValue('%kernel.cache_dir%/jms_security')->end()
- ->booleanNode('expressions')->defaultFalse()->end()
- ->arrayNode('voters')
- ->addDefaultsIfNotSet()
- ->canBeUnset()
- ->children()
- ->booleanNode('disable_authenticated')->defaultFalse()->end()
- ->booleanNode('disable_role')->defaultFalse()->end()
- ->booleanNode('disable_acl')->defaultFalse()->end()
- ->end()
- ->end()
- ->arrayNode('method_access_control')
- ->useAttributeAsKey('pattern')
- ->prototype('scalar')->isRequired()->cannotBeEmpty()->end()
- ->end()
- ->end()
- ->end()
- ;
-
- return $tb;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\DependencyInjection;
-
-use Symfony\Component\DependencyInjection\Reference;
-
-use JMS\SecurityExtraBundle\Exception\RuntimeException;
-use Symfony\Component\HttpKernel\DependencyInjection\Extension;
-use Symfony\Component\Config\FileLocator;
-use Symfony\Component\Config\Definition\Processor;
-use Symfony\Component\Config\Definition\Builder\TreeBuilder;
-use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-
-/**
- * JMSSecurityExtraExtension.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class JMSSecurityExtraExtension extends Extension
-{
- public function load(array $configs, ContainerBuilder $container)
- {
- $bundles = $container->getParameter('kernel.bundles');
- if (!isset($bundles['JMSAopBundle'])) {
- throw new RuntimeException('The JMSSecurityExtraBundle requires the JMSAopBundle, please make sure to enable it in your AppKernel.');
- }
-
- $config = $this->processConfiguration(new Configuration(), $configs);
-
- $loader = new XmlFileLoader($container, new FileLocator(array(__DIR__.'/../Resources/config/')));
- $loader->load('services.xml');
-
- $container->setParameter('security.access.secure_all_services', $config['secure_all_services']);
-
- $cacheDir = $container->getParameterBag()->resolveValue($config['cache_dir']);
- if (!is_dir($cacheDir)) {
- if (false === @mkdir($cacheDir, 0777, true)) {
- throw new RuntimeException(sprintf('Could not create cache directory "%s".', $cacheDir));
- }
- }
- $container->setParameter('security.extra.cache_dir', $cacheDir);
-
- if ($config['expressions']) {
- $loader->load('security_expressions.xml');
-
- if (!is_dir($cacheDir.'/expressions')) {
- if (false === @mkdir($cacheDir.'/expressions', 0777, true)) {
- throw new RuntimeException(sprintf('Could not create cache directory "%s".', $cacheDir.'/expressions'));
- }
- }
-
- $container->getDefinition('security.expressions.voter')
- ->addMethodCall('setCacheDir', array($cacheDir.'/expressions'));
- }
-
- $disableAllVoters = !isset($config['voters']);
- $container->setParameter('security.authenticated_voter.disabled',
- $disableAllVoters || $config['voters']['disable_authenticated']);
- $container->setParameter('security.role_voter.disabled',
- $disableAllVoters || $config['voters']['disable_role']);
- $container->setParameter('security.acl_voter.disabled',
- $disableAllVoters || $config['voters']['disable_acl']);
-
- if ($config['enable_iddqd_attribute']) {
- $container
- ->getDefinition('security.extra.iddqd_voter')
- ->addTag('security.voter')
- ;
-
- // FIXME: Also add an iddqd after invocation provider
- }
-
- if ($config['method_access_control']) {
- $driverDef = $container->getDefinition('security.extra.driver_chain');
- $args = $driverDef->getArguments();
- array_unshift($args[0], new Reference('security.extra.config_driver'));
- $driverDef->setArguments($args);
-
- $container->setParameter('security.access.method_access_control',
- $config['method_access_control']);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\DependencyInjection;
-
-use Symfony\Component\HttpKernel\DependencyInjection\Extension;
-use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension as BaseSecurityExtension;
-use Symfony\Component\HttpKernel\Kernel;
-use Symfony\Component\DependencyInjection\DefinitionDecorator;
-use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Reference;
-use Symfony\Component\Config\FileLocator;
-
-/**
- * Enhances the access_control section of the SecurityBundle.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class SecurityExtension extends Extension
-{
- private $extension;
-
- public function __construct(BaseSecurityExtension $extension)
- {
- $this->extension = $extension;
- }
-
- public function getAlias()
- {
- return $this->extension->getAlias();
- }
-
- public function getNamespace()
- {
- return $this->extension->getNamespace();
- }
-
- public function getXsdValidationBasePath()
- {
- return $this->extension->getXsdValidationBasePath();
- }
-
- public function getClassesToCompile()
- {
- return array_merge(parent::getClassesToCompile(), $this->extension->getClassesToCompile());
- }
-
- public function load(array $configs, ContainerBuilder $container)
- {
- $parentConfigs = array();
-
- foreach ($configs as $config) {
- if (isset($config['rule'])) {
- unset($config['rule']);
- }
- if (isset($config['access_control'])) {
- unset($config['access_control']);
- }
-
- $parentConfigs[] = $config;
- }
- $this->extension->load($parentConfigs, $container);
-
- $config = $this->processConfiguration(new AccessControlConfiguration(), $configs);
- $this->createAuthorization($config, $container);
- }
-
- public function __call($method, array $args)
- {
- return call_user_func_array(array($this->extension, $method), $args);
- }
-
- private function createAuthorization($config, ContainerBuilder $container)
- {
- if (!$config['access_control']) {
- return;
- }
-
- $this->addClassesToCompile(array(
- 'Symfony\\Component\\Security\\Http\\AccessMap',
- ));
-
- foreach ($config['access_control'] as $access) {
- $matcher = $this->invokeParent('createRequestMatcher', array(
- $container,
- $access['path'],
- $access['host'],
- count($access['methods']) === 0 ? null : $access['methods'],
- $access['ip']
- ));
-
- if (isset($access['roles'])) {
- $attributes = $access['roles'];
- } else {
- $def = new DefinitionDecorator('security.expressions.expression');
- $def->addArgument($access['access']);
- $container->setDefinition($exprId = 'security.expressions.expression.'.sha1($access['access']), $def);
-
- $attributes = array(new Reference($exprId));
- }
-
- $container->getDefinition('security.access_map')
- ->addMethodCall('add', array($matcher, $attributes, $access['requires_channel']));
- }
- }
-
- private function invokeParent($method, array $args = array())
- {
- $ref = new \ReflectionMethod($this->extension, $method);
- $ref->setAccessible(true);
-
- return $ref->invokeArgs($this->extension, $args);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Exception;
-
-/**
- * Base exception for the SecurityExtraBundle.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface Exception
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Exception;
-
-/**
- * InvalidArgumentException for the SecurityExtraBundle.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class InvalidArgumentException extends \InvalidArgumentException implements Exception
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Exception;
-
-/**
- * RuntimeException for the SecurityExtraBundle.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class RuntimeException extends \RuntimeException implements Exception
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle;
-
-use JMS\SecurityExtraBundle\DependencyInjection\SecurityExtension;
-use JMS\SecurityExtraBundle\DependencyInjection\Compiler\IntegrationPass;
-use JMS\SecurityExtraBundle\DependencyInjection\Compiler\DisableVotersPass;
-use JMS\SecurityExtraBundle\DependencyInjection\Compiler\AddExpressionCompilersPass;
-use Symfony\Component\DependencyInjection\Compiler\PassConfig;
-use JMS\SecurityExtraBundle\DependencyInjection\Compiler\AddAfterInvocationProvidersPass;
-use JMS\SecurityExtraBundle\DependencyInjection\Compiler\CollectSecuredServicesPass;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\HttpKernel\Bundle\Bundle;
-
-/**
- * Registers our custom compiler pass.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class JMSSecurityExtraBundle extends Bundle
-{
- const VERSION = '1.1.0';
-
- public function build(ContainerBuilder $container)
- {
- if (!$container->hasExtension('security')) {
- throw new \LogicException('The JMSSecurityExtraBundle must be registered after the SecurityBundle in your AppKernel.php.');
- }
- $container->registerExtension(new SecurityExtension($container->getExtension('security')));
-
- $passConfig = $container->getCompilerPassConfig();
-
- // needs to run before voter collection
- $passes = $passConfig->getBeforeOptimizationPasses();
- array_unshift($passes, new DisableVotersPass());
- $passConfig->setBeforeOptimizationPasses($passes);
-
- $passConfig->addPass(new AddAfterInvocationProvidersPass());
- $passConfig->addPass(new CollectSecuredServicesPass());
- $passConfig->addPass(new AddExpressionCompilersPass());
- $passConfig->addPass(new IntegrationPass());
- }
-}
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Metadata;
-
-use JMS\SecurityExtraBundle\Exception\RuntimeException;
-use JMS\SecurityExtraBundle\Exception\InvalidArgumentException;
-use Metadata\MethodMetadata;
-use Metadata\MergeableInterface;
-use Metadata\MergeableClassMetadata;
-
-/**
- * Contains class metadata information
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class ClassMetadata extends MergeableClassMetadata
-{
- public function addMethodMetadata(MethodMetadata $metadata)
- {
- if ($this->reflection->isFinal()) {
- throw new RuntimeException(sprintf('Class "%s" is declared final, and cannot be secured.', $reflection->name));
- }
-
- if ($metadata->reflection->isStatic()) {
- throw new RuntimeException(sprintf('Method "%s::%s" is declared static and cannot be secured.', $metadata->reflection->class, $metadata->reflection->name));
- }
-
- if ($metadata->reflection->isFinal()) {
- throw new RuntimeException(sprintf('Method "%s::%s" is declared final and cannot be secured.', $metadata->reflection->class, $metadata->reflection->name));
- }
-
- parent::addMethodMetadata($metadata);
- }
-
- public function merge(MergeableInterface $metadata)
- {
- if (!$metadata instanceof ClassMetadata) {
- throw new InvalidArgumentException('$metadata must be an instance of ClassMetadata.');
- }
-
- foreach ($this->methodMetadata as $name => $methodMetadata) {
- // check if metadata was declared on an interface
- if (!$metadata->reflection->hasMethod($name)) {
- continue;
- }
-
- if ($metadata->reflection->getMethod($name)->getDeclaringClass()->name
- !== $methodMetadata->class) {
- if (!isset($metadata->methodMetadata[$name])) {
- if ($methodMetadata->reflection->isAbstract()) {
- continue;
- }
-
- throw new RuntimeException(sprintf(
- 'You have overridden a secured method "%s::%s" in "%s". '
- .'Please copy over the applicable security metadata, and '
- .'also add @SatisfiesParentSecurityPolicy.',
- $methodMetadata->reflection->class,
- $name,
- $metadata->reflection->name
- ));
- }
-
- if (!$metadata->methodMetadata[$name]->satisfiesParentSecurityPolicy) {
- throw new RuntimeException(sprintf('Unresolved security metadata conflict for method "%s::%s" in "%s". Please copy the respective annotations, and add @SatisfiesParentSecurityPolicy to the child method.', $metadata->reflection->name, $name, $methodMetadata->reflection->getDeclaringClass()->getFilename()));
- }
- }
- }
-
- parent::merge($metadata);
- }
-
- public function isProxyRequired()
- {
- return !empty($this->methodMetadata);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Metadata\Driver;
-
-use JMS\SecurityExtraBundle\Exception\InvalidArgumentException;
-use Doctrine\Common\Annotations\Reader;
-use JMS\SecurityExtraBundle\Annotation\PreAuthorize;
-use JMS\SecurityExtraBundle\Annotation\RunAs;
-use JMS\SecurityExtraBundle\Annotation\SatisfiesParentSecurityPolicy;
-use JMS\SecurityExtraBundle\Annotation\Secure;
-use JMS\SecurityExtraBundle\Annotation\SecureParam;
-use JMS\SecurityExtraBundle\Annotation\SecureReturn;
-use JMS\SecurityExtraBundle\Metadata\ClassMetadata;
-use JMS\SecurityExtraBundle\Metadata\MethodMetadata;
-use Metadata\Driver\DriverInterface;
-use \ReflectionClass;
-use \ReflectionMethod;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Expression;
-
-/**
- * Loads security annotations and converts them to metadata
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class AnnotationDriver implements DriverInterface
-{
- private $reader;
-
- public function __construct(Reader $reader)
- {
- $this->reader = $reader;
- }
-
- public function loadMetadataForClass(ReflectionClass $reflection)
- {
- $metadata = new ClassMetadata($reflection->getName());
-
- foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED) as $method) {
- // check if the method was defined on this class
- if ($method->getDeclaringClass()->getName() !== $reflection->getName()) {
- continue;
- }
-
- $annotations = $this->reader->getMethodAnnotations($method);
-
- if ($annotations && null !== $methodMetadata = $this->convertMethodAnnotations($method, $annotations)) {
- $metadata->addMethodMetadata($methodMetadata);
- }
- }
-
- return $metadata;
- }
-
- private function convertMethodAnnotations(\ReflectionMethod $method, array $annotations)
- {
- $parameters = array();
- foreach ($method->getParameters() as $index => $parameter) {
- $parameters[$parameter->getName()] = $index;
- }
-
- $methodMetadata = new MethodMetadata($method->getDeclaringClass()->getName(), $method->getName());
- $hasSecurityMetadata = false;
- foreach ($annotations as $annotation) {
- if ($annotation instanceof Secure) {
- $methodMetadata->roles = $annotation->roles;
- $hasSecurityMetadata = true;
- } else if ($annotation instanceof PreAuthorize) {
- $methodMetadata->roles = array(new Expression($annotation->expr));
- $hasSecurityMetadata = true;
- } else if ($annotation instanceof SecureParam) {
- if (!isset($parameters[$annotation->name])) {
- throw new InvalidArgumentException(sprintf('The parameter "%s" does not exist for method "%s".', $annotation->name, $method->getName()));
- }
-
- $methodMetadata->addParamPermissions($parameters[$annotation->name], $annotation->permissions);
- $hasSecurityMetadata = true;
- } else if ($annotation instanceof SecureReturn) {
- $methodMetadata->returnPermissions = $annotation->permissions;
- $hasSecurityMetadata = true;
- } else if ($annotation instanceof SatisfiesParentSecurityPolicy) {
- $methodMetadata->satisfiesParentSecurityPolicy = true;
- $hasSecurityMetadata = true;
- } else if ($annotation instanceof RunAs) {
- $methodMetadata->runAsRoles = $annotation->roles;
- $hasSecurityMetadata = true;
- }
- }
-
- return $hasSecurityMetadata ? $methodMetadata : null;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Metadata\Driver;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Expression;
-use JMS\SecurityExtraBundle\Metadata\MethodMetadata;
-use Symfony\Component\HttpKernel\Kernel;
-use JMS\SecurityExtraBundle\Metadata\ClassMetadata;
-use Metadata\Driver\DriverInterface;
-
-/**
- * Uses Symfony2 DI configuration for metadata.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class ConfigDriver implements DriverInterface
-{
- private $bundles;
- private $config;
-
- public function __construct(array $bundles, array $config)
- {
- uasort($bundles, function($a, $b) {
- return strlen($b) - strlen($a);
- });
-
- foreach ($bundles as $name => $namespace) {
- $bundles[$name] = substr($namespace, 0, strrpos($namespace, '\\'));
- }
-
- $this->bundles = $bundles;
- $this->config = $config;
- }
-
- public function loadMetadataForClass(\ReflectionClass $class)
- {
- $metadata = new ClassMetadata($class->name);
-
- foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
- if ($method->getDeclaringClass()->name !== $class->name) {
- continue;
- }
-
- $expression = null;
- if (null !== $notation = $this->getControllerNotation($method)) {
- $expression = $this->getExpressionForSignature($notation);
- }
-
- if (null === $expression && null === $expression =
- $this->getExpressionForSignature($method->class.'::'.$method->name)) {
- continue;
- }
-
- $methodMetadata = new MethodMetadata($method->class, $method->name);
- $methodMetadata->roles = array(new Expression($expression));
- $metadata->addMethodMetadata($methodMetadata);
- }
-
- if (!$metadata->methodMetadata) {
- return null;
- }
-
- return $metadata;
- }
-
- private function getExpressionForSignature($signature)
- {
- foreach ($this->config as $pattern => $expr) {
- if (!preg_match('#'.$pattern.'#i', $signature)) {
- continue;
- }
-
- return $expr;
- }
-
- return null;
- }
-
- // TODO: Is it feasible to reverse-engineer the notation for service controllers?
- private function getControllerNotation(\ReflectionMethod $method)
- {
- $signature = $method->class.'::'.$method->name;
-
- // check if class is a controller
- if (0 === preg_match('#\\\\Controller\\\\([^\\\\]+)Controller::(.+)Action$#', $signature, $match)) {
- return null;
- }
-
- foreach ($this->bundles as $name => $namespace) {
- if (0 !== strpos($method->class, $namespace)) {
- continue;
- }
-
- // controller notation (AcmeBundle:Foo:foo)
- return $name.':'.$match[1].':'.$match[2];
- }
-
- return null;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Metadata;
-
-use Metadata\MethodMetadata as BaseMethodMetadata;
-
-/**
- * Contains method metadata information
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class MethodMetadata extends BaseMethodMetadata
-{
- public $roles = array();
- public $paramPermissions = array();
- public $returnPermissions = array();
- public $runAsRoles = array();
- public $satisfiesParentSecurityPolicy = false;
-
- /**
- * Adds a parameter restriction
- *
- * @param integer $index 0-based
- * @param array $permissions
- */
- public function addParamPermissions($index, array $permissions)
- {
- $this->paramPermissions[$index] = $permissions;
- }
-
- public function isDeclaredOnInterface()
- {
- foreach ($this->reflection->getDeclaringClass()->getInterfaces() as $interface) {
- if ($interface->hasMethod($this->name)) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * This allows to merge in metadata from an interface
- *
- * @param MethodMetadata $method
- * @return void
- */
- public function merge(MethodMetadata $method)
- {
- if (!$this->roles) {
- $this->roles = $method->roles;
- }
-
- if (!$this->returnPermissions) {
- $this->returnPermissions = $method->returnPermissions;
- }
-
- if (!$this->runAsRoles) {
- $this->runAsRoles = $method->runAsRoles;
- }
-
- foreach ($method->paramPermissions as $index => $permissions) {
- if (!isset($this->paramPermissions[$index])) {
- $this->paramPermissions[$index] = $permissions;
- }
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-For documentation, see:
-
- Resources/doc
-
-
-For license, see:
-
- Resources/meta/LICENSE
\ No newline at end of file
+++ /dev/null
-<?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">
-
- <parameters>
- <parameter key="security.acl.permission_evaluator.class">JMS\SecurityExtraBundle\Security\Acl\Expression\PermissionEvaluator</parameter>
- <parameter key="security.acl.has_permission_compiler.class">JMS\SecurityExtraBundle\Security\Acl\Expression\HasPermissionFunctionCompiler</parameter>
-
- <parameter key="security.expressions.voter.class">JMS\SecurityExtraBundle\Security\Authorization\Expression\LazyLoadingExpressionVoter</parameter>
- <parameter key="security.expressions.handler.class">JMS\SecurityExtraBundle\Security\Authorization\Expression\ContainerAwareExpressionHandler</parameter>
-
- <parameter key="security.expressions.compiler.class">JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler</parameter>
- <parameter key="security.expressions.expression.class">JMS\SecurityExtraBundle\Security\Authorization\Expression\Expression</parameter>
-
- <parameter key="security.expressions.variable_compiler.class">JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\ContainerAwareVariableCompiler</parameter>
- <parameter key="security.expressions.parameter_compiler.class">JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\ParameterExpressionCompiler</parameter>
-
- <parameter key="security.extra.config_driver.class">JMS\SecurityExtraBundle\Metadata\Driver\ConfigDriver</parameter>
-
- <parameter key="security.extra.twig_extension.class">JMS\SecurityExtraBundle\Twig\SecurityExtension</parameter>
- </parameters>
-
- <services>
- <service id="security.extra.twig_extension" class="%security.extra.twig_extension.class%" public="false">
- <argument type="service" id="security.context" />
- <tag name="twig.extension" alias="jms_security_extra" />
- </service>
-
- <service id="security.extra.config_driver" class="%security.extra.config_driver.class%" public="false">
- <argument>%kernel.bundles%</argument>
- <argument>%security.access.method_access_control%</argument>
- </service>
-
- <service id="security.expressions.parameter_compiler" class="%security.expressions.parameter_compiler.class%" public="false">
- <tag name="security.expressions.type_compiler" />
- </service>
-
- <service id="security.expressions.variable_compiler" class="%security.expressions.variable_compiler.class%" public="false">
- <tag name="security.expressions.type_compiler" />
-
- <!-- Some variables for built-in compilers for lazy-loading -->
- <tag name="security.expressions.variable" variable="trust_resolver"
- service="security.authentication.trust_resolver" />
- <tag name="security.expressions.variable" variable="role_hierarchy"
- service="security.role_hierarchy" />
- </service>
-
- <service id="security.expressions.voter" class="%security.expressions.voter.class%" public="false">
- <argument type="service" id="security.expressions.handler" />
-
- <call method="setLazyCompiler">
- <argument type="service" id="service_container" />
- <argument>security.expressions.compiler</argument>
- </call>
-
- <tag name="security.voter" priority="230" />
- </service>
-
- <service id="security.expressions.handler" class="%security.expressions.handler.class%" public="false">
- <argument type="service" id="service_container" />
- </service>
-
- <service id="security.expressions.compiler" class="%security.expressions.compiler.class%" />
-
- <service id="security.expressions.expression" class="%security.expressions.expression.class%" public="false" abstract="true" />
-
- <!-- Expression-Based ACL -->
- <service id="security.acl.permission_evaluator" class="%security.acl.permission_evaluator.class%" public="false">
- <tag name="monolog.logger" channel="security" />
- <argument type="service" id="security.acl.provider" />
- <argument type="service" id="security.acl.object_identity_retrieval_strategy" />
- <argument type="service" id="security.acl.security_identity_retrieval_strategy" />
- <argument type="service" id="security.acl.permission.map" />
- <argument type="service" id="logger" on-invalid="null" />
- </service>
-
- <service id="security.acl.has_permission_compiler" class="%security.acl.has_permission_compiler.class%" public="false">
- <tag name="security.expressions.function_compiler" />
- <tag name="security.expressions.variable" variable="permission_evaluator" service="security.acl.permission_evaluator"/>
- </service>
- </services>
-</container>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-
-<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">
-
- <parameters>
- <parameter key="security.secured_services" type="collection"></parameter>
-
- <parameter key="security.access.method_interceptor.class">JMS\SecurityExtraBundle\Security\Authorization\Interception\MethodSecurityInterceptor</parameter>
- <parameter key="security.access.method_access_control" type="collection" />
-
- <parameter key="security.access.run_as_manager.class">JMS\SecurityExtraBundle\Security\Authorization\RunAsManager</parameter>
- <parameter key="security.authentication.provider.run_as.class">JMS\SecurityExtraBundle\Security\Authentication\Provider\RunAsAuthenticationProvider</parameter>
- <parameter key="security.run_as.key">RunAsToken</parameter>
- <parameter key="security.run_as.role_prefix">ROLE_</parameter>
-
- <parameter key="security.access.after_invocation_manager.class">JMS\SecurityExtraBundle\Security\Authorization\AfterInvocation\AfterInvocationManager</parameter>
- <parameter key="security.access.after_invocation.acl_provider.class">JMS\SecurityExtraBundle\Security\Authorization\AfterInvocation\AclAfterInvocationProvider</parameter>
-
- <parameter key="security.access.iddqd_voter.class">JMS\SecurityExtraBundle\Security\Authorization\Voter\IddqdVoter</parameter>
-
- <parameter key="security.extra.metadata_factory.class">Metadata\MetadataFactory</parameter>
- <parameter key="security.extra.lazy_loading_driver.class">Metadata\Driver\LazyLoadingDriver</parameter>
- <parameter key="security.extra.driver_chain.class">Metadata\Driver\DriverChain</parameter>
- <parameter key="security.extra.annotation_driver.class">JMS\SecurityExtraBundle\Metadata\Driver\AnnotationDriver</parameter>
- <parameter key="security.extra.file_cache.class">Metadata\Cache\FileCache</parameter>
- </parameters>
-
- <services>
- <service id="security.access.run_as_manager" class="%security.access.run_as_manager.class%" public="false">
- <argument>%security.run_as.key%</argument>
- <argument>%security.run_as.role_prefix%</argument>
- </service>
-
- <service id="security.access.method_interceptor" class="%security.access.method_interceptor.class%">
- <argument type="service" id="security.context" />
- <argument type="service" id="security.authentication.manager" />
- <argument type="service" id="security.access.decision_manager" />
- <argument type="service" id="security.access.after_invocation_manager" />
- <argument type="service" id="security.access.run_as_manager" />
- <argument type="service" id="security.extra.metadata_factory" />
- <argument type="service" id="logger" on-invalid="null" />
- </service>
-
- <service id="security.access.pointcut" class="JMS\SecurityExtraBundle\Security\Authorization\Interception\SecurityPointcut">
- <argument type="service" id="security.extra.metadata_factory" />
- <argument>%security.access.secure_all_services%</argument>
- <argument>%security.access.method_access_control%</argument>
-
- <tag name="jms_aop.pointcut" interceptor="security.access.method_interceptor" />
- </service>
-
- <service id="security.access.after_invocation_manager" class="%security.access.after_invocation_manager.class%" public="false">
- <argument type="collection"></argument>
- </service>
-
- <service id="security.access.after_invocation.acl_provider" class="%security.access.after_invocation.acl_provider.class%" public="false">
- <argument type="service" id="security.acl.provider" />
- <argument type="service" id="security.acl.object_identity_retrieval_strategy" />
- <argument type="service" id="security.acl.security_identity_retrieval_strategy" />
- <argument type="service" id="security.acl.permission.map" />
- <tag name="security.after_invocation.provider" />
- </service>
-
- <service id="security.extra.iddqd_voter" class="%security.access.iddqd_voter.class%" public="false">
- </service>
-
- <service id="security.extra.driver_chain" class="%security.extra.driver_chain.class%" public="false">
- <argument type="collection">
- <argument type="service" id="security.extra.annotation_driver" />
- </argument>
- </service>
- <service id="security.extra.metadata_driver" alias="security.extra.driver_chain"></service>
-
- <service id="security.extra.lazy_loading_driver" class="%security.extra.lazy_loading_driver.class%" public="false">
- <argument type="service" id="service_container" />
- <argument>security.extra.metadata_driver</argument>
- </service>
-
- <service id="security.extra.annotation_driver" class="%security.extra.annotation_driver.class%" public="false">
- <argument type="service" id="annotation_reader" />
- </service>
-
- <service id="security.extra.file_cache" class="%security.extra.file_cache.class%" public="false">
- <argument>%security.extra.cache_dir%</argument>
- <argument>%kernel.debug%</argument>
- </service>
-
- <service id="security.extra.metadata_factory" class="%security.extra.metadata_factory.class%" public="false">
- <argument type="service" id="security.extra.lazy_loading_driver" />
- <argument type="service" id="security.extra.file_cache" />
- <call method="setIncludeInterfaces">
- <argument>true</argument>
- </call>
- </service>
- </services>
-
-</container>
\ No newline at end of file
+++ /dev/null
-========
-Overview
-========
-
-This bundle enhances the Symfony2 Security Component by adding several new features.
-
-Features:
-
-- powerful expression-based authorization language
-- method security authorization
-- authorization configuration via annotations
-
-Installation
-------------
-Add the following to your ``deps`` file::
-
- [JMSSecurityExtraBundle]
- git=https://github.com/schmittjoh/JMSSecurityExtraBundle.git
- target=/bundles/JMS/SecurityExtraBundle
-
- ; Dependencies:
- ;--------------
- [metadata]
- git=https://github.com/schmittjoh/metadata.git
- version=1.1.0 ; <- make sure to get 1.1, not 1.0
-
- ; see https://github.com/schmittjoh/JMSAopBundle/blob/master/Resources/doc/index.rst
- [JMSAopBundle]
- git=https://github.com/schmittjoh/JMSAopBundle.git
- target=/bundles/JMS/AopBundle
-
- [cg-library]
- git=https://github.com/schmittjoh/cg-library.git
-
- ; This dependency is optional (you need it if you are using non-service controllers):
- ; see https://github.com/schmittjoh/JMSDiExtraBundle/blob/master/Resources/doc/index.rst
- [JMSDiExtraBundle]
- git=https://github.com/schmittjoh/JMSDiExtraBundle.git
- target=/bundles/JMS/DiExtraBundle
-
-Then register the bundle with your kernel::
-
- // in AppKernel::registerBundles()
- $bundles = array(
- // ...
- new JMS\AopBundle\JMSAopBundle(),
- new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
- new JMS\DiExtraBundle\JMSDiExtraBundle($this),
- // ...
- );
-
-Make sure that you also register the namespaces with the autoloader::
-
- // app/autoload.php
- $loader->registerNamespaces(array(
- // ...
- 'JMS' => __DIR__.'/../vendor/bundles',
- 'Metadata' => __DIR__.'/../vendor/metadata/src',
- 'CG' => __DIR__.'/../vendor/cg-library/src',
- // ...
- ));
-
-Configuration
--------------
-
-Below, you find the default configuration::
-
- # app/config/config.yml
- jms_security_extra:
- # Whether you want to secure all services (true), or only secure specific
- # services (false); see also below
- secure_all_services: false
-
- # Enabling this setting will add an additional special attribute "IS_IDDQD".
- # Anybody with this attribute will effectively bypass all security checks.
- enable_iddqd_attribute: false
-
- # Enables expression language
- expressions: false
-
- # Allows you to disable some, or all built-in voters
- voters:
- disable_authenticated: false
- disable_role: false
- disable_acl: false
-
- # Allows you to specify access control rules for specific methods, such
- # as controller actions
- method_access_control: { }
-
-
-Expression-based Authorization Language
----------------------------------------
-The expression language is a very powerful alternative to the simple attributes
-of the security voting system. They allow to perform complex access decision
-checks, and because they are compiled down to raw PHP, they are much faster than
-the built-in voters. Also they are lazy-loading by nature, so you will also
-save some resources for example by not having to initialize the entire ACL system
-on each request.
-
-Programmatic Usage
-~~~~~~~~~~~~~~~~~~
-You can execute expressions programmatically by using the ``isGranted`` method
-of the SecurityContext. Some examples::
-
- use JMS\SecurityExtraBundle\Security\Authorization\Expression\Expression;
-
- $securityContext->isGranted(array(new Expression('hasRole("A")')));
- $securityContext->isGranted(array(new Expression('hasRole("A") or (hasRole("B") and hasRole("C"))')));
- $securityContext->isGranted(array(new Expression('hasPermission(object, "VIEW")'), $object));
- $securityContext->isGranted(array(new Expression('token.getUsername() == "Johannes"')));
-
-Twig Usage
-~~~~~~~~~~
-You can check expressions from Twig templates using the ``is_expr_granted``
-function. Some examples::
-
- is_expr_granted("hasRole('FOO')")
- is_expr_granted("hasPermission(object, 'VIEW')", object)
-
-Usage in Access Control
-~~~~~~~~~~~~~~~~~~~~~~~
-You can also use expressions in the ``access_control``::
-
- security:
- access_control:
- - { path: ^/foo, access: "hasRole('FOO') and hasRole('BAR')" }
-
-Annotation-based Usage
-~~~~~~~~~~~~~~~~~~~~~~
-see @PreAuthorize in the annotation reference
-
-Reference
-~~~~~~~~~
-+-----------------------------------+--------------------------------------------+
-| Expression | Description |
-+===================================+============================================+
-| hasRole('ROLE') | Checks whether the token has a certain |
-| | role. |
-+-----------------------------------+--------------------------------------------+
-| hasAnyRole('ROLE1', 'ROLE2', ...) | Checks whether the token has any of the |
-| | given roles. |
-+-----------------------------------+--------------------------------------------+
-| isAnonymous() | Checks whether the token is anonymous. |
-+-----------------------------------+--------------------------------------------+
-| isRememberMe() | Checks whether the token is remember me. |
-+-----------------------------------+--------------------------------------------+
-| isFullyAuthenticated() | Checks whether the token is fully |
-| | authenticated. |
-+-----------------------------------+--------------------------------------------+
-| isAuthenticated() | Checks whether the token is not anonymous. |
-+-----------------------------------+--------------------------------------------+
-| hasPermission(*var*, 'PERMISSION')| Checks whether the token has the given |
-| | permission for the given object (requires |
-| | the ACL system). |
-+-----------------------------------+--------------------------------------------+
-| token | Variable that refers to the token |
-| | which is currently in the security context.|
-+-----------------------------------+--------------------------------------------+
-| user | Variable that refers to the user |
-| | which is currently in the security context.|
-+-----------------------------------+--------------------------------------------+
-| object | Variable that refers to the object for |
-| | which access is being requested. |
-+-----------------------------------+--------------------------------------------+
-| #*paramName* | Any identifier prefixed with # refers to |
-| | a parameter of the same name that is passed|
-| | to the method where the expression is used.|
-+-----------------------------------+--------------------------------------------+
-| and / && | Binary "and" operator |
-+-----------------------------------+--------------------------------------------+
-| or / || | Binary "or" operator |
-+-----------------------------------+--------------------------------------------+
-| == | Binary "is equal" operator |
-+-----------------------------------+--------------------------------------------+
-| not / ! | Negation operator |
-+-----------------------------------+--------------------------------------------+
-
-Method Security Authorization
------------------------------
-Generally, you can secure all public, or protected methods which are non-static,
-and non-final. Private methods cannot be secured. You can also add metadata for
-abstract methods, or interfaces which will then be applied to their concrete
-implementations automatically.
-
-Access Control via DI configuration
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-You can specify access control **expressions** in the DI configuration::
-
- # config.yml
- jms_security_extra:
- method_access_control:
- ':loginAction$': 'isAnonymous()'
- 'AcmeFooBundle:.*:deleteAction': 'hasRole("ROLE_ADMIN")'
- '^MyNamespace\MyService::foo$': 'hasPermission(#user, "VIEW")'
-
-The pattern is a case-sensitive regular expression which is matched against two notations.
-The first match is being used.
-
-First, your pattern is matched against the notation for non-service controllers.
-This obviously is only done if your class is actually a controller, e.g.
-``AcmeFooBundle:Add:new`` for a controller named ``AddController`` and a method
-named ``newAction`` in a sub-namespace ``Controller`` in a bundle named ``AcmeFooBundle``.
-
-Last, your pattern is matched against the concatenation of the class name, and
-the method name that is being called, e.g. ``My\Fully\Qualified\ClassName::myMethodName``.
-
-**Note:** If you would like to secure non-service controllers, the
-``JMSDiExtraBundle`` must be installed.
-
-Access Control via Annotations
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-If you like to secure a service with annotations, you need to enable annotation
-configuration for this service::
-
- <service id="foo" class="Bar">
- <tag name="security.secure_service"/>
- </service>
-
-In case, you like to configure all services via annotations, you can also set
-``secure_all_services`` to true. Then, you do not need to add a tag for each
-service.
-
-
-Annotations
------------
-@PreAuthorize
-~~~~~~~~~~~~~
-This annotation lets you define an expression (see the expression language
-paragraph) which is executed prior to invoking a method::
-
- <?php
-
- use JMS\SecurityExtraBundle\Annotation\PreAuthorize;
-
- class MyService
- {
- /** @PreAuthorize("hasRole('A') or (hasRole('B') and hasRole('C'))") */
- public function secureMethod()
- {
- // ...
- }
- }
-
-@Secure
-~~~~~~~
-This annotation lets you define who is allowed to invoke a method::
-
- <?php
-
- use JMS\SecurityExtraBundle\Annotation\Secure;
-
- class MyService
- {
- /**
- * @Secure(roles="ROLE_USER, ROLE_FOO, ROLE_ADMIN")
- */
- public function secureMethod()
- {
- // ...
- }
- }
-
-@SecureParam
-~~~~~~~~~~~~
-This annotation lets you define restrictions for parameters which are passed to
-the method. This is only useful if the parameters are domain objects::
-
- <?php
-
- use JMS\SecurityExtraBundle\Annotation\SecureParam;
-
- class MyService
- {
- /**
- * @SecureParam(name="comment", permissions="EDIT, DELETE")
- * @SecureParam(name="post", permissions="OWNER")
- */
- public function secureMethod($comment, $post)
- {
- // ...
- }
- }
-
-@SecureReturn
-~~~~~~~~~~~~~
-This annotation lets you define restrictions for the value which is returned by
-the method. This is also only useful if the returned value is a domain object::
-
- <?php
-
- use JMS\SecurityExtraBundle\Annotation\SecureReturn;
-
- class MyService
- {
- /**
- * @SecureReturn(permissions="VIEW")
- */
- public function secureMethod()
- {
- // ...
-
- return $domainObject;
- }
- }
-
-@RunAs
-~~~~~~
-This annotation lets you specifiy roles which are added only for the duration
-of the method invocation. These roles will not be taken into consideration
-for before, or after invocation access decisions.
-
-This is typically used to implement a two-tier service layer where you have
-public and private services, and private services are only to be invoked
-through a specific public service::
-
- <?php
-
- use JMS\SecurityExtraBundle\Annotation\Secure;
- use JMS\SecurityExtraBundle\Annotation\RunAs;
-
- class MyPrivateService
- {
- /**
- * @Secure(roles="ROLE_PRIVATE_SERVICE")
- */
- public function aMethodOnlyToBeInvokedThroughASpecificChannel()
- {
- // ...
- }
- }
-
- class MyPublicService
- {
- protected $myPrivateService;
-
- /**
- * @Secure(roles="ROLE_USER")
- * @RunAs(roles="ROLE_PRIVATE_SERVICE")
- */
- public function canBeInvokedFromOtherServices()
- {
- return $this->myPrivateService->aMethodOnlyToBeInvokedThroughASpecificChannel();
- }
- }
-
-@SatisfiesParentSecurityPolicy
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-This must be defined on a method that overrides a method which has security metadata.
-It is there to ensure that you are aware the security of the overridden method cannot
-be enforced anymore, and that you must copy over all annotations if you want to keep
-them.
+++ /dev/null
- Apache License\r
- Version 2.0, January 2004\r
- http://www.apache.org/licenses/\r
-\r
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\r
-\r
- 1. Definitions.\r
-\r
- "License" shall mean the terms and conditions for use, reproduction,\r
- and distribution as defined by Sections 1 through 9 of this document.\r
-\r
- "Licensor" shall mean the copyright owner or entity authorized by\r
- the copyright owner that is granting the License.\r
-\r
- "Legal Entity" shall mean the union of the acting entity and all\r
- other entities that control, are controlled by, or are under common\r
- control with that entity. For the purposes of this definition,\r
- "control" means (i) the power, direct or indirect, to cause the\r
- direction or management of such entity, whether by contract or\r
- otherwise, or (ii) ownership of fifty percent (50%) or more of the\r
- outstanding shares, or (iii) beneficial ownership of such entity.\r
-\r
- "You" (or "Your") shall mean an individual or Legal Entity\r
- exercising permissions granted by this License.\r
-\r
- "Source" form shall mean the preferred form for making modifications,\r
- including but not limited to software source code, documentation\r
- source, and configuration files.\r
-\r
- "Object" form shall mean any form resulting from mechanical\r
- transformation or translation of a Source form, including but\r
- not limited to compiled object code, generated documentation,\r
- and conversions to other media types.\r
-\r
- "Work" shall mean the work of authorship, whether in Source or\r
- Object form, made available under the License, as indicated by a\r
- copyright notice that is included in or attached to the work\r
- (an example is provided in the Appendix below).\r
-\r
- "Derivative Works" shall mean any work, whether in Source or Object\r
- form, that is based on (or derived from) the Work and for which the\r
- editorial revisions, annotations, elaborations, or other modifications\r
- represent, as a whole, an original work of authorship. For the purposes\r
- of this License, Derivative Works shall not include works that remain\r
- separable from, or merely link (or bind by name) to the interfaces of,\r
- the Work and Derivative Works thereof.\r
-\r
- "Contribution" shall mean any work of authorship, including\r
- the original version of the Work and any modifications or additions\r
- to that Work or Derivative Works thereof, that is intentionally\r
- submitted to Licensor for inclusion in the Work by the copyright owner\r
- or by an individual or Legal Entity authorized to submit on behalf of\r
- the copyright owner. For the purposes of this definition, "submitted"\r
- means any form of electronic, verbal, or written communication sent\r
- to the Licensor or its representatives, including but not limited to\r
- communication on electronic mailing lists, source code control systems,\r
- and issue tracking systems that are managed by, or on behalf of, the\r
- Licensor for the purpose of discussing and improving the Work, but\r
- excluding communication that is conspicuously marked or otherwise\r
- designated in writing by the copyright owner as "Not a Contribution."\r
-\r
- "Contributor" shall mean Licensor and any individual or Legal Entity\r
- on behalf of whom a Contribution has been received by Licensor and\r
- subsequently incorporated within the Work.\r
-\r
- 2. Grant of Copyright License. Subject to the terms and conditions of\r
- this License, each Contributor hereby grants to You a perpetual,\r
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable\r
- copyright license to reproduce, prepare Derivative Works of,\r
- publicly display, publicly perform, sublicense, and distribute the\r
- Work and such Derivative Works in Source or Object form.\r
-\r
- 3. Grant of Patent License. Subject to the terms and conditions of\r
- this License, each Contributor hereby grants to You a perpetual,\r
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable\r
- (except as stated in this section) patent license to make, have made,\r
- use, offer to sell, sell, import, and otherwise transfer the Work,\r
- where such license applies only to those patent claims licensable\r
- by such Contributor that are necessarily infringed by their\r
- Contribution(s) alone or by combination of their Contribution(s)\r
- with the Work to which such Contribution(s) was submitted. If You\r
- institute patent litigation against any entity (including a\r
- cross-claim or counterclaim in a lawsuit) alleging that the Work\r
- or a Contribution incorporated within the Work constitutes direct\r
- or contributory patent infringement, then any patent licenses\r
- granted to You under this License for that Work shall terminate\r
- as of the date such litigation is filed.\r
-\r
- 4. Redistribution. You may reproduce and distribute copies of the\r
- Work or Derivative Works thereof in any medium, with or without\r
- modifications, and in Source or Object form, provided that You\r
- meet the following conditions:\r
-\r
- (a) You must give any other recipients of the Work or\r
- Derivative Works a copy of this License; and\r
-\r
- (b) You must cause any modified files to carry prominent notices\r
- stating that You changed the files; and\r
-\r
- (c) You must retain, in the Source form of any Derivative Works\r
- that You distribute, all copyright, patent, trademark, and\r
- attribution notices from the Source form of the Work,\r
- excluding those notices that do not pertain to any part of\r
- the Derivative Works; and\r
-\r
- (d) If the Work includes a "NOTICE" text file as part of its\r
- distribution, then any Derivative Works that You distribute must\r
- include a readable copy of the attribution notices contained\r
- within such NOTICE file, excluding those notices that do not\r
- pertain to any part of the Derivative Works, in at least one\r
- of the following places: within a NOTICE text file distributed\r
- as part of the Derivative Works; within the Source form or\r
- documentation, if provided along with the Derivative Works; or,\r
- within a display generated by the Derivative Works, if and\r
- wherever such third-party notices normally appear. The contents\r
- of the NOTICE file are for informational purposes only and\r
- do not modify the License. You may add Your own attribution\r
- notices within Derivative Works that You distribute, alongside\r
- or as an addendum to the NOTICE text from the Work, provided\r
- that such additional attribution notices cannot be construed\r
- as modifying the License.\r
-\r
- You may add Your own copyright statement to Your modifications and\r
- may provide additional or different license terms and conditions\r
- for use, reproduction, or distribution of Your modifications, or\r
- for any such Derivative Works as a whole, provided Your use,\r
- reproduction, and distribution of the Work otherwise complies with\r
- the conditions stated in this License.\r
-\r
- 5. Submission of Contributions. Unless You explicitly state otherwise,\r
- any Contribution intentionally submitted for inclusion in the Work\r
- by You to the Licensor shall be under the terms and conditions of\r
- this License, without any additional terms or conditions.\r
- Notwithstanding the above, nothing herein shall supersede or modify\r
- the terms of any separate license agreement you may have executed\r
- with Licensor regarding such Contributions.\r
-\r
- 6. Trademarks. This License does not grant permission to use the trade\r
- names, trademarks, service marks, or product names of the Licensor,\r
- except as required for reasonable and customary use in describing the\r
- origin of the Work and reproducing the content of the NOTICE file.\r
-\r
- 7. Disclaimer of Warranty. Unless required by applicable law or\r
- agreed to in writing, Licensor provides the Work (and each\r
- Contributor provides its Contributions) on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\r
- implied, including, without limitation, any warranties or conditions\r
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\r
- PARTICULAR PURPOSE. You are solely responsible for determining the\r
- appropriateness of using or redistributing the Work and assume any\r
- risks associated with Your exercise of permissions under this License.\r
-\r
- 8. Limitation of Liability. In no event and under no legal theory,\r
- whether in tort (including negligence), contract, or otherwise,\r
- unless required by applicable law (such as deliberate and grossly\r
- negligent acts) or agreed to in writing, shall any Contributor be\r
- liable to You for damages, including any direct, indirect, special,\r
- incidental, or consequential damages of any character arising as a\r
- result of this License or out of the use or inability to use the\r
- Work (including but not limited to damages for loss of goodwill,\r
- work stoppage, computer failure or malfunction, or any and all\r
- other commercial damages or losses), even if such Contributor\r
- has been advised of the possibility of such damages.\r
-\r
- 9. Accepting Warranty or Additional Liability. While redistributing\r
- the Work or Derivative Works thereof, You may choose to offer,\r
- and charge a fee for, acceptance of support, warranty, indemnity,\r
- or other liability obligations and/or rights consistent with this\r
- License. However, in accepting such obligations, You may act only\r
- on Your own behalf and on Your sole responsibility, not on behalf\r
- of any other Contributor, and only if You agree to indemnify,\r
- defend, and hold each Contributor harmless for any liability\r
- incurred by, or claims asserted against, such Contributor by reason\r
- of your accepting any such warranty or additional liability.\r
-\r
- END OF TERMS AND CONDITIONS\r
-\r
- APPENDIX: How to apply the Apache License to your work.\r
-\r
- To apply the Apache License to your work, attach the following\r
- boilerplate notice, with the fields enclosed by brackets "[]"\r
- replaced with your own identifying information. (Don't include\r
- the brackets!) The text should be enclosed in the appropriate\r
- comment syntax for the file format. We also recommend that a\r
- file or class name and description of purpose be included on the\r
- same "printed page" as the copyright notice for easier\r
- identification within third-party archives.\r
-\r
- Copyright [yyyy] [name of copyright owner]\r
-\r
- Licensed under the Apache License, Version 2.0 (the "License");\r
- you may not use this file except in compliance with the License.\r
- You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Acl\Expression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ConstantExpression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\Func\FunctionCompilerInterface;
-
-class HasPermissionFunctionCompiler implements FunctionCompilerInterface
-{
- public function getName()
- {
- return 'hasPermission';
- }
-
- public function compilePreconditions(ExpressionCompiler $compiler, FunctionExpression $function)
- {
- $compiler->verifyItem('token', 'Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
- }
-
- public function compile(ExpressionCompiler $compiler, FunctionExpression $function)
- {
- $compiler
- ->compileInternal(new VariableExpression('permission_evaluator'))
- ->write('->hasPermission(')
- ->compileInternal(new VariableExpression('token'))
- ->write(', ')
- ->compileInternal($function->args[0])
- ->write(', ')
- ;
-
- if ($function->args[1] instanceof ConstantExpression) {
- $compiler->write(var_export(strtoupper($function->args[1]->value), true).')');
-
- return;
- }
-
- $compiler
- ->write('strtoupper(')
- ->compileInternal($function->args[1])
- ->write('))')
- ;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Acl\Expression;
-
-use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
-use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
-use Symfony\Component\Security\Acl\Model\ObjectIdentityInterface;
-use Symfony\Component\Security\Acl\Permission\PermissionMapInterface;
-use Symfony\Component\Security\Acl\Model\AclProviderInterface;
-use Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface;
-use Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface;
-use Symfony\Component\HttpKernel\Log\LoggerInterface;
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-
-class PermissionEvaluator
-{
- private $aclProvider;
- private $oidRetrievalStrategy;
- private $sidRetrievalStrategy;
- private $permissionMap;
- private $allowIfObjectIdentityUnavailable;
- private $logger;
-
- public function __construct(AclProviderInterface $aclProvider,
- ObjectIdentityRetrievalStrategyInterface $oidRetrievalStrategy,
- SecurityIdentityRetrievalStrategyInterface $sidRetrievalStrategy,
- PermissionMapInterface $permissionMap,
- $allowIfObjectIdentityUnavailable = true,
- LoggerInterface $logger = null)
- {
- $this->aclProvider = $aclProvider;
- $this->oidRetrievalStrategy = $oidRetrievalStrategy;
- $this->sidRetrievalStrategy = $sidRetrievalStrategy;
- $this->permissionMap = $permissionMap;
- $this->allowIfObjectIdentityUnavailable = $allowIfObjectIdentityUnavailable;
- $this->logger = $logger;
- }
-
- public function hasPermission(TokenInterface $token, $object, $permission)
- {
- if (null === $masks = $this->permissionMap->getMasks($permission, $object)) {
- return false;
- }
-
- if (null === $object) {
- if (null !== $this->logger) {
- $this->logger->debug(sprintf('Object identity unavailable. Voting to %s', $this->allowIfObjectIdentityUnavailable? 'grant access' : 'abstain'));
- }
-
- return $this->allowIfObjectIdentityUnavailable ? true : false;
- } else if ($object instanceof FieldVote) {
- $field = $object->getField();
- $object = $object->getDomainObject();
- } else {
- $field = null;
- }
-
- if ($object instanceof ObjectIdentityInterface) {
- $oid = $object;
- } else if (null === $oid = $this->oidRetrievalStrategy->getObjectIdentity($object)) {
- if (null !== $this->logger) {
- $this->logger->debug(sprintf('Object identity unavailable. Voting to %s', $this->allowIfObjectIdentityUnavailable? 'grant access' : 'abstain'));
- }
-
- return $this->allowIfObjectIdentityUnavailable ? true : false;
- }
-
- $sids = $this->sidRetrievalStrategy->getSecurityIdentities($token);
-
- try {
- $acl = $this->aclProvider->findAcl($oid, $sids);
-
- if (null === $field && $acl->isGranted($masks, $sids, false)) {
- if (null !== $this->logger) {
- $this->logger->debug('ACL found, permission granted. Voting to grant access');
- }
-
- return true;
- } else if (null !== $field && $acl->isFieldGranted($field, $masks, $sids, false)) {
- if (null !== $this->logger) {
- $this->logger->debug('ACL found, permission granted. Voting to grant access');
- }
-
- return true;
- }
-
- if (null !== $this->logger) {
- $this->logger->debug('ACL found, insufficient permissions. Voting to deny access.');
- }
-
- return false;
- } catch (AclNotFoundException $noAcl) {
- if (null !== $this->logger) {
- $this->logger->debug('No ACL found for the object identity. Voting to deny access.');
- }
-
- return false;
- } catch (NoAceFoundException $noAce) {
- if (null !== $this->logger) {
- $this->logger->debug('ACL found, no ACE applicable. Voting to deny access.');
- }
-
- return false;
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Security\Acl\Voter;
-
-use Symfony\Component\Security\Acl\Voter\FieldVote;
-use Symfony\Component\HttpKernel\Log\LoggerInterface;
-use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
-use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
-use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
-use Symfony\Component\Security\Acl\Model\AclProviderInterface;
-use Symfony\Component\Security\Acl\Model\ObjectIdentityInterface;
-use Symfony\Component\Security\Acl\Permission\PermissionMapInterface;
-use Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface;
-use Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface;
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
-
-/**
- * This voter can be used as a base class for implementing your own permissions.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class AclVoter implements VoterInterface
-{
- private $aclProvider;
- private $permissionMap;
- private $objectIdentityRetrievalStrategy;
- private $securityIdentityRetrievalStrategy;
- private $allowIfObjectIdentityUnavailable;
- private $logger;
-
- public function __construct(AclProviderInterface $aclProvider, ObjectIdentityRetrievalStrategyInterface $oidRetrievalStrategy, SecurityIdentityRetrievalStrategyInterface $sidRetrievalStrategy, PermissionMapInterface $permissionMap, LoggerInterface $logger = null, $allowIfObjectIdentityUnavailable = true)
- {
- $this->aclProvider = $aclProvider;
- $this->permissionMap = $permissionMap;
- $this->objectIdentityRetrievalStrategy = $oidRetrievalStrategy;
- $this->securityIdentityRetrievalStrategy = $sidRetrievalStrategy;
- $this->logger = $logger;
- $this->allowIfObjectIdentityUnavailable = $allowIfObjectIdentityUnavailable;
- }
-
- public function supportsAttribute($attribute)
- {
- return $this->permissionMap->contains($attribute);
- }
-
- public function vote(TokenInterface $token, $object, array $attributes)
- {
- foreach ($attributes as $attribute) {
- if (null === $masks = $this->permissionMap->getMasks((string) $attribute, $object)) {
- continue;
- }
-
- if (null === $object) {
- if (null !== $this->logger) {
- $this->logger->debug(sprintf('Object identity unavailable. Voting to %s', $this->allowIfObjectIdentityUnavailable? 'grant access' : 'abstain'));
- }
-
- return $this->allowIfObjectIdentityUnavailable ? self::ACCESS_GRANTED : self::ACCESS_ABSTAIN;
- } else if ($object instanceof FieldVote) {
- $field = $object->getField();
- $object = $object->getDomainObject();
- } else {
- $field = null;
- }
-
- if ($object instanceof ObjectIdentityInterface) {
- $oid = $object;
- } else if (null === $oid = $this->objectIdentityRetrievalStrategy->getObjectIdentity($object)) {
- if (null !== $this->logger) {
- $this->logger->debug(sprintf('Object identity unavailable. Voting to %s', $this->allowIfObjectIdentityUnavailable? 'grant access' : 'abstain'));
- }
-
- return $this->allowIfObjectIdentityUnavailable ? self::ACCESS_GRANTED : self::ACCESS_ABSTAIN;
- }
-
- if (!$this->supportsClass($oid->getType())) {
- return self::ACCESS_ABSTAIN;
- }
-
- $sids = $this->securityIdentityRetrievalStrategy->getSecurityIdentities($token);
-
- try {
- $acl = $this->aclProvider->findAcl($oid, $sids);
-
- if (null === $field && $acl->isGranted($masks, $sids, false)) {
- if (null !== $this->logger) {
- $this->logger->debug('ACL found, permission granted. Voting to grant access');
- }
-
- return self::ACCESS_GRANTED;
- } else if (null !== $field && $acl->isFieldGranted($field, $masks, $sids, false)) {
- if (null !== $this->logger) {
- $this->logger->debug('ACL found, permission granted. Voting to grant access');
- }
-
- return self::ACCESS_GRANTED;
- }
-
- if (null !== $this->logger) {
- $this->logger->debug('ACL found, insufficient permissions. Voting to deny access.');
- }
-
- return self::ACCESS_DENIED;
- } catch (AclNotFoundException $noAcl) {
- if (null !== $this->logger) {
- $this->logger->debug('No ACL found for the object identity. Voting to deny access.');
- }
-
- return self::ACCESS_DENIED;
- } catch (NoAceFoundException $noAce) {
- if (null !== $this->logger) {
- $this->logger->debug('ACL found, no ACE applicable. Voting to deny access.');
- }
-
- return self::ACCESS_DENIED;
- }
- }
-
- // no attribute was supported
- return self::ACCESS_ABSTAIN;
- }
-
- /**
- * You can override this method when writing a voter for a specific domain
- * class.
- *
- * @param string $class The class name
- *
- * @return Boolean
- */
- public function supportsClass($class)
- {
- return true;
- }
-}
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authentication\Provider;
-
-use Symfony\Component\Security\Core\Exception\BadCredentialsException;
-use JMS\SecurityExtraBundle\Security\Authentication\Token\RunAsUserToken;
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
-
-/**
- * Class which authenticates RunAsTokens.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class RunAsAuthenticationProvider implements AuthenticationProviderInterface
-{
- private $key;
-
- public function __construct($key)
- {
- $this->key = $key;
- }
-
- public function authenticate(TokenInterface $token)
- {
- if (!$this->supports($token)) {
- return null;
- }
-
- if ($token->getKey() === $this->key) {
- return $token;
- } else {
- throw new BadCredentialsException('The keys do not match.');
- }
- }
-
- public function supports(TokenInterface $token)
- {
- return $token instanceof RunAsUserToken;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authentication\Token;
-
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
-
-/**
- * This token is automatically generated by the RunAsManager when an invocation
- * is supposed to be run with a different Token.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class RunAsUserToken extends AbstractToken
-{
- private $originalToken;
- private $key;
- private $credentials;
-
- public function __construct($key, $user, $credentials, array $roles, TokenInterface $originalToken)
- {
- parent::__construct($roles);
-
- $this->originalToken = $originalToken;
- $this->credentials = $credentials;
- $this->key = $key;
-
- $this->setUser($user);
- $this->setAuthenticated(true);
- }
-
- public function getKey()
- {
- return $this->key;
- }
-
- public function getOriginalToken()
- {
- return $this->originalToken;
- }
-
- public function getCredentials()
- {
- return $this->credentials;
- }
-
- public function eraseCredentials()
- {
- parent::eraseCredentials();
-
- $this->credentials = null;
- }
-
- public function serialize()
- {
- return serialize(array(
- $this->originalToken,
- $this->key,
- $this->credentials,
- parent::serialize(),
- ));
- }
-
- public function unserialize($str)
- {
- list($this->originalToken, $this->key, $this->credentials, $parentStr) = unserialize($str);
- parent::unserialize($parentStr);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\AfterInvocation;
-
-use Symfony\Component\HttpKernel\Log\LoggerInterface;
-use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
-use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
-use Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface;
-use Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface;
-use Symfony\Component\Security\Acl\Model\AclProviderInterface;
-use Symfony\Component\Security\Acl\Permission\PermissionMapInterface;
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-use Symfony\Component\Security\Core\Exception\AccessDeniedException;
-
-/**
- * This after invocation provider filters returned objects based on ACLs.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class AclAfterInvocationProvider implements AfterInvocationProviderInterface
-{
- private $aclProvider;
- private $oidRetrievalStrategy;
- private $sidRetrievalStrategy;
- private $permissionMap;
- private $logger;
-
- public function __construct(AclProviderInterface $aclProvider, ObjectIdentityRetrievalStrategyInterface $oidRetrievalStrategy, SecurityIdentityRetrievalStrategyInterface $sidRetrievalStrategy, PermissionMapInterface $permissionMap, LoggerInterface $logger = null)
- {
- $this->aclProvider = $aclProvider;
- $this->oidRetrievalStrategy = $oidRetrievalStrategy;
- $this->sidRetrievalStrategy = $sidRetrievalStrategy;
- $this->permissionMap = $permissionMap;
- $this->logger = $logger;
- }
-
- public function decide(TokenInterface $token, $secureObject, array $attributes, $returnedObject)
- {
- if (null === $returnedObject) {
- if (null !== $this->logger) {
- $this->logger->debug('Returned object was null, skipping security check.');
- }
-
- return null;
- }
-
- foreach ($attributes as $attribute) {
- if (!$this->supportsAttribute($attribute)) {
- continue;
- }
-
- if (null === $oid = $this->oidRetrievalStrategy->getObjectIdentity($returnedObject)) {
- if (null !== $this->logger) {
- $this->logger->debug('Returned object was no domain object, skipping security check.');
- }
-
- return $returnedObject;
- }
-
- $sids = $this->sidRetrievalStrategy->getSecurityIdentities($token);
-
- try {
- $acl = $this->aclProvider->findAcl($oid, $sids);
- if ($acl->isGranted($this->permissionMap->getMasks($attribute, $returnedObject), $sids, false)) {
- return $returnedObject;
- }
-
- if (null !== $this->logger) {
- $this->logger->debug('Token has been denied access for returned object.');
- }
- } catch (AclNotFoundException $noAcl) {
- throw new AccessDeniedException('No applicable ACL found for domain object.');
- } catch (NoAceFoundException $noAce) {
- if (null !== $this->logger) {
- $this->logger->debug('No applicable ACE found for the given Token, denying access.');
- }
- }
-
- throw new AccessDeniedException('ACL has denied access for attribute: '.$attribute);
- }
-
- // no attribute was supported
- return $returnedObject;
- }
-
- public function supportsAttribute($attribute)
- {
- return $this->permissionMap->contains($attribute);
- }
-
- public function supportsClass($className)
- {
- return true;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\AfterInvocation;
-
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-
-/**
- * This is the pendant to the AccessDecisionManager which is used to make
- * access decisions after a method has been executed.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class AfterInvocationManager implements AfterInvocationManagerInterface
-{
- private $providers;
-
- public function __construct(array $providers)
- {
- $this->providers = $providers;
- }
-
- /**
- * {@inheritDoc}
- */
- public function decide(TokenInterface $token, $secureInvocation, array $attributes, $returnedObject)
- {
- foreach ($this->providers as $provider) {
- $returnedObject = $provider->decide($token, $secureInvocation, $attributes, $returnedObject);
- }
-
- return $returnedObject;
- }
-
- /**
- * {@inheritDoc}
- */
- public function supportsAttribute($attribute)
- {
- foreach ($this->providers as $provider) {
- if (true === $provider->supportsAttribute($attribute)) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public function supportsClass($className)
- {
- foreach ($this->providers as $provider) {
- if (true === $provider->supportsClass($className)) {
- return true;
- }
- }
-
- return false;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\AfterInvocation;
-
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-
-/**
- * AfterInvocationManagerInterface
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface AfterInvocationManagerInterface
-{
- /**
- * Makes an access decision after the invocation of a method
- *
- * @param TokenInterface $token
- * @param object $secureObject
- * @param array $attributes
- * @param mixed $returnedValue the value that was returned by the method invocation
- * @return mixed the filter return value
- */
- function decide(TokenInterface $token, $secureObject, array $attributes, $returnedValue);
-
- /**
- * Determines whether the given attribute is supported
- *
- * @param string $attribute
- * @return Boolean
- */
- function supportsAttribute($attribute);
-
- /**
- * Determines whether the given class is supported
- *
- * @param string $className the class of the secure object
- * @return Boolean
- */
- function supportsClass($className);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\AfterInvocation;
-
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-
-/**
- * AfterInvocationProviderInterface
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface AfterInvocationProviderInterface
-{
- function decide(TokenInterface $token, $secureObject, array $attributes, $returnedObject);
- function supportsAttribute($attribute);
- function supportsClass($className);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-class AndExpression implements ExpressionInterface
-{
- public $left;
- public $right;
-
- public function __construct(ExpressionInterface $left, ExpressionInterface $right)
- {
- $this->left = $left;
- $this->right = $right;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-class ArrayExpression implements ExpressionInterface
-{
- public $elements;
-
- public function __construct(array $elements)
- {
- $this->elements = $elements;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-class ConstantExpression implements ExpressionInterface
-{
- public $value;
-
- public function __construct($value)
- {
- $this->value = $value;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-interface ExpressionInterface
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-class FunctionExpression implements ExpressionInterface
-{
- /** READ-ONLY */
- public $name;
- public $args;
-
- public function __construct($name, array $args)
- {
- $this->name = $name;
- $this->args = $args;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-class GetItemExpression
-{
- public $array;
- public $key;
-
- public function __construct(ExpressionInterface $array, ExpressionInterface $key)
- {
- $this->array = $array;
- $this->key = $key;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-class GetPropertyExpression implements ExpressionInterface
-{
- public $object;
- public $name;
-
- public function __construct(ExpressionInterface $obj, $name)
- {
- $this->object = $obj;
- $this->name = $name;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-class IsEqualExpression implements ExpressionInterface
-{
- public $left;
- public $right;
-
- public function __construct(ExpressionInterface $left, ExpressionInterface $right)
- {
- $this->left = $left;
- $this->right = $right;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-class MethodCallExpression implements ExpressionInterface
-{
- public $object;
- public $method;
- public $args;
-
- public function __construct(ExpressionInterface $obj, $method, array $args)
- {
- $this->object = $obj;
- $this->method = $method;
- $this->args = $args;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php\r
-\r
-/*\r
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;\r
-\r
-class NotExpression implements ExpressionInterface\r
-{\r
- public $expr;\r
- \r
- public function __construct(ExpressionInterface $expr)\r
- {\r
- $this->expr = $expr;\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-class OrExpression implements ExpressionInterface
-{
- public $left;
- public $right;
-
- public function __construct(ExpressionInterface $left, ExpressionInterface $right)
- {
- $this->left = $left;
- $this->right = $right;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-class ParameterExpression implements ExpressionInterface
-{
- public $name;
-
- public function __construct($name)
- {
- $this->name = $name;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast;
-
-class VariableExpression implements ExpressionInterface
-{
- public $name;
- public $allowNull;
-
- public function __construct($name, $allowNull = false)
- {
- $this->name = $name;
- $this->allowNull = $allowNull;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler;
-
-class AndExpressionCompiler extends BinaryExprCompiler
-{
- public function getType()
- {
- return 'JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\AndExpression';
- }
-
- protected function getOperator()
- {
- return '&&';
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ExpressionInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-/**
- * Base Compiler for Binary Operators.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-abstract class BinaryExprCompiler implements TypeCompilerInterface
-{
- public function compilePreconditions(ExpressionCompiler $compiler, ExpressionInterface $expr)
- {
- $compiler
- ->compilePreconditions($expr->left)
- ->compilePreconditions($expr->right)
- ;
- }
-
- public function compile(ExpressionCompiler $compiler, ExpressionInterface $expr)
- {
- $compiler
- ->write("(")
- ->compileInternal($expr->left)
- ->write(") ".$this->getOperator()." (")
- ->compileInternal($expr->right)
- ->write(")")
- ;
- }
-
- abstract protected function getOperator();
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler;
-
-use Symfony\Component\DependencyInjection\ContainerInterface;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ExpressionInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\VariableExpressionCompiler;
-
-class ContainerAwareVariableCompiler extends VariableExpressionCompiler
-{
- private $serviceMap = array();
- private $parameterMap = array();
-
- public function setMaps(array $serviceMap, array $parameterMap)
- {
- $this->serviceMap = $serviceMap;
- $this->parameterMap = $parameterMap;
- }
-
- public function compile(ExpressionCompiler $compiler, ExpressionInterface $expr)
- {
- if (isset($this->serviceMap[$expr->name])) {
- $compiler->write("\$context['container']->get('{$this->serviceMap[$expr->name]}'");
-
- if ($expr->allowNull) {
- $compiler->write(", ".ContainerInterface::NULL_ON_INVALID_REFERENCE);
- }
-
- $compiler->write(")");
-
- return;
- }
-
- if (isset($this->parameterMap[$expr->name])) {
- $compiler->write("\$context['container']->getParameter('{$this->parameterMap[$expr->name]}')");
-
- return;
- }
-
- parent::compile($compiler, $expr);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\Func;
-
-use JMS\SecurityExtraBundle\Exception\InvalidArgumentException;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-abstract class AuthenticationTrustFunctionCompiler implements FunctionCompilerInterface
-{
- public function compilePreconditions(ExpressionCompiler $compiler, FunctionExpression $function)
- {
- if (!empty($function->args)) {
- throw new InvalidArgumentException(sprintf('The '.$this->getName().'() function does not accept any arguments, but got "%s".', var_export($function->args, true)));
- }
-
- $compiler->verifyItem('token', 'Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\Func;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-interface FunctionCompilerInterface
-{
- function getName();
- function compilePreconditions(ExpressionCompiler $compiler, FunctionExpression $function);
- function compile(ExpressionCompiler $compiler, FunctionExpression $function);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\Func;
-
-use JMS\SecurityExtraBundle\Exception\RuntimeException;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-class HasAnyRoleFunctionCompiler implements FunctionCompilerInterface
-{
- private $rolesExpr;
-
- public function getName()
- {
- return 'hasAnyRole';
- }
-
- public function compilePreconditions(ExpressionCompiler $compiler, FunctionExpression $function)
- {
- if (0 === count($function->args)) {
- throw new RuntimeException('The function hasAnyRole() expects at least one argument, but got none.');
- }
-
- $this->rolesExpr = $compiler->getRolesExpr();
- }
-
- public function compile(ExpressionCompiler $compiler, FunctionExpression $function)
- {
- $compiler->write("(");
-
- $first = true;
- foreach ($function->args as $arg) {
- if (!$first) {
- $compiler->write(" || ");
- }
- $first = false;
-
- $compiler
- ->write("isset({$this->rolesExpr}[")
- ->compileInternal($arg)
- ->write("])")
- ;
- }
-
- $compiler->write(")");
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\Func;
-
-use JMS\SecurityExtraBundle\Exception\RuntimeException;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-class HasRoleFunctionCompiler implements FunctionCompilerInterface
-{
- private $rolesExpr;
-
- public function getName()
- {
- return 'hasRole';
- }
-
- public function compilePreconditions(ExpressionCompiler $compiler, FunctionExpression $function)
- {
- if (1 !== count($function->args)) {
- throw new RuntimeException(sprintf('The hasRole() function expects exactly one argument, but got "%s".', var_export($function->args, true)));
- }
-
- $this->rolesExpr = $compiler->getRolesExpr();
- }
-
- public function compile(ExpressionCompiler $compiler, FunctionExpression $function)
- {
- $compiler
- ->write("isset({$this->rolesExpr}[")
- ->compileInternal($function->args[0])
- ->write("])")
- ;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\Func;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-class IsAnonymousFunctionCompiler extends AuthenticationTrustFunctionCompiler
-{
- public function getName()
- {
- return 'isAnonymous';
- }
-
- public function compile(ExpressionCompiler $compiler, FunctionExpression $function)
- {
- $compiler
- ->compileInternal(new VariableExpression('trust_resolver'))
- ->write("->isAnonymous(\$context['token'])");
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\Func;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-class IsAuthenticatedFunctionCompiler extends AuthenticationTrustFunctionCompiler
-{
- public function getName()
- {
- return 'isAuthenticated';
- }
-
- public function compile(ExpressionCompiler $compiler, FunctionExpression $function)
- {
- $compiler
- ->write("!")
- ->compileInternal(new VariableExpression('trust_resolver'))
- ->write("->isAnonymous(\$context['token'])")
- ;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\Func;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-class IsFullyAuthenticatedFunctionCompiler extends AuthenticationTrustFunctionCompiler
-{
- public function getName()
- {
- return 'isFullyAuthenticated';
- }
-
- public function compile(ExpressionCompiler $compiler, FunctionExpression $function)
- {
- $compiler
- ->compileInternal(new VariableExpression('trust_resolver'))
- ->write("->isFullFledged(\$context['token'])");
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\Func;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-class IsRememberMeFunctionCompiler extends AuthenticationTrustFunctionCompiler
-{
- public function getName()
- {
- return 'isRememberMe';
- }
-
- public function compile(ExpressionCompiler $compiler, FunctionExpression $function)
- {
- $compiler
- ->compileInternal(new VariableExpression('trust_resolver'))
- ->write("->isRememberMe(\$context['token'])");
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler;
-
-class IsEqualExpressionCompiler extends BinaryExprCompiler
-{
- public function getType()
- {
- return 'JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\IsEqualExpression';
- }
-
- protected function getOperator()
- {
- return '===';
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php\r
-\r
-/*\r
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler;\r
-\r
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ExpressionInterface;
-\r
-class NotExpressionCompiler implements TypeCompilerInterface\r
-{\r
- public function getType()\r
- {\r
- return 'JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\NotExpression';\r
- }\r
- \r
- public function compilePreconditions(ExpressionCompiler $compiler, ExpressionInterface $expr)\r
- {\r
- $compiler->compilePreconditions($expr->expr);\r
- }\r
- \r
- public function compile(ExpressionCompiler $compiler, ExpressionInterface $expr)\r
- {\r
- $compiler\r
- ->write('!(')\r
- ->compileInternal($expr->expr)\r
- ->write(')')\r
- ;\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler;
-
-class OrExpressionCompiler extends BinaryExprCompiler
-{
- public function getType()
- {
- return 'JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\OrExpression';
- }
-
- protected function getOperator()
- {
- return '||';
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ExpressionInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\TypeCompilerInterface;
-
-class ParameterExpressionCompiler implements TypeCompilerInterface
-{
- public function getType()
- {
- return 'JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ParameterExpression';
- }
-
- public function compilePreconditions(ExpressionCompiler $compiler, ExpressionInterface $parameter)
- {
- $compiler->verifyItem('object', 'CG\Proxy\MethodInvocation');
-
- if (!isset($compiler->attributes['parameter_mapping_name'])) {
- $this->addParameterMapping($compiler);
- }
-
- $compiler
- ->writeln("if (!isset(\${$compiler->attributes['parameter_mapping_name']}['{$parameter->name}'])) {")
- ->indent()
- ->write("throw new RuntimeException(sprintf('There is no parameter with name \"{$parameter->name}\" for method \"%s\".', ")
- ->compileInternal(new VariableExpression('object'))
- ->writeln("));")
- ->outdent()
- ->write("}\n\n")
- ;
- }
-
- public function compile(ExpressionCompiler $compiler, ExpressionInterface $parameter)
- {
- $compiler
- ->compileInternal(new VariableExpression('object'))
- ->write("->arguments[")
- ->write("\${$compiler->attributes['parameter_mapping_name']}")
- ->write("['{$parameter->name}']]")
- ;
- }
-
- private function addParameterMapping(ExpressionCompiler $compiler)
- {
- $name = $compiler->nextName();
- $indexName = $compiler->nextName();
- $paramName = $compiler->nextName();
-
- $compiler
- ->setAttribute('parameter_mapping_name', $name)
- ->writeln("\$$name = array();")
- ->write("foreach (")
- ->compileInternal(new VariableExpression('object'))
- ->writeln("->reflection->getParameters() as \$$indexName => \$$paramName) {")
- ->indent()
- ->writeln("\${$name}[\${$paramName}->name] = \$$indexName;")
- ->outdent()
- ->writeln("}\n")
- ;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ExpressionInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-interface TypeCompilerInterface
-{
- function getType();
- function compilePreconditions(ExpressionCompiler $compiler, ExpressionInterface $expr);
- function compile(ExpressionCompiler $compiler, ExpressionInterface $expr);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ExpressionInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-class VariableExpressionCompiler implements TypeCompilerInterface
-{
- public function getType()
- {
- return 'JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression';
- }
-
- public function compilePreconditions(ExpressionCompiler $compiler, ExpressionInterface $expr)
- {
- if ('user' === $expr->name) {
- $compiler
- ->setAttribute('user_var_name', $name = $compiler->nextName())
- ->write("\$$name = ")
- ->compileInternal(new VariableExpression('token'))
- ->write("->getUser();\n\n")
- ;
- }
- }
-
- public function compile(ExpressionCompiler $compiler, ExpressionInterface $expr)
- {
- if ('permitAll' === $expr->name) {
- $compiler->write('true');
-
- return;
- }
-
- if ('denyAll' === $expr->name) {
- $compiler->write('false');
-
- return;
- }
-
- if ('user' === $expr->name) {
- $compiler->write("\${$compiler->attributes['user_var_name']}");
-
- return;
- }
-
- if ($expr->allowNull) {
- $compiler->write("(isset(\$context['{$expr->name}']) ? ");
- }
-
- $compiler->write("\$context['{$expr->name}']");
-
- if ($expr->allowNull) {
- $compiler->write(" : null)");
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionHandlerInterface;
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-use Symfony\Component\DependencyInjection\ContainerInterface;
-
-/**
- * Lazy-loading container aware expression handler.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class ContainerAwareExpressionHandler implements ExpressionHandlerInterface
-{
- private $container;
-
- public function __construct(ContainerInterface $container)
- {
- $this->container = $container;
- }
-
- public function createContext(TokenInterface $token, $object)
- {
- return array(
- 'container' => $this->container,
- 'token' => $token,
- 'object' => $object,
- );
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression;
-
-use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
-use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-
-class DefaultExpressionHandler implements ExpressionHandlerInterface
-{
- private $trustResolver;
- private $roleHierarchy;
-
- public function __construct(AuthenticationTrustResolverInterface $trustResolver,
- RoleHierarchyInterface $roleHierarchy = null)
- {
- $this->trustResolver = $trustResolver;
- $this->roleHierarchy = $roleHierarchy;
- }
-
- public function createContext(TokenInterface $token, $object)
- {
- $context = array(
- 'token' => $token,
- 'object' => $object,
- 'trust_resolver' => $this->trustResolver,
- );
-
- if (null !== $this->roleHierarchy) {
- $context['role_hierarchy'] = $this->roleHierarchy;
- }
-
- return $context;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression;
-
-final class Expression
-{
- /** READ-ONLY */
- public $expression;
-
- public function __construct($expression)
- {
- $this->expression = $expression;
- }
-
- public function getHashCode()
- {
- return sha1($this->expression);
- }
-
- public function __toString()
- {
- return 'EXPRESSION('.$this->expression.')';
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression;
-
-use JMS\SecurityExtraBundle\Exception\RuntimeException;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\TypeCompilerInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\IsEqualExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\Func\FunctionCompilerInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ExpressionInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\OrExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\MethodCallExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\GetPropertyExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\GetItemExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ConstantExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ArrayExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\AndExpression;
-
-class ExpressionCompiler
-{
- public $attributes = array();
-
- private $indentationLevel = 0;
- private $indentationSpaces = 4;
-
- private $nameCount = 0;
- private $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
- private $charCount = 52;
- private $reservedNames = array('context' => true);
-
- private $itemExists = array();
- private $itemType = array();
- private $rolesName;
-
- private $code;
- private $parser;
- private $typeCompilers;
- private $functionCompilers;
-
- public function __construct()
- {
- $this->addTypeCompiler(new Compiler\AndExpressionCompiler());
- $this->addTypeCompiler(new Compiler\IsEqualExpressionCompiler());
- $this->addTypeCompiler(new Compiler\OrExpressionCompiler());
- $this->addTypeCompiler(new Compiler\VariableExpressionCompiler());
- $this->addTypeCompiler(new Compiler\NotExpressionCompiler());
-
- $this->functionCompilers = array(
- 'isAnonymous' => new Compiler\Func\IsAnonymousFunctionCompiler(),
- 'isAuthenticated' => new Compiler\Func\IsAuthenticatedFunctionCompiler(),
- 'isRememberMe' => new Compiler\Func\IsRememberMeFunctionCompiler(),
- 'isFullyAuthenticated' => new Compiler\Func\IsFullyAuthenticatedFunctionCompiler(),
- 'hasRole' => new Compiler\Func\HasRoleFunctionCompiler(),
- 'hasAnyRole' => new Compiler\Func\HasAnyRoleFunctionCompiler(),
- );
- }
-
- public function setAttribute($name, $value)
- {
- $this->attributes[$name] = $value;
-
- return $this;
- }
-
- public function addTypeCompiler(TypeCompilerInterface $compiler)
- {
- $this->typeCompilers[$compiler->getType()] = $compiler;
- }
-
- public function addFunctionCompiler(FunctionCompilerInterface $compiler)
- {
- $this->functionCompilers[$compiler->getName()] = $compiler;
- }
-
- public function compileExpression(Expression $expr)
- {
- return $this->compile($this->getParser()->parse($expr->expression),
- $expr->expression);
- }
-
- public function compile(ExpressionInterface $expr, $raw = null)
- {
- $this->nameCount = 0;
- $this->code = '';
- $this->itemExists = $this->itemType = $this->attributes = array();
- $this->rolesName = null;
-
- if ($raw) {
- $this->writeln('// Expression: '.$raw);
- }
-
- $this
- ->writeln('return function(array $context) {')
- ->indent()
- ->compilePreconditions($expr)
- ->write('return ')
- ->compileInternal($expr)
- ->writeln(';')
- ->outdent()
- ->writeln('};')
- ;
-
- return $this->code;
- }
-
- public function indent()
- {
- $this->indentationLevel += 1;
-
- return $this;
- }
-
- public function outdent()
- {
- $this->indentationLevel -= 1;
-
- if ($this->indentationLevel < 0) {
- throw new RuntimeException('The identation level cannot be less than zero.');
- }
-
- return $this;
- }
-
- public function writeln($content)
- {
- $this->write($content."\n");
-
- return $this;
- }
-
- public function getRolesExpr()
- {
- if (null !== $this->rolesName) {
- return '$'.$this->rolesName;
- }
-
- $this->verifyItem('token', 'Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
-
- $this->rolesName = $rolesName = $this->nextName();
- $hierarchyName = $this->nextName();
- $tmpName = $this->nextName();
- $this
- ->writeln("\$$rolesName = \$context['token']->getRoles();")
- ->write("if (null !== \$$hierarchyName = ")
- ->compileInternal(new VariableExpression('role_hierarchy', true))
- ->writeln(") {")
- ->indent()
- ->writeln("\$$rolesName = \${$hierarchyName}->getReachableRoles(\$$rolesName);")
- ->outdent()
- ->write("}\n\n")
- ->writeln("\$$tmpName = array();")
- ->writeln("foreach (\$$rolesName as \$role) {")
- ->indent()
- ->writeln("\${$tmpName}[\$role->getRole()] = true;")
- ->outdent()
- ->writeln("}")
- ->write("\$$rolesName = \$$tmpName;\n\n")
- ;
-
- return '$'.$rolesName;
- }
-
- public function verifyItem($key, $expectedType = null)
- {
- if (!isset($this->itemExists[$key])) {
- $this->itemExists[$key] = true;
-
- $this
- ->writeln("if (!isset(\$context['$key'])) {")
- ->indent()
- ->writeln("throw new RuntimeException('The context contains no item with key \"$key\".');")
- ->outdent()
- ->write("}\n\n")
- ;
- }
-
- if (null !== $expectedType) {
- if (isset($this->itemType[$key])) {
- if ($this->itemType[$key] !== $expectedType) {
- throw new RuntimeException(sprintf('Cannot verify that item "%s" is of type "%s" because it is already expected to be of type "%s".',
- $key, $expectedType, $this->itemType[$key]
- ));
- }
-
- return $this;
- }
-
- $this
- ->writeln("if (!\$context['$key'] instanceof $expectedType) {")
- ->indent()
- ->writeln("throw new RuntimeException(sprintf('The item \"$key\" is expected to be of type \"$expectedType\", but got \"%s\".', get_class(\$context['$key'])));")
- ->outdent()
- ->write("}\n\n")
- ;
- }
-
- return $this;
- }
-
- public function write($content)
- {
- $lines = explode("\n", $content);
- for ($i=0,$c=count($lines); $i<$c; $i++) {
- if ($this->indentationLevel > 0
- && !empty($lines[$i])
- && (empty($this->code) || "\n" === substr($this->code, -1))) {
- $this->code .= str_repeat(' ', $this->indentationLevel * $this->indentationSpaces);
- }
-
- $this->code .= $lines[$i];
-
- if ($i+1 < $c) {
- $this->code .= "\n";
- }
- }
-
- return $this;
- }
-
- public function nextName()
- {
- while (true) {
- $name = '';
- $i = $this->nameCount;
-
- $name .= $this->chars[$i % $this->charCount];
- $i = intval($i / $this->charCount);
-
- while ($i > 0) {
- $i -= 1;
- $name .= $this->chars[$i % $this->charCount];
- $i = intval($i / $this->charCount);
- }
-
- $this->nameCount += 1;
-
- // check that the name is not reserved
- if (isset($this->reservedNames[$name])) {
- continue;
- }
-
- return $name;
- }
- }
-
- public function compilePreconditions(ExpressionInterface $expr)
- {
- if ($typeCompiler = $this->findTypeCompiler(get_class($expr))) {
- $typeCompiler->compilePreconditions($this, $expr);
-
- return $this;
- }
-
- if ($expr instanceof FunctionExpression) {
- $this->getFunctionCompiler($expr->name)->compilePreconditions($this, $expr);
-
- foreach ($expr->args as $arg) {
- $this->compilePreconditions($arg);
- }
-
- return $this;
- }
-
- if ($expr instanceof VariableExpression) {
- $this->getVariableCompiler($expr->name)->compilePreconditions($this, $expr);
-
- return $this;
- }
-
- if ($expr instanceof MethodCallExpression) {
- $this->compilePreconditions($expr->object);
-
- foreach ($expr->args as $arg) {
- $this->compilePreconditions($arg);
- }
-
- return $this;
- }
-
- if ($expr instanceof GetPropertyExpression) {
- $this->compilePreconditions($expr->object);
-
- return $this;
- }
-
- return $this;
- }
-
- public function compileInternal(ExpressionInterface $expr)
- {
- if ($typeCompiler = $this->findTypeCompiler(get_class($expr))) {
- $typeCompiler->compile($this, $expr);
-
- return $this;
- }
-
- if ($expr instanceof ArrayExpression) {
- $this->code .= 'array(';
- foreach ($expr->elements as $key => $value) {
- $this->code .= var_export($key, true).' => ';
- $this->compileInternal($value);
- $this->code .= ',';
- }
- $this->code .= ')';
-
- return $this;
- }
-
- if ($expr instanceof ConstantExpression) {
- $this->code .= var_export($expr->value, true);
-
- return $this;
- }
-
- if ($expr instanceof FunctionExpression) {
- $this->getFunctionCompiler($expr->name)->compile($this, $expr);
-
- return $this;
- }
-
- if ($expr instanceof GetItemExpression) {
- $this->compileInternal($expr->array);
- $this->code .= '['.$expr->key.']';
-
- return $this;
- }
-
- if ($expr instanceof GetPropertyExpression) {
- $this->compileInternal($expr->object);
- $this->code .= '->'.$expr->name;
-
- return $this;
- }
-
- if ($expr instanceof MethodCallExpression) {
- $this->compileInternal($expr->object);
- $this->code .= '->'.$expr->method.'(';
-
- $first = true;
- foreach ($expr->args as $arg) {
- if (!$first) {
- $this->code .= ', ';
- }
- $first = false;
-
- $this->compileInternal($arg);
- }
- $this->code .= ')';
-
- return $this;
- }
-
- throw new RuntimeException(sprintf('Unknown expression "%s".', get_class($expr)));
- }
-
- public function getFunctionCompiler($name)
- {
- if (!isset($this->functionCompilers[$name])) {
- throw new RuntimeException(sprintf('There is no compiler for function "%s".', $name));
- }
-
- return $this->functionCompilers[$name];
- }
-
- private function findTypeCompiler($type)
- {
- return isset($this->typeCompilers[$type]) ? $this->typeCompilers[$type] : null;
- }
-
- private function getParser()
- {
- if (null !== $this->parser) {
- return $this->parser;
- }
-
- return $this->parser = new ExpressionParser();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression;
-
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-
-interface ExpressionHandlerInterface
-{
- function createContext(TokenInterface $token, $object);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression;
-
-use JMS\SecurityExtraBundle\Exception\InvalidArgumentException;
-
-final class ExpressionLexer
-{
- public $token;
- public $lookahead;
-
- private $tokens;
- private $pointer;
-
- const T_STRING = 1;
- const T_IDENTIFIER = 2;
- const T_NONE = 3;
- const T_COMMA = 4;
- const T_OPEN_PARENTHESIS = 5;
- const T_CLOSE_PARENTHESIS = 6;
- const T_AND = 7;
- const T_OR = 8;
- const T_PARAMETER = 9;
- const T_OBJECT_OPERATOR = 10;
- const T_OPEN_BRACKET = 11;
- const T_CLOSE_BRACKET = 12;
- const T_OPEN_BRACE = 13;
- const T_CLOSE_BRACE = 14;
- const T_COLON = 15;
- const T_IS_EQUAL = 16;
- const T_NOT = 17;
-
- public static function getLiteral($type)
- {
- static $constants;
-
- if (null === $constants) {
- $ref = new \ReflectionClass(get_called_class());
- $constants = $ref->getConstants();
- }
-
- if (false === $literal = array_search($type, $constants, true)) {
- throw new InvalidArgumentException(sprintf('There is no token of value "%s".', $type));
- }
-
- return $literal;
- }
-
- public function initialize($input)
- {
- static $pattern = '/(#?[a-z][a-z0-9]*|\'(?:[^\']|(?<=\\\\)\')*\'|"(?:[^"]|(?<=\\\\)")*"|&&|\|\||==)|\s+|(.)/i';
-
- $parts = preg_split($pattern, $input, -1, PREG_SPLIT_OFFSET_CAPTURE
- | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
-
- $tokens = array();
- foreach ($parts as $part) {
- list($value, $position) = $part;
- $type = self::T_NONE;
-
- if ("'" === $value[0] || '"' === $value[0]) {
- $type = self::T_STRING;
- $value = substr($value, 1, -1);
- } else if (',' === $value) {
- $type = self::T_COMMA;
- } else if ('(' === $value) {
- $type = self::T_OPEN_PARENTHESIS;
- } else if (')' === $value) {
- $type = self::T_CLOSE_PARENTHESIS;
- } else if ('[' === $value) {
- $type = self::T_OPEN_BRACKET;
- } else if (']' === $value) {
- $type = self::T_CLOSE_BRACKET;
- } else if ('{' === $value) {
- $type = self::T_OPEN_BRACE;
- } else if ('}' === $value) {
- $type = self::T_CLOSE_BRACE;
- } else if ('&&' === $value || 'and' === strtolower($value)) {
- $type = self::T_AND;
- } else if ('||' === $value || 'or' === strtolower($value)) {
- $type = self::T_OR;
- } else if ('!' === $value || 'not' === strtolower($value)) {
- $type = self::T_NOT;
- } else if (':' === $value) {
- $type = self::T_COLON;
- } else if ('.' === $value) {
- $type = self::T_OBJECT_OPERATOR;
- } else if ('==' === $value) {
- $type = self::T_IS_EQUAL;
- } else if ('#' === $value[0]) {
- $type = self::T_PARAMETER;
- $value = substr($value, 1);
- } else if (ctype_alpha($value)) {
- $type = self::T_IDENTIFIER;
- }
-
- $tokens[] = array(
- 'type' => $type,
- 'value' => $value,
- 'position' => $position,
- );
- }
-
- $this->tokens = $tokens;
- $this->pointer = -1;
- $this->next();
- }
-
- public function next()
- {
- $this->pointer += 1;
- $this->token = $this->lookahead;
- $this->lookahead = isset($this->tokens[$this->pointer]) ?
- $this->tokens[$this->pointer] : null;
-
- return $this->lookahead !== null;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\NotExpression;
-
-use JMS\SecurityExtraBundle\Exception\RuntimeException;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\IsEqualExpression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ParameterExpression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ConstantExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\OrExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\AndExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ArrayExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\GetItemExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\GetPropertyExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\MethodCallExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ExpressionInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-
-final class ExpressionParser
-{
- const PRECEDENCE_OR = 10;
- const PRECEDENCE_AND = 15;
- const PRECEDENCE_IS_EQUAL = 20;
- const PRECEDENCE_NOT = 30;
-
- private $lexer;
-
- public function __construct()
- {
- $this->lexer = new ExpressionLexer();
- }
-
- public function parse($str)
- {
- $this->lexer->initialize($str);
-
- return $this->Expression();
- }
-
- private function Expression($precedence = 0)
- {
- $expr = $this->Primary();
-
- while (true) {
- if (ExpressionLexer::T_AND === $this->lexer->lookahead['type']
- && $precedence <= self::PRECEDENCE_AND) {
- $this->lexer->next();
-
- $expr = new AndExpression($expr, $this->Expression(
- self::PRECEDENCE_AND + 1));
- continue;
- }
-
- if (ExpressionLexer::T_OR === $this->lexer->lookahead['type']
- && $precedence <= self::PRECEDENCE_OR) {
- $this->lexer->next();
-
- $expr = new OrExpression($expr, $this->Expression(
- self::PRECEDENCE_OR + 1));
- continue;
- }
-
- if (ExpressionLexer::T_IS_EQUAL === $this->lexer->lookahead['type']
- && $precedence <= self::PRECEDENCE_IS_EQUAL) {
- $this->lexer->next();
-
- $expr = new IsEqualExpression($expr, $this->Expression(
- self::PRECEDENCE_IS_EQUAL + 1));
- continue;
- }
-
- break;
- }
-
- return $expr;
- }
-
- private function Primary()
- {
- if (ExpressionLexer::T_NOT === $this->lexer->lookahead['type']) {
- $this->lexer->next();
- $expr = new NotExpression($this->Expression(self::PRECEDENCE_NOT));
-
- return $this->Suffix($expr);
- }
-
- if (ExpressionLexer::T_OPEN_PARENTHESIS === $this->lexer->lookahead['type']) {
- $this->lexer->next();
- $expr = $this->Expression();
- $this->match(ExpressionLexer::T_CLOSE_PARENTHESIS);
-
- return $this->Suffix($expr);
- }
-
- if (ExpressionLexer::T_STRING === $this->lexer->lookahead['type']) {
- return new ConstantExpression($this->match(ExpressionLexer::T_STRING));
- }
-
- if (ExpressionLexer::T_OPEN_BRACE === $this->lexer->lookahead['type']) {
- return $this->Suffix($this->MapExpr());
- }
-
- if (ExpressionLexer::T_OPEN_BRACKET === $this->lexer->lookahead['type']) {
- return $this->Suffix($this->ListExpr());
- }
-
- if (ExpressionLexer::T_IDENTIFIER === $this->lexer->lookahead['type']) {
- $name = $this->match(ExpressionLexer::T_IDENTIFIER);
-
- if (ExpressionLexer::T_OPEN_PARENTHESIS === $this->lexer->lookahead['type']) {
- $args = $this->Arguments();
-
- return $this->Suffix(new FunctionExpression($name, $args));
- }
-
- return $this->Suffix(new VariableExpression($name));
- }
-
- if (ExpressionLexer::T_PARAMETER === $this->lexer->lookahead['type']) {
- return $this->Suffix(new ParameterExpression($this->match(ExpressionLexer::T_PARAMETER)));
- }
-
- $this->error('primary expression');
- }
-
- private function ListExpr()
- {
- $this->match(ExpressionLexer::T_OPEN_BRACKET);
-
- $elements = array();
- while (ExpressionLexer::T_CLOSE_BRACKET !== $this->lexer->lookahead['type']) {
- $elements[] = $this->Expression();
-
- if (ExpressionLexer::T_COMMA !== $this->lexer->lookahead['type']) {
- break;
- }
- $this->lexer->next();
- }
-
- $this->match(ExpressionLexer::T_CLOSE_BRACKET);
-
- return new ArrayExpression($elements);
- }
-
- private function MapExpr()
- {
- $this->match(ExpressionLexer::T_OPEN_BRACE);
-
- $entries = array();
- while (ExpressionLexer::T_CLOSE_BRACE !== $this->lexer->lookahead['type']) {
- $key = $this->match(ExpressionLexer::T_STRING);
- $this->match(ExpressionLexer::T_COLON);
- $entries[$key] = $this->Expression();
-
- if (ExpressionLexer::T_COMMA !== $this->lexer->lookahead['type']) {
- break;
- }
-
- $this->lexer->next();
- }
-
- $this->match(ExpressionLexer::T_CLOSE_BRACE);
-
- return new ArrayExpression($entries);
- }
-
- private function Suffix(ExpressionInterface $expr)
- {
- while (true) {
- if (ExpressionLexer::T_OBJECT_OPERATOR === $this->lexer->lookahead['type']) {
- $this->lexer->next();
- $name = $this->match(ExpressionLexer::T_IDENTIFIER);
-
- if (ExpressionLexer::T_OPEN_PARENTHESIS === $this->lexer->lookahead['type']) {
- $args = $this->Arguments();
- $expr = new MethodCallExpression($expr, $name, $args);
- continue;
- }
-
- $expr = new GetPropertyExpression($expr, $name);
- continue;
- }
-
- if (ExpressionLexer::T_OPEN_BRACKET === $this->lexer->lookahead['type']) {
- $this->lexer->next();
- $key = $this->Expression();
- $this->match(ExpressionLexer::T_CLOSE_BRACKET);
- $expr = new GetItemExpression($expr, $key);
- continue;
- }
-
- break;
- }
-
- return $expr;
- }
-
- private function FunctionCall()
- {
- $name = $this->match(ExpressionLexer::T_IDENTIFIER);
- $args = $this->Arguments();
-
- return new FunctionExpression($name, $args);
- }
-
- private function Arguments()
- {
- $this->match(ExpressionLexer::T_OPEN_PARENTHESIS);
- $args = array();
-
- while (ExpressionLexer::T_CLOSE_PARENTHESIS !== $this->lexer->lookahead['type']) {
- $args[] = $this->Expression();
-
- if (ExpressionLexer::T_COMMA !== $this->lexer->lookahead['type']) {
- break;
- }
-
- $this->match(ExpressionLexer::T_COMMA);
- }
- $this->match(ExpressionLexer::T_CLOSE_PARENTHESIS);
-
- return $args;
- }
-
- private function Value()
- {
- return $this->matchAny(array(ExpressionLexer::T_STRING));
- }
-
- private function matchAny(array $types)
- {
- if (null !== $this->lexer->lookahead) {
- foreach ($types as $type) {
- if ($type === $this->lexer->lookahead['type']) {
- $this->lexer->next();
-
- return $this->lexer->token['value'];
- }
- }
- }
-
- $this->error(sprintf('one of these tokens "%s"',
- implode('", "', array_map(array('JMS\SecurityExtraBundle\Security\Authorization\Expression\Lexer', 'getLiteral'), $types))
- ));
- }
-
- private function match($type)
- {
- if (null === $this->lexer->lookahead
- || $type !== $this->lexer->lookahead['type']) {
- $this->error(sprintf('token "%s"', ExpressionLexer::getLiteral($type)));
- }
-
- $this->lexer->next();
-
- return $this->lexer->token['value'];
- }
-
- private function error($expected)
- {
- $actual = null === $this->lexer->lookahead ? 'end of file'
- : sprintf('token "%s" with value "%s" at position %d',
- ExpressionLexer::getLiteral($this->lexer->lookahead['type']),
- $this->lexer->lookahead['value'],
- $this->lexer->lookahead['position']);
-
- throw new RuntimeException(sprintf('Expected %s, but got %s.', $expected, $actual));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression;
-
-use JMS\SecurityExtraBundle\Exception\RuntimeException;
-use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
-use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
-
-/**
- * Expression-based voter.
- *
- * This voter allows to use complex access expression in a high-performance
- * way. This is the preferred voter for any non-simple access checks.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class ExpressionVoter implements VoterInterface
-{
- private $evaluators = array();
- private $compiler;
- private $cacheDir;
- private $expressionHandler;
-
- public function __construct(ExpressionHandlerInterface $expressionHandler) {
- $this->expressionHandler = $expressionHandler;
- }
-
- public function setCacheDir($cacheDir)
- {
- $this->cacheDir = $cacheDir;
- }
-
- public function setCompiler(ExpressionCompiler $compiler)
- {
- $this->compiler = $compiler;
- }
-
- public function vote(TokenInterface $token, $object, array $attributes)
- {
- $result = VoterInterface::ACCESS_ABSTAIN;
-
- foreach ($attributes as $attribute) {
- if (!$attribute instanceof Expression) {
- continue;
- }
-
- $result = VoterInterface::ACCESS_DENIED;
- if (!isset($this->evaluators[$attribute->expression])) {
- $this->evaluators[$attribute->expression] =
- $this->createEvaluator($attribute);
- }
-
- if (call_user_func($this->evaluators[$attribute->expression],
- $this->expressionHandler->createContext($token, $object))) {
- return VoterInterface::ACCESS_GRANTED;
- }
- }
-
- return $result;
- }
-
- public function supportsAttribute($attribute)
- {
- return $attribute instanceof Expression;
- }
-
- public function supportsClass($class)
- {
- return true;
- }
-
- protected function getCompiler()
- {
- if (null === $this->compiler) {
- throw new RuntimeException('A compiler must be set.');
- }
-
- return $this->compiler;
- }
-
- private function createEvaluator(Expression $expr)
- {
- if ($this->cacheDir) {
- if (is_file($file = $this->cacheDir.'/'.sha1($expr->expression).'.php')) {
- return require $file;
- }
-
- $source = $this->getCompiler()->compileExpression($expr);
- file_put_contents($file, "<?php\n".$source);
-
- return require $file;
- }
-
- return eval($this->getCompiler()->compileExpression($expr));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Expression;
-
-use Symfony\Component\DependencyInjection\ContainerInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionVoter;
-
-class LazyLoadingExpressionVoter extends ExpressionVoter
-{
- private $container;
- private $compilerId;
-
- public function setLazyCompiler(ContainerInterface $container, $id)
- {
- $this->container = $container;
- $this->compilerId = $id;
- }
-
- protected function getCompiler()
- {
- return $this->container->get($this->compilerId);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Interception;
-
-use JMS\SecurityExtraBundle\Exception\RuntimeException;
-use CG\Core\ClassUtils;
-
-use CG\Proxy\MethodInterceptorInterface;
-use CG\Proxy\MethodInvocation;
-use JMS\SecurityExtraBundle\Metadata\MethodMetadata;
-use JMS\SecurityExtraBundle\Security\Authentication\Token\RunAsUserToken;
-use JMS\SecurityExtraBundle\Security\Authorization\AfterInvocation\AfterInvocationManagerInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\RunAsManagerInterface;
-use Metadata\MetadataFactoryInterface;
-use Symfony\Component\HttpKernel\Log\LoggerInterface;
-use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
-use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
-use Symfony\Component\Security\Core\SecurityContext;
-use Symfony\Component\Security\Core\Exception\AccessDeniedException;
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
-
-/**
- * All invocations of secure methods will go through this class.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class MethodSecurityInterceptor implements MethodInterceptorInterface
-{
- private $alwaysAuthenticate;
- private $securityContext;
- private $metadataFactory;
- private $authenticationManager;
- private $accessDecisionManager;
- private $afterInvocationManager;
- private $runAsManager;
- private $logger;
-
- public function __construct(SecurityContext $securityContext, AuthenticationManagerInterface $authenticationManager, AccessDecisionManagerInterface $accessDecisionManager,
- AfterInvocationManagerInterface $afterInvocationManager, RunAsManagerInterface $runAsManager, MetadataFactoryInterface $metadataFactory, LoggerInterface $logger = null)
- {
- $this->alwaysAuthenticate = false;
- $this->securityContext = $securityContext;
- $this->metadataFactory = $metadataFactory;
- $this->authenticationManager = $authenticationManager;
- $this->accessDecisionManager = $accessDecisionManager;
- $this->afterInvocationManager = $afterInvocationManager;
- $this->runAsManager = $runAsManager;
- $this->logger = $logger;
- }
-
- public function setAlwaysAuthenticate($boolean)
- {
- $this->alwaysAuthenticate = !!$boolean;
- }
-
- public function intercept(MethodInvocation $method)
- {
- $metadata = $this->metadataFactory->getMetadataForClass($method->reflection->class);
-
- // no security metadata, proceed
- if (empty($metadata) || !isset($metadata->methodMetadata[$method->reflection->name])) {
- return $method->proceed();
- }
- $metadata = $metadata->methodMetadata[$method->reflection->name];
-
- if (null === $token = $this->securityContext->getToken()) {
- throw new AuthenticationCredentialsNotFoundException(
- 'The security context was not populated with a Token.'
- );
- }
-
- if ($this->alwaysAuthenticate || !$token->isAuthenticated()) {
- $token = $this->authenticationManager->authenticate($token);
- $this->securityContext->setToken($token);
- }
-
- if (!empty($metadata->roles) && false === $this->accessDecisionManager->decide($token, $metadata->roles, $method)) {
- throw new AccessDeniedException('Token does not have the required roles.');
- }
-
- if (!empty($metadata->paramPermissions)) {
- foreach ($method->arguments as $index => $argument) {
- if (null !== $argument && isset($metadata->paramPermissions[$index]) && false === $this->accessDecisionManager->decide($token, $metadata->paramPermissions[$index], $argument)) {
- throw new AccessDeniedException(sprintf('Token does not have the required permissions for method "%s::%s".', $method->reflection->class, $method->reflection->name));
- }
- }
- }
-
- $runAsToken = null;
- if (!empty($metadata->runAsRoles)) {
- $runAsToken = $this->runAsManager->buildRunAs($token, $method, $metadata->runAsRoles);
-
- if (null !== $this->logger) {
- $this->logger->debug('Populating security context with RunAsToken');
- }
-
- if (null === $runAsToken) {
- throw new RuntimeException('RunAsManager must not return null from buildRunAs().');
- }
-
- $this->securityContext->setToken($runAsToken);
- }
-
- try {
- $returnValue = $method->proceed();
-
- if (null !== $runAsToken) {
- $this->restoreOriginalToken($runAsToken);
- }
-
- if (empty($metadata->returnPermissions)) {
- return $returnValue;
- }
-
- return $this->afterInvocationManager->decide($this->securityContext->getToken(), $method, $metadata->returnPermissions, $returnValue);
- } catch (\Exception $failed) {
- if (null !== $runAsToken) {
- $this->restoreOriginalToken($runAsToken);
- }
-
- throw $failed;
- }
- }
-
- private function restoreOriginalToken(RunAsUserToken $runAsToken)
- {
- if (null !== $this->logger) {
- $this->logger->debug('Populating security context with original Token.');
- }
-
- $this->securityContext->setToken($runAsToken->getOriginalToken());
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Interception;
-
-use CG\Core\ClassUtils;
-use Metadata\MetadataFactoryInterface;
-use JMS\AopBundle\Aop\PointcutInterface;
-
-class SecurityPointcut implements PointcutInterface
-{
- private $metadataFactory;
- private $secureAllServices;
- private $securedClasses = array();
- private $patterns;
-
- public function __construct(MetadataFactoryInterface $metadataFactory, $secureAllServices = false, array $patterns = array())
- {
- $this->metadataFactory = $metadataFactory;
- $this->secureAllServices = $secureAllServices;
- $this->patterns = $patterns;
- }
-
- public function setSecuredClasses(array $classes)
- {
- $this->securedClasses = $classes;
- }
-
- public function matchesClass(\ReflectionClass $class)
- {
- if ($this->secureAllServices) {
- return true;
- }
-
- if ('Controller' === substr(ClassUtils::getUserClass($class->name), -10)) {
- return true;
- }
-
- foreach ($this->patterns as $pattern => $expr) {
- // if not for all patterns the class is specified, then we need to scan all
- // classes to catch all methods
- if (false === $pos = strpos($pattern, '::')) {
- // controller notation is already checked by JMSDiExtraBundle,
- // we can safely ignore these patterns here
- if (2 === substr_count($pattern, ':')) {
- continue;
- }
-
- return true;
- }
-
- if (0 < preg_match('#'.substr($pattern, 0, $pos).'$#', $class->name)) {
- return true;
- }
- }
-
- foreach ($this->securedClasses as $securedClass) {
- if ($class->name === $securedClass || $class->isSubclassOf($securedClass)) {
- return true;
- }
- }
-
- return false;
- }
-
- public function matchesMethod(\ReflectionMethod $method)
- {
- $userClass = ClassUtils::getUserClass($method->class);
- $metadata = $this->metadataFactory->getMetadataForClass($userClass);
-
- if (null === $metadata) {
- return false;
- }
-
- return isset($metadata->methodMetadata[$method->name]);
- }
-}
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization;
-
-use JMS\SecurityExtraBundle\Security\Authentication\Token\RunAsUserToken;
-use Symfony\Component\Security\Core\Role\Role;
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-
-/**
- * The RunAsManager creates throw-away Tokens which are temporarily injected into
- * the security context for the duration of the invocation of a specific method.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class RunAsManager implements RunAsManagerInterface
-{
- private $key;
- private $rolePrefix;
-
- public function __construct($key, $rolePrefix = 'ROLE_')
- {
- $this->key = $key;
- $this->rolePrefix = $rolePrefix;
- }
-
- /**
- * {@inheritDoc}
- */
- public function buildRunAs(TokenInterface $token, $secureObject, array $attributes)
- {
- $roles = array();
- foreach ($attributes as $attribute)
- {
- if ($this->supportsAttribute($attribute)) {
- $roles[] = new Role($attribute);
- }
- }
-
- if (0 === count($roles)) {
- return null;
- }
-
- $roles = array_merge($roles, $token->getRoles());
-
- return new RunAsUserToken($this->key, $token->getUser(), $token->getCredentials(), $roles, $token);
- }
-
- /**
- * {@inheritDoc}
- */
- public function supportsAttribute($attribute)
- {
- return !empty($attribute) && 0 === strpos($attribute, $this->rolePrefix);
- }
-
- /**
- * {@inheritDoc}
- */
- public function supportsClass($className)
- {
- return true;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization;
-
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-
-/**
- * RunAsManagerInterface
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-interface RunAsManagerInterface
-{
- /**
- * Creates a temporary RunAsToken.
- *
- * The returned Token must have a complementing AuthenticationProvider implementation.
- *
- * @param TokenInterface $token the original Token
- * @param object $secureObject the secure object which caused this call
- * @param array $attributes an array of attributes to apply to the built token
- * @return TokenInterface
- */
- function buildRunAs(TokenInterface $token, $secureObject, array $attributes);
-
- /**
- * Whether this RunAsManager supports the given attribute
- *
- * @param string $attribute
- * @return Boolean
- */
- function supportsAttribute($attribute);
-
- /**
- * Whether this RunAsManager supports the given class.
- *
- * @param string $className The class of the secure object which requests RunAs capabilities
- * @return Boolean
- */
- function supportsClass($className);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Security\Authorization\Voter;
-
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
-
-/**
- * This voter adds a special role "ROLE_IDDQD" which effectively bypasses any,
- * and all security checks.
- *
- * Most of the time, you will want to use this rule in combination with a
- * @RunAs annotation to disable security checks for the invocation of a
- * specific method.
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class IddqdVoter implements VoterInterface
-{
- public function vote(TokenInterface $token, $object, array $attributes)
- {
- return $this->isIddqd($token) ? VoterInterface::ACCESS_GRANTED : VoterInterface::ACCESS_ABSTAIN;
- }
-
- protected function isIddqd(TokenInterface $token)
- {
- foreach ($token->getRoles() as $role) {
- if ('ROLE_IDDQD' === $role->getRole()) {
- return true;
- }
- }
-
- return false;
- }
-
- public function supportsAttribute($attribute)
- {
- return true;
- }
-
- public function supportsClass($class)
- {
- return true;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\DependencyInjection\Compiler;
-
-use Symfony\Component\DependencyInjection\Definition;
-use JMS\SecurityExtraBundle\DependencyInjection\Compiler\AddAfterInvocationProvidersPass;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-
-class AddAfterInvocationProvidersPassTest extends \PHPUnit_Framework_TestCase
-{
- public function testProcessStopsWhenNoAfterInvocationManager()
- {
- $container = $this->getContainer();
- $container
- ->expects($this->once())
- ->method('hasDefinition')
- ->with($this->equalTo('security.access.after_invocation_manager'))
- ->will($this->returnValue(false))
- ;
- $container
- ->expects($this->never())
- ->method('findTaggedServiceIds')
- ;
-
- $this->process($container);
- }
-
- public function testProcessRemovesAclProviderIfAclIsNotActive()
- {
- $container = new ContainerBuilder();
- $container->setDefinition('security.access.after_invocation_manager', $manager = new Definition());
-
- $container
- ->register('security.access.after_invocation.acl_provider')
- ->addTag('security.after_invocation.provider')
- ;
-
- $this->assertEquals(array(), $manager->getArguments());
- $this->process($container);
- $this->assertEquals(array(array()), $manager->getArguments());
- }
-
- public function testProcess()
- {
- $container = new ContainerBuilder();
-
- $container->setDefinition('security.access.after_invocation_manager', $manager = new Definition());
-
- $provider1 = new Definition();
- $provider1->addTag('security.after_invocation.provider');
- $container->setDefinition('provider1', $provider1);
-
- $provider2 = new Definition();
- $provider2->addTag('security.after_invocation.provider');
- $container->setDefinition('provider2', $provider2);
-
- $this->process($container);
-
- $arguments = $manager->getArguments();
- $this->assertEquals(2, count($providers = $arguments[0]));
- $this->assertEquals('provider1', (string) $providers[0]);
- $this->assertEquals('provider2', (string) $providers[1]);
- }
-
- protected function process(ContainerBuilder $container)
- {
- $pass = new AddAfterInvocationProvidersPass();
- $pass->process($container);
- }
-
- protected function getContainer()
- {
- return $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\DependencyInjection\Compiler;
-
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-
-use JMS\SecurityExtraBundle\DependencyInjection\Compiler\CollectSecuredServicesPass;
-
-class CollectSecuredServicesPassTest extends \PHPUnit_Framework_TestCase
-{
- public function testProcess()
- {
- $container = new ContainerBuilder();
- $container
- ->register('security.access.pointcut', 'JMS\SecurityExtraBundle\Security\Authorization\Interception\SecurityPointcut')
- ;
-
- $container
- ->register('a', 'stdClass')
- ->addTag('security.secure_service')
- ;
- $container
- ->register('b', 'stdClass')
- ->addTag('security.secure_service')
- ;
-
- $pass = new CollectSecuredServicesPass();
- $pass->process($container);
-
- $this->assertEquals(array(
- array('setSecuredClasses', array(array('stdClass', 'stdClass'))),
- ), $container->getDefinition('security.access.pointcut')->getMethodCalls());
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\DependencyInjection;
-
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use JMS\SecurityExtraBundle\DependencyInjection\JMSSecurityExtraExtension;
-
-class JMSSecurityExtraExtensionTest extends \PHPUnit_Framework_TestCase
-{
- private $extension;
-
- public function testConfigLoad()
- {
- $config = array();
- $this->extension->load(array($config), $container = $this->getContainer());
-
- $this->assertTrue($container->hasDefinition('security.access.method_interceptor'));
- $this->assertFalse($container->getParameter('security.access.secure_all_services'));
- $this->assertFalse($container->getDefinition('security.extra.iddqd_voter')->hasTag('security.voter'));
- }
-
- public function testConfigLoadSecureAll()
- {
- $this->extension->load(array(array('secure_all_services' => true)),
- $container = $this->getContainer());
-
- $this->assertTrue($container->getParameter('security.access.secure_all_services'));
- }
-
- public function testConfigLoadEnableIddqdAttribute()
- {
- $this->extension->load(array(array('enable_iddqd_attribute' => true)),
- $container = $this->getContainer());
-
- $this->assertTrue($container->getDefinition('security.extra.iddqd_voter')->hasTag('security.voter'));
- }
-
- public function testConfigLoadWithMethodAccessControl()
- {
- $this->extension->load(array(array(
- 'expressions' => true,
- 'method_access_control' => array(
- ':login$' => 'hasRole("FOO")',
- )
- )), $container = $this->getContainer());
-
- $this->assertEquals(array(':login$' => 'hasRole("FOO")'),
- $container->getParameter('security.access.method_access_control'));
- }
-
- /**
- * @expectedException \RuntimeException
- */
- public function testConfigLoadThrowsExceptionWhenMethodAccessControlWithoutExpressions()
- {
- $this->extension->load(array(array(
- 'expressions' => false,
- 'method_access_control' => array('foo' => 'bar'),
- )), $this->getContainer());
- }
-
- protected function setUp()
- {
- $this->extension = new JMSSecurityExtraExtension();
- }
-
- private function getContainer()
- {
- $container = new ContainerBuilder();
- $container->setParameter('kernel.cache_dir', sys_get_temp_dir());
- $container->setParameter('kernel.bundles', array('JMSAopBundle' => 'JMS\AopBundle\JMSAopBundle'));
-
- return $container;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Fixtures;
-
-use JMS\SecurityExtraBundle\Annotation\SecureReturn;
-use JMS\SecurityExtraBundle\Annotation\SecureParam;
-use JMS\SecurityExtraBundle\Annotation\Secure;
-
-interface AMNDOIDCS_Interface
-{
- /**
- * @SecureReturn(permissions="VIEW")
- */
- function abstractMethod();
-}
-
-abstract class AMNDOIDCS_DirectChild implements AMNDOIDCS_Interface
-{
-}
-
-class AbstractMethodNotDirectlyOverwrittenInDirectChildService extends AMNDOIDCS_DirectChild
-{
- /**
- * Some comment
- */
- public function abstractMethod()
- {
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Fixtures\Annotation;
-
-/** @Annotation */
-final class NonSecurityAnnotation
-{
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Fixtures;
-
-use JMS\SecurityExtraBundle\Annotation\SecureReturn;
-use JMS\SecurityExtraBundle\Annotation\SecureParam;
-use JMS\SecurityExtraBundle\Annotation\Secure;
-
-interface E {
- /**
- * @SecureReturn(permissions="VIEW,UNDELETE")
- */
- function retrieve();
-}
-interface F {
- /**
- * @SecureParam(name="secure", permissions="OWNER")
- * @SecureParam(name="foo", permissions="MASTER, EDIT")
- */
- function delete($foo, $asdf, $secure);
-}
-interface C { }
-interface D extends F {}
-interface B extends C, E { }
-abstract class G implements F, E {
- /**
- * @Secure(roles="ROLE_FOO, IS_AUTHENTICATED_FULLY")
- * @SecureParam(name="secure", permissions="FOO")
- * @SecureReturn(permissions="WOW")
- */
- abstract function abstractMethod($foo, $secure);
-}
-class A extends G implements C, B, D {
- public function retrieve() { }
- public function delete($one, $two, $three) { }
- public function abstractMethod($asdf, $wohoo) { }
-}
-class ComplexService extends A implements C { }
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Fixtures;
-
-use JMS\SecurityExtraBundle\Annotation\SatisfiesParentSecurityPolicy;
-use JMS\SecurityExtraBundle\Annotation\SecureReturn;
-
-class CorrectSubService extends MainService
-{
- /**
- * @SatisfiesParentSecurityPolicy
- * @SecureReturn(permissions="VIEW")
- */
- public function differentMethodSignature($comment)
- {
- return parent::differentMethodSignature($comment);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Fixtures;
-
-use JMS\SecurityExtraBundle\Annotation\Secure;
-use JMS\SecurityExtraBundle\Tests\Fixtures\Annotation\NonSecurityAnnotation;
-use JMS\SecurityExtraBundle\Annotation\SecureParam;
-
-class MainService
-{
- /**
- * This Method has no relevant security annotations
- * @NonSecurityAnnotation
- */
- public function foo()
- {
- }
-
- /**
- * @SecureParam(name="comment", permissions="EDIT")
- */
- public function differentMethodSignature($comment)
- {
- // some secure action
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Fixtures;
-
-class SubService extends MainService
-{
- public function differentMethodSignature($commentId)
- {
- $comment = 'asdgasdf'.$commentId;
-
- return MainService::differentMethodSignature($comment);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Functional;
-
-// get the autoload file
-$dir = __DIR__;
-$lastDir = null;
-while ($dir !== $lastDir) {
- $lastDir = $dir;
-
- if (is_file($dir.'/autoload.php')) {
- require_once $dir.'/autoload.php';
- break;
- }
-
- if (is_file($dir.'/app/bootstrap.php.cache')) {
- require_once $dir.'/app/bootstrap.php.cache';
- break;
- }
-
- if (is_file($dir.'/autoload.php.dist')) {
- require_once $dir.'/autoload.php.dist';
- break;
- }
-
- $dir = dirname($dir);
-}
-
-use Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\FormLoginBundle\FormLoginBundle;
-
-use JMS\SecurityExtraBundle\Tests\Functional\TestBundle\TestBundle;
-
-use Symfony\Component\HttpKernel\Util\Filesystem;
-use Symfony\Component\Config\Loader\LoaderInterface;
-use Symfony\Component\HttpKernel\Kernel;
-
-class AppKernel extends Kernel
-{
- private $config;
-
- public function __construct($config)
- {
- parent::__construct('test', true);
-
- $fs = new Filesystem();
- if (!$fs->isAbsolutePath($config)) {
- $config = __DIR__.'/config/'.$config;
- }
-
- if (!file_exists($config)) {
- throw new \RuntimeException(sprintf('The config file "%s" does not exist.', $config));
- }
-
- $this->config = $config;
- }
-
- public function registerBundles()
- {
- return array(
- new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
- new \Symfony\Bundle\SecurityBundle\SecurityBundle(),
- new \Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
- new \Symfony\Bundle\TwigBundle\TwigBundle(),
- new TestBundle(),
- new FormLoginBundle(),
- new \Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
- new \JMS\AopBundle\JMSAopBundle(),
- new \JMS\DiExtraBundle\JMSDiExtraBundle($this),
- new \JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
- );
- }
-
- public function registerContainerConfiguration(LoaderInterface $loader)
- {
- $loader->load($this->config);
- }
-
- public function getCacheDir()
- {
- return sys_get_temp_dir().'/JMSSecurityExtraBundle/'.sha1($this->config);
- }
-
- protected function getContainerClass()
- {
- return parent::getContainerClass().sha1($this->config);
- }
-
- public function serialize()
- {
- return $this->config;
- }
-
- public function unserialize($str)
- {
- $this->__construct($str);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Functional;
-
-use Symfony\Component\HttpKernel\Util\Filesystem;
-
-use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
-
-class BaseTestCase extends WebTestCase
-{
- static protected function createKernel(array $options = array())
- {
- return new AppKernel(
- isset($options['config']) ? $options['config'] : 'default.yml'
- );
- }
-
- protected function setUp()
- {
- parent::setUp();
-
- $fs = new Filesystem();
- $fs->remove(sys_get_temp_dir().'/JMSSecurityExtraBundle');
- }
-
- protected function tearDown()
- {
- parent::tearDown();
-
- $fs = new Filesystem();
- $fs->remove(sys_get_temp_dir().'/JMSSecurityExtraBundle');
- }
-
- protected function login($client, $username = null, $password = null)
- {
- if (empty($username) || empty($password)) {
- $username = 'johannes';
- $password = 'test';
- }
-
- $crawler = $client->request('get', '/login')->selectButton('login');
- $form = $crawler->form();
-
- $form['_username'] = $username;
- $form['_password'] = $password;
- $client->submit($form);
-
- $security = $client->getProfile()->getCollector('security');
-
- $this->assertTrue(is_string($security->getUser()) && strlen($security->getUser()) > 0);
- $this->assertTrue($security->isAuthenticated(), 'Logged in user is not authenticated.');
- }
-
- protected final function importDatabaseSchema()
- {
- $em = self::$kernel->getContainer()->get('em');
-
- $metadata = $em->getMetadataFactory()->getAllMetadata();
- if (!empty($metadata)) {
- $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($em);
- $schemaTool->createSchema($metadata);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Functional;
-
-class MethodAccessControlTest extends BaseTestCase
-{
- public function testControllerAddActionIsSecure()
- {
- $client = $this->createClient(array('config' => 'method_access_control.yml'));
-
- $client->request('GET', '/add');
- $response = $client->getResponse();
-
- $this->assertEquals(302, $response->getStatusCode());
- $this->assertEquals('http://localhost/login', $response->headers->get('Location'));
- }
-
- public function testControllerEditActionIsNotSecure()
- {
- $client = $this->createClient(array('config' => 'method_access_control.yml'));
-
- $client->request('GET', '/edit');
- $response = $client->getResponse();
-
- $this->assertEquals(200, $response->getStatusCode());
- }
-
- /**
- * @expectedException Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
- */
- public function testUserManagerDeleteIsSecure()
- {
- $this->createClient(array('config' => 'method_access_control.yml'));
-
- $manager = self::$kernel->getContainer()->get('user_manager');
-
- $this->assertNotEquals(
- 'JMS\SecurityExtraBundle\Tests\Functional\TestBundle\User\UserManager',
- get_class($manager)
- );
- $manager->delete();
- }
-
- public function testAcl()
- {
- $client = $this->createClient(array('config' => 'acl_enabled.yml'));
- $client->insulate();
-
- $this->importDatabaseSchema();
- $this->login($client);
-
- $client->request('POST', '/post/add', array('title' => 'Foo'));
-
- $response = $client->getResponse();
- $this->assertEquals('/post/edit/1', $response->headers->get('Location'),
- substr($response, 0, 2000));
-
- $client->request('GET', '/post/edit/1');
- $response = $client->getResponse();
- $this->assertEquals(200, $response->getStatusCode(), substr($response, 0, 2000));
- $this->assertEquals('Foo', $response->getContent());
- }
-
- public function testRoleHierarchyIsRespected()
- {
- $client = $this->createClient(array('config' => 'all_voters_disabled.yml'));
- $client->insulate();
-
- $this->login($client);
-
- $client->request('GET', '/post/list');
-
- $response = $client->getResponse();
- $this->assertEquals(200, $response->getStatusCode(), substr($response, 0, 2000));
- $this->assertEquals('list', $response->getContent(), substr($response, 0, 2000));
- }
-}
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE html>
-<html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>{% block title %}Welcome!{% endblock %}</title>
- {% block stylesheets %}{% endblock %}
- <link rel="shortcut icon" href="{{ asset('favicon.ico') }}" />
- </head>
- <body>
- {% block body %}{% endblock %}
- {% block javascripts %}{% endblock %}
- </body>
-</html>
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Functional\TestBundle\Controller;
-
-use Symfony\Component\HttpFoundation\Response;
-
-class CrudController
-{
- public function addAction()
- {
- return new Response();
- }
-
- public function editAction()
- {
- return new Response();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Functional\TestBundle\Controller;
-
-use Symfony\Component\Security\Acl\Permission\MaskBuilder;
-
-use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
-
-use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
-
-use Symfony\Component\HttpFoundation\Response;
-use Symfony\Component\HttpKernel\Exception\HttpException;
-use JMS\SecurityExtraBundle\Tests\Functional\TestBundle\Entity\Post;
-use JMS\SecurityExtraBundle\Annotation\PreAuthorize;
-use JMS\DiExtraBundle\Annotation as DI;
-
-class PostController
-{
- /** @DI\Inject */
- private $request;
-
- /** @DI\Inject */
- private $em;
-
- /** @DI\Inject("security.context") */
- private $context;
-
- /** @DI\Inject */
- private $router;
-
- /**
- * @PreAuthorize("isAuthenticated()")
- */
- public function newPostAction()
- {
- if (!$title = $this->request->request->get('title')) {
- throw new HttpException(400);
- }
-
- $this->em->getConnection()->beginTransaction();
- try {
- $post = new Post($title);
- $this->em->persist($post);
- $this->em->flush();
-
- $oid = ObjectIdentity::fromDomainObject($post);
- $acl = $this->getAclProvider()->createAcl($oid);
-
- $sid = UserSecurityIdentity::fromToken($this->context->getToken());
- $acl->insertObjectAce($sid, MaskBuilder::MASK_OWNER);
- $this->getAclProvider()->updateAcl($acl);
-
- $this->em->getConnection()->commit();
-
- return new Response('', 201, array(
- 'Location' => $this->router->generate('post_controller_edit', array('id' => $post->getId())),
- ));
- } catch (\Exception $ex) {
- $this->em->getConnection()->rollBack();
- $this->em->close();
-
- throw $ex;
- }
- }
-
- /**
- * @PreAuthorize("hasPermission(#post, 'edit')")
- */
- public function editPostAction(Post $post)
- {
- return new Response($post->getTitle());
- }
-
- /**
- * @PreAuthorize("hasRole('ROLE_BAR')")
- */
- public function listPostAction()
- {
- return new Response('list');
- }
-
- /** @DI\LookupMethod("security.acl.provider") */
- protected function getAclProvider() { }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Functional\TestBundle\Entity;
-
-use Doctrine\ORM\Mapping as ORM;
-
-/**
- * @ORM\Entity
- * @ORM\Table(name = "posts")
- *
- * @author Johannes M. Schmitt <schmittjoh@gmail.com>
- */
-class Post
-{
- /**
- * @ORM\Id
- * @ORM\GeneratedValue(strategy="AUTO")
- * @ORM\Column(type="integer")
- */
- private $id;
-
- /**
- * @ORM\Column(type = "string")
- */
- private $title;
-
- public function __construct($title)
- {
- $this->title = $title;
- }
-
- public function getId()
- {
- return $this->id;
- }
-
- public function getTitle()
- {
- return $this->title;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Functional\TestBundle\Logger;
-
-use Symfony\Component\HttpKernel\Log\LoggerInterface;
-
-class FileLogger implements LoggerInterface
-{
- private $dir;
-
- public function __construct($logDir)
- {
- $this->dir = $logDir;
- }
-
- public function emerg($message, array $context = array())
- {
- $this->log('[EMERG] '.$message);
- }
-
- public function alert($message, array $context = array())
- {
- $this->log('[ALERT] '.$message);
- }
-
- public function crit($message, array $context = array())
- {
- $this->log('[CRIT] '.$message);
- }
-
- public function err($message, array $context = array())
- {
- $this->log('[ERR] '.$message);
- }
-
- public function warn($message, array $context = array())
- {
- $this->log('[WARN] '.$message);
- }
-
- public function notice($message, array $context = array())
- {
- $this->log('[NOTICE] '.$message);
- }
-
- public function info($message, array $context = array())
- {
- $this->log('[INFO] '.$message);
- }
-
- public function debug($message, array $context = array())
- {
- $this->log('[DEBUG] '.$message);
- }
-
- private function log($message)
- {
- file_put_contents($this->dir.'/log', $message."\n", FILE_APPEND);
- }
-}
\ No newline at end of file
+++ /dev/null
-{% if (is_expr_granted("hasRole('FOO')")) -%}
-granted
-{%- else -%}
-denied
-{%- endif %}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Functional\TestBundle;
-
-use Symfony\Component\HttpKernel\Bundle\Bundle;
-
-class TestBundle extends Bundle
-{
-
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Functional\TestBundle\User;
-
-class UserManager
-{
- public function delete()
- {
- throw new \Exception('Should not be called.');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Functional;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Expression;
-
-use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
-use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
-
-class TwigIntegrationTest extends BaseTestCase
-{
- private $context;
- private $twig;
-
- public function testIsExprGrantedWithSufficientPermissions()
- {
- $this->context->setToken(new UsernamePasswordToken('foo', 'bar', 'baz', array('FOO')));
-
- $this->assertEquals('granted',
- $this->twig->render('TestBundle::is_expr_granted.html.twig'));
- }
-
- public function testIsExprGranted()
- {
- $this->context->setToken(new AnonymousToken('foo', 'bar'));
-
- $this->assertEquals('denied',
- $this->twig->render('TestBundle::is_expr_granted.html.twig'));
- }
-
- protected function setUp()
- {
- parent::setUp();
-
- $this->createClient(array('config' => 'all_voters_disabled.yml'));
- $this->context = self::$kernel->getContainer()->get('security.context');
- $this->twig = self::$kernel->getContainer()->get('twig');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Functional;
-
-class VoterDisablingTest extends BaseTestCase
-{
- public function testDisableAllVoters()
- {
- $client = $this->createClient(array('config' => 'all_voters_disabled.yml'));
- $client->insulate();
-
- $adm = self::$kernel->getContainer()->get('security.access.decision_manager');
-
- $this->assertEquals(1, count($voters = $this->getField($adm, 'voters')));
- $this->assertInstanceOf('JMS\SecurityExtraBundle\Security\Authorization\Expression\LazyLoadingExpressionVoter', $voters[0]);
- }
-
- public function testDefault()
- {
- $client = $this->createClient(array('config' => 'default.yml'));
- $client->insulate();
-
- $adm = self::$kernel->getContainer()->get('security.access.decision_manager');
-
- $this->assertEquals(2, count($voters = $this->getField($adm, 'voters')));
- $this->assertInstanceOf('Symfony\Component\Security\Core\Authorization\Voter\RoleVoter', $voters[0]);
- $this->assertInstanceOf('Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter', $voters[1]);
- }
-
- public function testSomeVotersDisabled()
- {
- $client = $this->createClient(array('config' => 'some_voters_disabled.yml'));
- $client->insulate();
-
- $adm = self::$kernel->getContainer()->get('security.access.decision_manager');
-
- $this->assertEquals(1, count($voters = $this->getField($adm, 'voters')));
- $this->assertInstanceOf('Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter', $voters[0]);
- }
-
- private function getField($obj, $field)
- {
- $ref = new \ReflectionProperty($obj, $field);
- $ref->setAccessible(true);
-
- return $ref->getValue($obj);
- }
-}
\ No newline at end of file
+++ /dev/null
-imports:
- - { resource: default.yml }
-
-security:
- acl: ~
-
-jms_security_extra:
- expressions: true
- voters: false
\ No newline at end of file
+++ /dev/null
-imports:
- - { resource: default.yml }
-
-jms_security_extra:
- expressions: true
- voters: false
\ No newline at end of file
+++ /dev/null
-imports:
- - { resource: framework.yml }
- - { resource: twig.yml }
- - { resource: security.yml }
- - { resource: doctrine.yml }
+++ /dev/null
-services:
- em: @doctrine.orm.entity_manager
-
-doctrine:
- dbal:
- driver: pdo_sqlite
- path: %kernel.cache_dir%/sqlite.db
-
- orm:
- auto_generate_proxy_classes: %kernel.debug%
- entity_managers:
- default:
- auto_mapping: true
+++ /dev/null
-services:
- logger:
- class: JMS\SecurityExtraBundle\Tests\Functional\TestBundle\Logger\FileLogger
- arguments: [%kernel.cache_dir%]
-
-framework:
- secret: test
- profiler: ~
- test: ~
- session:
- storage_id: session.storage.filesystem
- form: true
- csrf_protection: true
- validation:
- enabled: true
- enable_annotations: true
- router:
- resource: %kernel.root_dir%/config/routing.yml
\ No newline at end of file
+++ /dev/null
-imports:
- - { resource: default.yml }
-
-services:
- user_manager:
- class: JMS\SecurityExtraBundle\Tests\Functional\TestBundle\User\UserManager
-
-jms_security_extra:
- expressions: ~
- method_access_control:
- 'UserManager::delete$': 'hasRole("FOO")'
- 'TestBundle:Crud:add': 'hasRole("FOO")'
\ No newline at end of file
+++ /dev/null
-crud_controller_add:
- pattern: /add
- defaults:
- _controller: TestBundle:Crud:add
-
-crud_controller_edit:
- pattern: /edit
- defaults:
- _controller: TestBundle:Crud:edit
-
-post_controller_add:
- pattern: /post/add
- defaults:
- _controller: TestBundle:Post:newPost
-
-post_controller_edit:
- pattern: /post/edit/{id}
- defaults:
- _controller: TestBundle:Post:editPost
-
-post_controller_list:
- pattern: /post/list
- defaults:
- _controller: TestBundle:Post:listPost
-
-form_login_bundle:
- resource: @FormLoginBundle/Resources/config/routing.yml
\ No newline at end of file
+++ /dev/null
-security:
- providers:
- in_memory:
- users:
- johannes: { password: test, roles: [ROLE_FOO] }
-
- role_hierarchy:
- ROLE_FOO: [ROLE_BAR]
-
- encoders:
- Symfony\Component\Security\Core\User\UserInterface: plaintext
-
- firewalls:
- default:
- form_login: ~
- anonymous: ~
- logout: ~
+++ /dev/null
-imports:
- - { resource: default.yml }
-
-security:
- acl: ~
-
-jms_security_extra:
- voters:
- disable_role: true
- disable_acl: true
+++ /dev/null
-framework:
- templating:
- engines: [twig, php]
-
-twig:
- debug: %kernel.debug%
- strict_variables: %kernel.debug%
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Metadata;
-
-use Doctrine\Common\Annotations\AnnotationReader;
-
-use JMS\SecurityExtraBundle\Metadata\Driver\AnnotationDriver;
-
-use Metadata\MetadataFactory;
-
-class ClassMetadataTest extends \PHPUnit_Framework_TestCase
-{
- /**
- * @expectedException \RuntimeException
- * @expectedMessage You have overridden a secured method "differentMethodSignature" in "SubService". Please copy over the applicable security metadata, and also add @SatisfiesParentSecurityPolicy.
- */
- public function testAnalyzeThrowsExceptionWhenSecureMethodIsOverridden()
- {
- $this->getFactory()->getMetadataForClass('JMS\SecurityExtraBundle\Tests\Fixtures\SubService');
- }
-
- public function testAnalyzeThrowsNoExceptionWhenAbstractMethodIsNotOverridenInDirectChildClass()
- {
- $metadata = $this
- ->getFactory()
- ->getMetadataForClass('JMS\SecurityExtraBundle\Tests\Fixtures\AbstractMethodNotDirectlyOverwrittenInDirectChildService')
- ;
-
- $this->assertTrue(isset($metadata->methodMetadata['abstractMethod']));
-
- $metadata = $metadata->methodMetadata['abstractMethod'];
- $this->assertEquals(array('VIEW'), $metadata->returnPermissions);
- }
-
- public function testAnalyzeThrowsNoExceptionWhenSatisfiesParentSecurityPolicyIsDefined()
- {
- $metadata = $this
- ->getFactory()
- ->getMetadataForClass('JMS\SecurityExtraBundle\Tests\Fixtures\CorrectSubService')
- ;
-
- $methods = $metadata->methodMetadata;
- $this->assertTrue(isset($methods['differentMethodSignature']));
-
- $metadata = $methods['differentMethodSignature'];
- $this->assertEquals(array(), $metadata->roles);
- $this->assertEquals(array(), $metadata->paramPermissions);
- $this->assertEquals(array('VIEW'), $metadata->returnPermissions);
- }
-
- public function testAnalyzeWithComplexHierarchy()
- {
- $metadata = $this
- ->getFactory()
- ->getMetadataForClass('JMS\SecurityExtraBundle\Tests\Fixtures\ComplexService')
- ;
-
- $methods = $metadata->methodMetadata;
- $this->assertTrue(isset($methods['delete'], $methods['retrieve'], $methods['abstractMethod']));
-
- $metadata = $methods['delete'];
- $this->assertEquals(array(0 => array('MASTER', 'EDIT'), 2 => array('OWNER')), $metadata->paramPermissions);
- $this->assertEquals(array(), $metadata->returnPermissions);
- $this->assertEquals(array(), $metadata->roles);
-
- $metadata = $methods['retrieve'];
- $this->assertEquals(array('VIEW', 'UNDELETE'), $metadata->returnPermissions);
- $this->assertEquals(array(), $metadata->paramPermissions);
- $this->assertEquals(array(), $metadata->roles);
-
- $metadata = $methods['abstractMethod'];
- $this->assertEquals(array('ROLE_FOO', 'IS_AUTHENTICATED_FULLY'), $metadata->roles);
- $this->assertEquals(array(1 => array('FOO')), $metadata->paramPermissions);
- $this->assertEquals(array('WOW'), $metadata->returnPermissions);
- }
-
- public function testAnalyze()
- {
- $metadata = $this
- ->getFactory()
- ->getMetadataForClass('JMS\SecurityExtraBundle\Tests\Fixtures\MainService')
- ;
-
- $methods = $metadata->methodMetadata;
- $this->assertTrue(isset($methods['differentMethodSignature']));
-
- $metadata = $methods['differentMethodSignature'];
- $this->assertEquals(array(array('EDIT')), $metadata->paramPermissions);
- $this->assertEquals(array(), $metadata->returnPermissions);
- $this->assertEquals(array(), $metadata->roles);
- $this->assertFalse($metadata->isDeclaredOnInterface());
- }
-
- private function getFactory()
- {
- $factory = new MetadataFactory(new AnnotationDriver(new AnnotationReader()));
- $factory->setIncludeInterfaces(true);
-
- return $factory;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Mapping\Driver;
-
-use Doctrine\Common\Annotations\AnnotationReader;
-
-use JMS\SecurityExtraBundle\Metadata\Driver\AnnotationDriver;
-
-require_once __DIR__.'/Fixtures/services.php';
-
-class AnnotationDriverTest extends \PHPUnit_Framework_TestCase
-{
- public function testLoadMetadataFromClass()
- {
- $driver = new AnnotationDriver(new AnnotationReader());
-
- $metadata = $driver->loadMetadataForClass(new \ReflectionClass('JMS\SecurityExtraBundle\Tests\Mapping\Driver\FooService'));
- $this->assertTrue(isset($metadata->methodMetadata['foo']));
- $method = $metadata->methodMetadata['foo'];
- $this->assertEquals(array('ROLE_USER', 'ROLE_ADMIN', 'ROLE_SUPERADMIN'), $method->roles);
- $this->assertEquals(array(), $method->returnPermissions);
- $this->assertEquals(array(0 => array('VIEW')), $method->paramPermissions);
-
- $metadata = $driver->loadMetadataForClass(new \ReflectionClass('JMS\SecurityExtraBundle\Tests\Mapping\Driver\FooInterface'));
- $this->assertTrue(isset($metadata->methodMetadata['foo']));
- $method = $metadata->methodMetadata['foo'];
- $this->assertEquals(array(), $method->roles);
- $this->assertEquals(array(0 => array('OWNER'), 1 => array('EDIT')), $method->paramPermissions);
- $this->assertEquals(array('MASTER'), $method->returnPermissions);
- }
-
- public function testLoadMetadataFromClassWithShortNotation()
- {
- $driver = new AnnotationDriver(new AnnotationReader());
-
- $metadata = $driver->loadMetadataForClass(new \ReflectionClass('JMS\SecurityExtraBundle\Tests\Mapping\Driver\FooService'));
- $this->assertTrue(isset($metadata->methodMetadata['shortNotation']));
- $method = $metadata->methodMetadata['shortNotation'];
- $this->assertEquals(array('ROLE_FOO', 'ROLE_BAR'), $method->roles);
- }
-
- public function testLoadMetadataFromClassDoesNotProcessMethodsForWhichNoSecurityMetadataExists()
- {
- $driver = new AnnotationDriver(new AnnotationReader());
-
- $metadata = $driver->loadMetadataForClass(new \ReflectionClass('JMS\SecurityExtraBundle\Tests\Fixtures\MainService'));
- $this->assertTrue(class_exists('JMS\SecurityExtraBundle\Tests\Fixtures\Annotation\NonSecurityAnnotation', false));
- $this->assertFalse(isset($metadata->methodMetadata['foo']));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Metadata\Driver;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Expression;
-use JMS\SecurityExtraBundle\Metadata\MethodMetadata;
-use JMS\SecurityExtraBundle\Metadata\ClassMetadata;
-use JMS\SecurityExtraBundle\Metadata\Driver\ConfigDriver;
-
-class ConfigDriverTest extends \PHPUnit_Framework_TestCase
-{
- public function testLoadMetadata()
- {
- $driver = new ConfigDriver(array(), array(
- 'CrudController::.*Action$' => 'hasRole("FOO")',
- ));
-
- $metadata = $driver->loadMetadataForClass($this->getClass('Controller\\CrudController'));
-
- $this->assertEquals(5, count($metadata->methodMetadata));
-
- $metadata = $metadata->methodMetadata;
- foreach (array('addAction', 'deleteAction', 'editAction', 'showAction', 'newAction') as $action) {
- $this->assertArrayHasKey($action, $metadata);
- $this->assertEquals(array(new Expression('hasRole("FOO")')), $metadata[$action]->roles);
- }
- }
-
- public function testLoadMetadataControllerNotation()
- {
- $driver = new ConfigDriver(array(
- 'AcmeFooBundle' => 'JMS\SecurityExtraBundle\Tests\Metadata\Driver\Fixtures\AcmeFooBundle',
- ), array(
- '^AcmeFooBundle:.*:delete.*$' => 'hasRole("ROLE_ADMIN")',
- ));
-
- $metadata = $driver->loadMetadataForClass($this->getClass('Controller\\CrudController'));
-
- $this->assertEquals(1, count($metadata->methodMetadata));
- $this->assertArrayHasKey('deleteAction', $metadata->methodMetadata);
- $this->assertEquals(array(new Expression('hasRole("ROLE_ADMIN")')), $metadata->methodMetadata['deleteAction']->roles);
- }
-
- public function testLoadMetadataWithoutConfig()
- {
- $driver = new ConfigDriver(array(), array());
- $this->assertNull($driver->loadMetadataForClass($this->getClass('Controller\\CrudController')));
- }
-
- private function getClass($name)
- {
- return new \ReflectionClass('JMS\SecurityExtraBundle\Tests\Metadata\Driver\Fixtures\\'.$name);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Metadata\Driver\Fixtures\Controller;
-
-class CrudController
-{
- public function addAction() { }
- public function deleteAction() { }
- public function editAction() { }
- public function showAction() { }
- public function newAction() { }
-
- protected function dooFoooBarr() {}
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Mapping\Driver;
-
-use JMS\SecurityExtraBundle\Annotation\SecureReturn;
-use JMS\SecurityExtraBundle\Annotation\SecureParam;
-use JMS\SecurityExtraBundle\Annotation\Secure;
-
-class FooService implements FooInterface
-{
- /**
- * @Secure(roles="ROLE_USER, ROLE_ADMIN, ROLE_SUPERADMIN")
- * @SecureParam(name="param", permissions="VIEW")
- */
- public function foo($param, $anotherParam) { }
-
- /**
- * @Secure("ROLE_FOO, ROLE_BAR")
- */
- public function shortNotation() { }
-}
-interface FooInterface
-{
- /**
- * @SecureParam(name="param", permissions="OWNER")
- * @SecureParam(name="anotherParam", permissions="EDIT")
- * @SecureReturn(permissions="MASTER")
- */
- function foo($param, $anotherParam);
-}
\ No newline at end of file
+++ /dev/null
-<?php\r
-\r
-namespace JMS\SecurityExtraBundle\Tests\Security\Acl\Expression;\r
-\r
-use JMS\SecurityExtraBundle\Security\Acl\Expression\HasPermissionFunctionCompiler;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ConstantExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-\r
-class HasPermissionFunctionCompilerTest extends \PHPUnit_Framework_TestCase\r
-{\r
- private $compiler;\r
-\r
- public function testCompile()\r
- {\r
- $source = $this->compiler->compile(new FunctionExpression('hasPermission',\r
- array(new VariableExpression('foo'), new ConstantExpression('VIEW'))));\r
-\r
- $this->assertContains(\r
- "\$context['permission_evaluator']->hasPermission(\$context['token'], \$context['foo'], 'VIEW');",\r
- $source);\r
- }\r
-\r
- public function testCompileUpperCasesPermissions()\r
- {\r
- $source = $this->compiler->compile(new FunctionExpression('hasPermission',\r
- array(new VariableExpression('foo'), new ConstantExpression('view'))));\r
-\r
- $this->assertContains(\r
- "\$context['permission_evaluator']->hasPermission(\$context['token'], \$context['foo'], 'VIEW');",\r
- $source);\r
- }\r
-\r
- protected function setUp()\r
- {\r
- $this->compiler = new ExpressionCompiler();\r
- $this->compiler->addFunctionCompiler(new HasPermissionFunctionCompiler());\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-<?php\r
-\r
-namespace JMS\SecurityExtraBundle\Tests\Security\Acl\Expression;\r
-\r
-use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
-\r
-use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
-\r
-use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
-use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
-use JMS\SecurityExtraBundle\Security\Acl\Expression\PermissionEvaluator;
-\r
-class PermissionEvaluatorTest extends \PHPUnit_Framework_TestCase\r
-{\r
- private $token;\r
- private $object;\r
- private $oid;\r
- private $sid;\r
- private $acl;\r
- private $evaluator;\r
- private $provider;\r
- private $oidStrategy;\r
- private $sidStrategy;\r
- private $permissionMap;\r
- \r
- public function testHasPermission()\r
- {\r
- $this->permissionMap->expects($this->once())\r
- ->method('getMasks')\r
- ->with('VIEW', $this->oid)\r
- ->will($this->returnValue(array(1, 2, 3, 4)));\r
- $this->sidStrategy->expects($this->once())\r
- ->method('getSecurityIdentities')\r
- ->with($this->token)\r
- ->will($this->returnValue(array($this->sid)));\r
- \r
- $this->provider->expects($this->once())\r
- ->method('findAcl')\r
- ->with($this->oid)\r
- ->will($this->returnValue($this->acl));\r
- \r
- $this->acl->expects($this->once())\r
- ->method('isGranted')\r
- ->with(array(1, 2, 3, 4), array($this->sid), false)\r
- ->will($this->returnValue(true));\r
- \r
- $this->assertTrue($this->evaluator->hasPermission($this->token, $this->oid, 'VIEW'));\r
- }\r
- \r
- public function testHasPermissionReturnsFalseWhenNoMasksExist()\r
- {\r
- $this->permissionMap->expects($this->once())\r
- ->method('getMasks')\r
- ->with('FOO', $this->object)\r
- ->will($this->returnValue(null));\r
- \r
- $this->assertFalse($this->evaluator->hasPermission($this->token, $this->object, 'FOO'));\r
- }\r
- \r
- public function testHasPermissionWhenNoObjectIsGiven()\r
- {\r
- $this->permissionMap->expects($this->once())\r
- ->method('getMasks')\r
- ->with('FOO', null)\r
- ->will($this->returnValue(array(1)));\r
- \r
- $this->assertTrue($this->evaluator->hasPermission($this->token, null, 'FOO'));\r
- }\r
- \r
- public function testHasPermissionWhenNoObjectIdentityIsAvailable()\r
- {\r
- $this->permissionMap->expects($this->once())\r
- ->method('getMasks')\r
- ->with('FOO', $this->object)\r
- ->will($this->returnValue(array(1)));\r
- \r
- $this->oidStrategy->expects($this->once())\r
- ->method('getObjectIdentity')\r
- ->with($this->object)\r
- ->will($this->returnValue(null));\r
- \r
- $this->assertTrue($this->evaluator->hasPermission($this->token, $this->object, 'FOO'));\r
- }\r
- \r
- public function testHasPermissionWhenAclIsNotFound()\r
- {\r
- $this->permissionMap->expects($this->once())\r
- ->method('getMasks')\r
- ->with('FOO', $this->oid)\r
- ->will($this->returnValue(array(1)));\r
- \r
- $this->sidStrategy->expects($this->once())\r
- ->method('getSecurityIdentities')\r
- ->with($this->token)\r
- ->will($this->returnValue(array($this->sid)));\r
- \r
- $this->provider->expects($this->once())\r
- ->method('findAcl')\r
- ->with($this->oid)\r
- ->will($this->throwException(new AclNotFoundException()));\r
- \r
- $this->assertFalse($this->evaluator->hasPermission($this->token, $this->oid, 'FOO'));\r
- }\r
- \r
- public function testHasPermissionWhenAceIsNotFound()\r
- {\r
- $this->permissionMap->expects($this->once())\r
- ->method('getMasks')\r
- ->with('FOO', $this->oid)\r
- ->will($this->returnValue(array(1)));\r
- \r
- $this->sidStrategy->expects($this->once())\r
- ->method('getSecurityIdentities')\r
- ->with($this->token)\r
- ->will($this->returnValue(array($this->sid)));\r
- \r
- $this->provider->expects($this->once())\r
- ->method('findAcl')\r
- ->with($this->oid)\r
- ->will($this->returnValue($this->acl));\r
- \r
- $this->acl->expects($this->once())\r
- ->method('isGranted')\r
- ->with(array(1), array($this->sid))\r
- ->will($this->throwException(new NoAceFoundException()));\r
- \r
- $this->assertFalse($this->evaluator->hasPermission($this->token, $this->oid, 'FOO'));\r
- }\r
- \r
- protected function setUp()\r
- {\r
- $this->token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');\r
- $this->oid = $this->getMock('Symfony\Component\Security\Acl\Model\ObjectIdentityInterface');\r
- $this->sid = $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface');\r
- $this->acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface');\r
- $this->object = new \stdClass;\r
- $this->provider = $this->getMock('Symfony\Component\Security\Acl\Model\AclProviderInterface');\r
- $this->oidStrategy = $this->getMock('Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface');\r
- $this->sidStrategy = $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface');\r
- $this->permissionMap = $this->getMock('Symfony\Component\Security\Acl\Permission\PermissionMapInterface');\r
- $this->evaluator = new PermissionEvaluator($this->provider, $this->oidStrategy, $this->sidStrategy, $this->permissionMap);\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Acl\Voter;
-
-use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
-use Symfony\Component\Security\Acl\Voter\FieldVote;
-use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
-use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
-use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
-use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
-use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
-use JMS\SecurityExtraBundle\Security\Acl\Voter\AclVoter;
-
-class AclVoterTest extends \PHPUnit_Framework_TestCase
-{
- /**
- * @dataProvider getSupportsAttributeTests
- */
- public function testSupportsAttribute($attribute, $supported)
- {
- list($voter,, $permissionMap,,) = $this->getVoter();
-
- $permissionMap
- ->expects($this->once())
- ->method('contains')
- ->with($this->identicalTo($attribute))
- ->will($this->returnValue($supported))
- ;
-
- $this->assertSame($supported, $voter->supportsAttribute($attribute));
- }
-
- public function getSupportsAttributeTests()
- {
- return array(
- array('foo', true),
- array('foo', false),
- );
- }
-
- /**
- * @dataProvider getSupportsClassTests
- */
- public function testSupportsClass($class)
- {
- list($voter,,,,) = $this->getVoter();
-
- $this->assertTrue($voter->supportsClass($class));
- }
-
- public function getSupportsClassTests()
- {
- return array(
- array('foo'),
- array('bar'),
- array('moo'),
- );
- }
-
- public function testVote()
- {
- list($voter,, $permissionMap,,) = $this->getVoter();
- $permissionMap
- ->expects($this->atLeastOnce())
- ->method('getMasks')
- ->will($this->returnValue(null))
- ;
-
- $this->assertSame(VoterInterface::ACCESS_ABSTAIN, $voter->vote($this->getToken(), null, array('VIEW', 'EDIT', 'DELETE')));
- }
-
- /**
- * @dataProvider getTrueFalseTests
- */
- public function testVoteWhenNoObjectIsPassed($allowIfObjectIdentityUnavailable)
- {
- list($voter,, $permissionMap,,) = $this->getVoter($allowIfObjectIdentityUnavailable);
- $permissionMap
- ->expects($this->once())
- ->method('getMasks')
- ->will($this->returnValue(array()))
- ;
-
- if ($allowIfObjectIdentityUnavailable) {
- $vote = VoterInterface::ACCESS_GRANTED;
- } else {
- $vote = VoterInterface::ACCESS_ABSTAIN;
- }
-
- $this->assertSame($vote, $voter->vote($this->getToken(), null, array('VIEW')));
- }
-
- /**
- * @dataProvider getTrueFalseTests
- */
- public function testVoteWhenOidStrategyReturnsNull($allowIfUnavailable)
- {
- list($voter,, $permissionMap, $oidStrategy,) = $this->getVoter($allowIfUnavailable);
- $permissionMap
- ->expects($this->once())
- ->method('getMasks')
- ->will($this->returnValue(array()))
- ;
-
- $oidStrategy
- ->expects($this->once())
- ->method('getObjectIdentity')
- ->will($this->returnValue(null))
- ;
-
- if ($allowIfUnavailable) {
- $vote = VoterInterface::ACCESS_GRANTED;
- } else {
- $vote = VoterInterface::ACCESS_ABSTAIN;
- }
-
- $this->assertSame($vote, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
- }
-
- public function getTrueFalseTests()
- {
- return array(array(true), array(false));
- }
-
- public function testVoteNoAclFound()
- {
- list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
-
- $permissionMap
- ->expects($this->once())
- ->method('getMasks')
- ->will($this->returnValue(array()))
- ;
-
- $oidStrategy
- ->expects($this->once())
- ->method('getObjectIdentity')
- ->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
- ;
-
- $sidStrategy
- ->expects($this->once())
- ->method('getSecurityIdentities')
- ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
- ;
-
- $provider
- ->expects($this->once())
- ->method('findAcl')
- ->with($this->equalTo($oid), $this->equalTo($sids))
- ->will($this->throwException(new AclNotFoundException('Not found.')))
- ;
-
- $this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
- }
-
- /**
- * @dataProvider getTrueFalseTests
- */
- public function testVoteGrantsAccess($grant)
- {
- list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
-
- $permissionMap
- ->expects($this->once())
- ->method('getMasks')
- ->with($this->equalTo('VIEW'))
- ->will($this->returnValue($masks = array(1, 2, 3)))
- ;
-
- $oidStrategy
- ->expects($this->once())
- ->method('getObjectIdentity')
- ->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
- ;
-
- $sidStrategy
- ->expects($this->once())
- ->method('getSecurityIdentities')
- ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
- ;
-
- $provider
- ->expects($this->once())
- ->method('findAcl')
- ->with($this->equalTo($oid), $this->equalTo($sids))
- ->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
- ;
-
- $acl
- ->expects($this->once())
- ->method('isGranted')
- ->with($this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
- ->will($this->returnValue($grant))
- ;
-
- if ($grant) {
- $vote = VoterInterface::ACCESS_GRANTED;
- } else {
- $vote = VoterInterface::ACCESS_DENIED;
- }
-
- $this->assertSame($vote, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
- }
-
- public function testVoteNoAceFound()
- {
- list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
-
- $permissionMap
- ->expects($this->once())
- ->method('getMasks')
- ->with($this->equalTo('VIEW'))
- ->will($this->returnValue($masks = array(1, 2, 3)))
- ;
-
- $oidStrategy
- ->expects($this->once())
- ->method('getObjectIdentity')
- ->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
- ;
-
- $sidStrategy
- ->expects($this->once())
- ->method('getSecurityIdentities')
- ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
- ;
-
- $provider
- ->expects($this->once())
- ->method('findAcl')
- ->with($this->equalTo($oid), $this->equalTo($sids))
- ->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
- ;
-
- $acl
- ->expects($this->once())
- ->method('isGranted')
- ->with($this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
- ->will($this->throwException(new NoAceFoundException('No ACE')))
- ;
-
- $this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
- }
-
- /**
- * @dataProvider getTrueFalseTests
- */
- public function testVoteGrantsFieldAccess($grant)
- {
- list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
-
- $permissionMap
- ->expects($this->once())
- ->method('getMasks')
- ->with($this->equalTo('VIEW'))
- ->will($this->returnValue($masks = array(1, 2, 3)))
- ;
-
- $oidStrategy
- ->expects($this->once())
- ->method('getObjectIdentity')
- ->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
- ;
-
- $sidStrategy
- ->expects($this->once())
- ->method('getSecurityIdentities')
- ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
- ;
-
- $provider
- ->expects($this->once())
- ->method('findAcl')
- ->with($this->equalTo($oid), $this->equalTo($sids))
- ->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
- ;
-
- $acl
- ->expects($this->once())
- ->method('isFieldGranted')
- ->with($this->identicalTo('foo'), $this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
- ->will($this->returnValue($grant))
- ;
-
- if ($grant) {
- $vote = VoterInterface::ACCESS_GRANTED;
- } else {
- $vote = VoterInterface::ACCESS_DENIED;
- }
-
- $this->assertSame($vote, $voter->vote($this->getToken(), new FieldVote(new \stdClass(), 'foo'), array('VIEW')));
- }
-
- public function testVoteNoFieldAceFound()
- {
- list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
-
- $permissionMap
- ->expects($this->once())
- ->method('getMasks')
- ->with($this->equalTo('VIEW'))
- ->will($this->returnValue($masks = array(1, 2, 3)))
- ;
-
- $oidStrategy
- ->expects($this->once())
- ->method('getObjectIdentity')
- ->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
- ;
-
- $sidStrategy
- ->expects($this->once())
- ->method('getSecurityIdentities')
- ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
- ;
-
- $provider
- ->expects($this->once())
- ->method('findAcl')
- ->with($this->equalTo($oid), $this->equalTo($sids))
- ->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
- ;
-
- $acl
- ->expects($this->once())
- ->method('isFieldGranted')
- ->with($this->identicalTo('foo'), $this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
- ->will($this->throwException(new NoAceFoundException('No ACE')))
- ;
-
- $this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new FieldVote(new \stdClass(), 'foo'), array('VIEW')));
- }
-
- public function testWhenReceivingAnObjectIdentityInterfaceWeDontRetrieveANewObjectIdentity()
- {
- list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
-
- $oid = new ObjectIdentity('someID','someType');
-
- $permissionMap
- ->expects($this->once())
- ->method('getMasks')
- ->with($this->equalTo('VIEW'))
- ->will($this->returnValue($masks = array(1, 2, 3)))
- ;
-
- $oidStrategy
- ->expects($this->never())
- ->method('getObjectIdentity')
- ;
-
- $sidStrategy
- ->expects($this->once())
- ->method('getSecurityIdentities')
- ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
- ;
-
- $provider
- ->expects($this->once())
- ->method('findAcl')
- ->with($this->equalTo($oid), $this->equalTo($sids))
- ->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
- ;
-
- $acl
- ->expects($this->once())
- ->method('isGranted')
- ->with($this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
- ->will($this->throwException(new NoAceFoundException('No ACE')))
- ;
-
- $voter->vote($this->getToken(), $oid, array('VIEW'));
- }
-
- protected function getToken()
- {
- return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
- }
-
- protected function getVoter($allowIfObjectIdentityUnavailable = true)
- {
- $provider = $this->getMock('Symfony\Component\Security\Acl\Model\AclProviderInterface');
- $permissionMap = $this->getMock('Symfony\Component\Security\Acl\Permission\PermissionMapInterface');
- $oidStrategy = $this->getMock('Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface');
- $sidStrategy = $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface');
-
- return array(
- new AclVoter($provider, $oidStrategy, $sidStrategy, $permissionMap, null, $allowIfObjectIdentityUnavailable),
- $provider,
- $permissionMap,
- $oidStrategy,
- $sidStrategy,
- );
- }
-}
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authentication\Provider;
-
-use JMS\SecurityExtraBundle\Security\Authentication\Token\RunAsUserToken;
-
-use JMS\SecurityExtraBundle\Security\Authentication\Provider\RunAsAuthenticationProvider;
-
-class RunAsAuthenticationProviderTest extends \PHPUnit_Framework_TestCase
-{
- public function testAuthenticateReturnsNullIfTokenISUnsupported()
- {
- $provider = new RunAsAuthenticationProvider('foo');
- $token = $this->GetMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
-
- $this->assertNull($provider->authenticate($token));
- }
-
- /**
- * @expectedException Symfony\Component\Security\Core\Exception\BadCredentialsException
- */
- public function testAuthenticateThrowsExceptionWhenKeysDontMatch()
- {
- $provider = new RunAsAuthenticationProvider('foo');
- $token = $this->getSupportedToken();
- $token
- ->expects($this->once())
- ->method('getKey')
- ->will($this->returnValue('moo'))
- ;
-
- $provider->authenticate($token);
- }
-
- public function testAuthenticate()
- {
- $provider = new RunAsAuthenticationProvider('foo');
- $token = $this->getSupportedToken();
- $token
- ->expects($this->once())
- ->method('getKey')
- ->will($this->returnValue('foo'))
- ;
-
- $this->assertSame($token, $provider->authenticate($token));
- }
-
- public function testSupportsDoesNotAcceptInvalidToken()
- {
- $provider = new RunAsAuthenticationProvider('foo');
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
-
- $this->assertFalse($provider->supports($token));
- }
-
- public function testSupports()
- {
- $provider = new RunAsAuthenticationProvider('foo');
-
- $token = $this->getSupportedToken();
- $this->assertTrue($provider->supports($token));
- }
-
- protected function getSupportedToken()
- {
- return $this->getMockBuilder('JMS\SecurityExtraBundle\Security\Authentication\Token\RunAsUserToken')
- ->disableOriginalConstructor()
- ->getMock();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authentication\Token;
-
-use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
-
-use Symfony\Component\Security\Core\Role\Role;
-use JMS\SecurityExtraBundle\Security\Authentication\Token\RunAsUserToken;
-
-class RunAsUserTokenTest extends \PHPUnit_Framework_TestCase
-{
- public function testConstructor()
- {
- $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
-
- $runAsToken = new RunAsUserToken('foo', $user, 'secret', array('ROLE_FOO'), $token);
- $this->assertSame($user, $runAsToken->getUser());
- $this->assertSame('secret', $runAsToken->getCredentials());
- $this->assertSame($token, $runAsToken->getOriginalToken());
- $this->assertEquals(array(new Role('ROLE_FOO')), $runAsToken->getRoles());
- $this->assertSame('foo', $runAsToken->getKey());
- }
-
- public function testEraseCredentials()
- {
- $token = new RunAsUserToken('foo', 'foo', 'secret', array(), $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
- $this->assertEquals('secret', $token->getCredentials());
- $token->eraseCredentials();
- $this->assertNull($token->getCredentials());
- }
-
- public function testSerializeUnserialize()
- {
- $token = new RunAsUserToken('foo', 'bar', 'secret', array(), new UsernamePasswordToken('foo', 'pass', 'foo', array()));
- $this->assertEquals($token, unserialize(serialize($token)));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authorization\AfterInvocation;
-
-use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
-
-use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
-use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
-use JMS\SecurityExtraBundle\Security\Authorization\AfterInvocation\AclAfterInvocationProvider;
-
-class AclAfterInvocationProviderTest extends \PHPUnit_Framework_TestCase
-{
- public function testDecideReturnsNullWhenObjectIsNull()
- {
- $provider = new AclAfterInvocationProvider($this->getAclProvider(), $this->getOidStrategy(), $this->getSidStrategy(), $this->getPermissionMap());
-
- $this->assertNull($provider->decide($this->getToken(), null, array(), null));
- }
-
- public function testDecideDoesNotModifyReturnedObjectWhenNoAttributeIsSupported()
- {
- $provider = new AclAfterInvocationProvider($this->getAclProvider(), $this->getOidStrategy(), $this->getSidStrategy(), $this->getPermissionMap());
-
- $returnedObject = new \stdClass;
- $this->assertSame($returnedObject, $provider->decide($this->getToken(), null, array('foo', 'moo'), $returnedObject));
- }
-
- public function testDecideDoesNotModifyReturnedObjectWhenNoObjectIdentityCanBeRetrieved()
- {
- $oidStrategy = $this->getOidStrategy();
- $oidStrategy
- ->expects($this->once())
- ->method('getObjectIdentity')
- ->will($this->returnValue(null))
- ;
-
- $permissionMap = $this->getPermissionMap();
- $permissionMap
- ->expects($this->once())
- ->method('contains')
- ->will($this->returnValue(true))
- ;
-
- $returnedObject = array('foo' => 'moo');
- $provider = new AclAfterInvocationProvider($this->getAclProvider(), $oidStrategy, $this->getSidStrategy(), $permissionMap);
- $this->assertSame($returnedObject, $provider->decide($this->getToken(), null, array('foo'), $returnedObject));
- }
-
- /**
- * @expectedException Symfony\Component\Security\Core\Exception\AccessDeniedException
- */
- public function testDecideThrowsAccessDeniedExceptionWhenNoAclIsFound()
- {
- $oidStrategy = $this->getOidStrategy();
- $oidStrategy
- ->expects($this->once())
- ->method('getObjectIdentity')
- ->will($this->returnValue(new ObjectIdentity(1, 'foo')))
- ;
-
- $sidStrategy = $this->getSidStrategy();
- $sidStrategy
- ->expects($this->once())
- ->method('getSecurityIdentities')
- ->will($this->returnValue(array()))
- ;
-
- $permissionMap = $this->getPermissionMap();
- $permissionMap
- ->expects($this->once())
- ->method('contains')
- ->will($this->returnValue(true))
- ;
-
- $aclProvider = $this->getAclProvider();
- $aclProvider
- ->expects($this->once())
- ->method('findAcl')
- ->will($this->throwException(new AclNotFoundException('No ACL')))
- ;
-
- $provider = new AclAfterInvocationProvider($aclProvider, $oidStrategy, $sidStrategy, $permissionMap);
- $provider->decide($this->getToken(), null, array('foo'), 'foo');
- }
-
- /**
- * @expectedException Symfony\Component\Security\Core\Exception\AccessDeniedException
- */
- public function testDecideThrowsAccessDeniedExceptionWhenNoAceIsFound()
- {
- $masks = array(1, 3);
- $permissionMap = $this->getPermissionMap();
- $permissionMap
- ->expects($this->once())
- ->method('contains')
- ->will($this->returnValue(true))
- ;
- $permissionMap
- ->expects($this->once())
- ->method('getMasks')
- ->will($this->returnValue($masks))
- ;
-
- $acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface');
- $acl
- ->expects($this->once())
- ->method('isGranted')
- ->will($this->throwException(new NoAceFoundException('No ACE')))
- ;
-
- $aclProvider = $this->getAclProvider();
- $aclProvider
- ->expects($this->once())
- ->method('findAcl')
- ->will($this->returnValue($acl))
- ;
-
- $oidStrategy = $this->getOidStrategy();
- $oidStrategy
- ->expects($this->once())
- ->method('getObjectIdentity')
- ->will($this->returnValue(new ObjectIdentity(1, 'foo')))
- ;
-
- $sidStrategy = $this->getSidStrategy();
- $sidStrategy
- ->expects($this->once())
- ->method('getSecurityIdentities')
- ->will($this->returnValue(array('foo')))
- ;
-
- $provider = new AclAfterInvocationProvider($aclProvider, $oidStrategy, $sidStrategy, $permissionMap);
- $provider->decide($this->getToken(), null, array('foo'), array('foo'));
- }
-
- public function testDecide()
- {
- $masks = array(1, 3);
- $permissionMap = $this->getPermissionMap();
- $permissionMap
- ->expects($this->once())
- ->method('contains')
- ->will($this->returnValue(true))
- ;
- $permissionMap
- ->expects($this->once())
- ->method('getMasks')
- ->will($this->returnValue($masks))
- ;
-
- $acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface');
- $acl
- ->expects($this->once())
- ->method('isGranted')
- ->will($this->returnValue(true))
- ;
-
- $aclProvider = $this->getAclProvider();
- $aclProvider
- ->expects($this->once())
- ->method('findAcl')
- ->will($this->returnValue($acl))
- ;
-
- $oidStrategy = $this->getOidStrategy();
- $oidStrategy
- ->expects($this->once())
- ->method('getObjectIdentity')
- ->will($this->returnValue(new ObjectIdentity(1, 'foo')))
- ;
-
- $sidStrategy = $this->getSidStrategy();
- $sidStrategy
- ->expects($this->once())
- ->method('getSecurityIdentities')
- ->will($this->returnValue(array('foo')))
- ;
-
- $provider = new AclAfterInvocationProvider($aclProvider, $oidStrategy, $sidStrategy, $permissionMap);
- $this->assertSame(array('foo'), $provider->decide($this->getToken(), null, array('foo'), array('foo')));
- }
-
- public function testSupportsAttribute()
- {
- $aclProvider = $this->getAclProvider();
- $oidStrategy = $this->getOidStrategy();
- $sidStrategy = $this->getSidStrategy();
- $permissionMap = $this->getPermissionMap();
-
- $permissionMap
- ->expects($this->at(0))
- ->method('contains')
- ->with($this->equalTo('foo'))
- ->will($this->returnValue(true))
- ;
- $permissionMap
- ->expects($this->at(1))
- ->method('contains')
- ->with($this->equalTo('asdf'))
- ->wilL($this->returnValue(false))
- ;
-
- $provider = new AclAfterInvocationProvider($aclProvider, $oidStrategy, $sidStrategy, $permissionMap);
- $this->assertTrue($provider->supportsAttribute('foo'));
- $this->assertFalse($provider->supportsAttribute('asdf'));
- }
-
- protected function getToken()
- {
- return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
- }
-
- protected function getPermissionMap()
- {
- return $this->getMock('Symfony\Component\Security\Acl\Permission\PermissionMapInterface');
- }
-
- protected function getAclProvider()
- {
- return $this->getMock('Symfony\Component\Security\Acl\Model\AclProviderInterface');
- }
-
- protected function getOidStrategy()
- {
- return $this->getMock('Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface');
- }
-
- protected function getSidStrategy()
- {
- return $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authorization\AfterInvocation;
-
-use JMS\SecurityExtraBundle\Security\Authorization\AfterInvocation\AfterInvocationManager;
-
-class AfterInvocationManagerTest extends \PHPUnit_Framework_TestCase
-{
- public function testDecide()
- {
- $attributes = array('FOO');
-
- $provider1 = $this->getProvider();
- $provider1
- ->expects($this->once())
- ->method('decide')
- ->with(
- $this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'),
- $this->anything(),
- $this->equalTo($attributes),
- $this->equalTo('foo')
- )
- ->will($this->returnValue('bar'))
- ;
-
- $provider2 = $this->getProvider();
- $provider2
- ->expects($this->once())
- ->method('decide')
- ->with(
- $this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'),
- $this->anything(),
- $this->equalTo($attributes),
- $this->equalTo('bar')
- )
- ->will($this->returnValue('moo'))
- ;
-
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
-
- $manager = new AfterInvocationManager(array($provider1, $provider2));
- $this->assertEquals('moo', $manager->decide($token, 'sth', $attributes, 'foo'));
- }
-
- /**
- * @dataProvider getSupportsTests
- */
- public function testSupportsAttribute($attribute, $supported)
- {
- $provider = $this->getProvider();
- $provider
- ->expects($this->once())
- ->method('supportsAttribute')
- ->with($this->equalTo($attribute))
- ->will($this->returnValue($supported))
- ;
-
- $manager = new AfterInvocationManager(array($provider));
- $this->assertSame($supported, $manager->supportsAttribute($attribute));
- }
-
- /**
- * @dataProvider getSupportsTests
- */
- public function testSupportsClass($class, $supported)
- {
- $provider = $this->getProvider();
- $provider
- ->expects($this->once())
- ->method('supportsClass')
- ->with($this->equalTo($class))
- ->will($this->returnValue($supported))
- ;
-
- $manager = new AfterInvocationManager(array($provider));
- $this->assertSame($supported, $manager->supportsClass($class));
- }
-
- public function getSupportsTests()
- {
- return array(
- array('FOO', true),
- array('BAR', false),
- );
- }
-
- protected function getProvider()
- {
- return $this->getMock('JMS\SecurityExtraBundle\Security\Authorization\AfterInvocation\AfterInvocationProviderInterface');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authorization\Expression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\ParameterExpressionCompiler;
-
-use JMS\SecurityExtraBundle\Security\Acl\Expression\HasPermissionFunctionCompiler;
-
-use JMS\SecurityExtraBundle\Tests\Security\Authorization\Expression\Fixture\Issue22\Project;
-
-use JMS\SecurityExtraBundle\Tests\Security\Authorization\Expression\Fixture\Issue22\SecuredObject;
-use CG\Proxy\MethodInvocation;
-use Symfony\Component\Security\Core\Role\Role;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Expression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-class ExpressionCompilerTest extends \PHPUnit_Framework_TestCase
-{
- private $compiler;
-
- public function testCompileExpression()
- {
- $evaluator = eval($this->compiler->compileExpression(new Expression('isAnonymous()')));
-
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
-
- $trustResolver = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface');
- $trustResolver->expects($this->once())
- ->method('isAnonymous')
- ->with($token)
- ->will($this->returnValue(true));
-
- $context = array(
- 'token' => $token,
- 'trust_resolver' => $trustResolver,
- );
-
- $this->assertTrue($evaluator($context));
- }
-
- public function testCompileComplexExpression()
- {
- $evaluator = eval($this->compiler->compileExpression(
- new Expression('hasRole("ADMIN") or hasAnyRole("FOO", "BAR")')));
-
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
- $token->expects($this->once())
- ->method('getRoles')
- ->will($this->returnValue(array(new Role('FOO'))));
- $this->assertTrue($evaluator(array('token' => $token)));
-
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
- $token->expects($this->once())
- ->method('getRoles')
- ->will($this->returnValue(array(new Role('BAZ'))));
- $this->assertFalse($evaluator(array('token' => $token)));
- }
-
- /**
- * @dataProvider getPrecedenceTests
- */
- public function testCompilePrecedence($expected, $a, $b, $c)
- {
- $evaluator = eval($this->compiler->compileExpression(
- new Expression('A and (B or C)')));
-
- $this->assertSame($expected, $evaluator(array('A' => $a, 'B' => $b, 'C' => $c)));
- }
-
- public function getPrecedenceTests()
- {
- return array(
- array(true, true, true, false),
- array(true, true, true, true),
- array(true, true, false, true),
- array(false, true, false, false),
- array(false, false, true, true),
- array(false, false, true, false),
- array(false, false, false, true),
- array(false, false, false, false),
- );
- }
-
- public function testCompileWhenParameterIsWrappedInMethodCall()
- {
- $this->compiler->addTypeCompiler(new ParameterExpressionCompiler());
- $this->compiler->addFunctionCompiler(new HasPermissionFunctionCompiler());
-
- // the first call ensure that state is reset correctly
- $this->compiler->compileExpression(new Expression(
- 'hasPermission(#project.getCompany(), "OPERATOR")'));
- $evaluator = eval($this->compiler->compileExpression(
- new Expression('hasPermission(#project.getCompany(), "OPERATOR")')));
-
- $secureObject = new SecuredObject();
- $project = new Project();
- $permissionEvaluator = $this->getMockBuilder('JMS\SecurityExtraBundle\Security\Acl\Expression\PermissionEvaluator')
- ->disableOriginalConstructor()
- ->getMock();
- $permissionEvaluator->expects($this->once())
- ->method('hasPermission')
- ->will($this->returnValue(false));
-
- $context = array(
- 'token' => $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'),
- 'object' => new MethodInvocation(new \ReflectionMethod($secureObject, 'delete'), $secureObject, array($project), array()),
- 'permission_evaluator' => $permissionEvaluator,
- );
-
- $this->assertFalse($evaluator($context));
- }
-
- /**
- * @dataProvider getUnaryNotTests
- */
- public function testCompileWithUnaryOperator($roles, $expected)
- {
- $evaluator = eval($this->compiler->compileExpression(new Expression(
- 'not hasRole("FOO") and !hasRole("BAR") and hasRole("BAZ")')));
-
- $roles = array_map(function($v) {
- return new Role($v);
- }, $roles);
-
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
- $token->expects($this->once())
- ->method('getRoles')
- ->will($this->returnValue($roles));
-
- $this->assertSame($expected, $evaluator(array('token' => $token)));
- }
-
- public function getUnaryNotTests()
- {
- return array(
- array(array('FOO'), false),
- array(array(), false),
- array(array('BAR'), false),
- array(array('BAZ'), true),
- array(array('FOO', 'BAR'), false),
- array(array('FOO', 'BAZ'), false),
- array(array('BAR', 'BAZ'), false),
- );
- }
-
- protected function setUp()
- {
- $this->compiler = new ExpressionCompiler();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authorization\Expression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionLexer;
-
-class ExpressionLexerTest extends \PHPUnit_Framework_TestCase
-{
- private $lexer;
-
- public function testParameter()
- {
- $this->lexer->initialize('#contact');
-
- $this->assertEquals(array(
- 'type' => ExpressionLexer::T_PARAMETER,
- 'value' => 'contact',
- 'position' => 0,
- ), $this->lexer->lookahead);
- $this->assertFalse($this->lexer->next());
- }
-
- protected function setUp()
- {
- $this->lexer = new ExpressionLexer();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authorization\Expression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\IsEqualExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ParameterExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ConstantExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\GetItemExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\ArrayExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\MethodCallExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\GetPropertyExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\VariableExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\OrExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\AndExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Ast\FunctionExpression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionParser;
-
-class ExpressionParserTest extends \PHPUnit_Framework_TestCase
-{
- private $parser;
-
- public function testSingleFunction()
- {
- $this->assertEquals(new FunctionExpression('isAnonymous', array()),
- $this->parser->parse('isAnonymous()'));
- }
-
- public function testSingleFunctionWithOneArgument()
- {
- $this->assertEquals(new FunctionExpression('hasRole', array(
- new ConstantExpression('ROLE_ADMIN'))),
- $this->parser->parse('hasRole("ROLE_ADMIN")'));
- }
-
- public function testSingleFunctionWithMultipleArguments()
- {
- $this->assertEquals(new FunctionExpression('hasAnyRole', array(
- new ConstantExpression('FOO'), new ConstantExpression('BAR'))),
- $this->parser->parse('hasAnyRole("FOO", "BAR",)'));
- }
-
- public function testComplexFunctionExpression()
- {
- $expected = new OrExpression(new FunctionExpression('hasRole', array(
- new ConstantExpression('ADMIN'))),
- new FunctionExpression('hasAnyRole', array(new ConstantExpression('FOO'),
- new ConstantExpression('BAR'))));
-
- $this->assertEquals($expected, $this->parser->parse('hasRole("ADMIN") or hasAnyRole("FOO", "BAR")'));
- }
-
- public function testAnd()
- {
- $expected = new AndExpression(
- new FunctionExpression('isAnonymous', array()),
- new FunctionExpression('hasRole', array(new ConstantExpression('FOO'))));
-
- $this->assertEquals($expected, $this->parser->parse('isAnonymous() && hasRole("FOO")'));
- $this->assertEquals($expected, $this->parser->parse('isAnonymous() and hasRole("FOO")'));
- }
-
- /**
- * @dataProvider getPrecedenceTests
- */
- public function testPrecendence($expected, $expr)
- {
- $this->assertEquals($expected, $this->parser->parse($expr));
- }
-
- public function getPrecedenceTests()
- {
- $tests = array();
-
- $expected = new OrExpression(
- new AndExpression(new VariableExpression('A'), new VariableExpression('B')),
- new VariableExpression('C')
- );
- $tests[] = array($expected, 'A && B || C');
- $tests[] = array($expected, '(A && B) || C');
-
- $expected = new OrExpression(
- new VariableExpression('C'),
- new AndExpression(new VariableExpression('A'), new VariableExpression('B'))
- );
- $tests[] = array($expected, 'C || A && B');
- $tests[] = array($expected, 'C || (A && B)');
-
- $expected = new AndExpression(
- new AndExpression(new VariableExpression('A'), new VariableExpression('B')),
- new VariableExpression('C')
- );
- $tests[] = array($expected, 'A && B && C');
-
- $expected = new AndExpression(
- new VariableExpression('A'),
- new OrExpression(new VariableExpression('B'), new VariableExpression('C'))
- );
- $tests[] = array($expected, 'A && (B || C)');
-
- return $tests;
- }
-
- public function testGetProperty()
- {
- $expected = new GetPropertyExpression(new VariableExpression('A'), 'foo');
- $this->assertEquals($expected, $this->parser->parse('A.foo'));
- }
-
- public function testMethodCall()
- {
- $expected = new MethodCallExpression(new VariableExpression('A'), 'foo', array());
- $this->assertEquals($expected, $this->parser->parse('A.foo()'));
- }
-
- public function testArray()
- {
- $expected = new ArrayExpression(array(
- 'foo' => new ConstantExpression('bar'),
- ));
- $this->assertEquals($expected, $this->parser->parse('{"foo":"bar",}'));
- $this->assertEquals($expected, $this->parser->parse('{"foo":"bar"}'));
-
- $expected = new ArrayExpression(array(
- new ConstantExpression('foo'),
- new ConstantExpression('bar'),
- ));
- $this->assertEquals($expected, $this->parser->parse('["foo","bar",]'));
- $this->assertEquals($expected, $this->parser->parse('["foo","bar"]'));
- }
-
- public function testGetItem()
- {
- $expected = new GetItemExpression(
- new GetPropertyExpression(new VariableExpression('A'), 'foo'),
- new ConstantExpression('foo')
- );
- $this->assertEquals($expected, $this->parser->parse('A.foo["foo"]'));
- }
-
- public function testParameter()
- {
- $expected = new ParameterExpression('contact');
- $this->assertEquals($expected, $this->parser->parse('#contact'));
- }
-
- public function testIsEqual()
- {
- $expected = new IsEqualExpression(new MethodCallExpression(
- new VariableExpression('user'), 'getUsername', array()),
- new ConstantExpression('Johannes'));
- $this->assertEquals($expected, $this->parser->parse('user.getUsername() == "Johannes"'));
- }
-
- protected function setUp()
- {
- $this->parser = new ExpressionParser;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authorization\Expression;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\DefaultExpressionHandler;
-use Symfony\Component\Security\Core\Role\Role;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
-use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Expression;
-use Symfony\Component\HttpKernel\Util\Filesystem;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionVoter;
-
-class ExpressionVoterTest extends \PHPUnit_Framework_TestCase
-{
- private $voter;
- private $cacheDir;
- private $fs;
-
- public function testVoteWithoutCache()
- {
- $this->voter->setCacheDir(null);
-
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
- $token->expects($this->once())
- ->method('getRoles')
- ->will($this->returnValue(array(new Role('ROLE_FOO'))));
-
- $this->assertSame(VoterInterface::ACCESS_GRANTED, $this->voter->vote(
- $token,
- new \stdClass,
- array(new Expression('hasRole("ROLE_FOO")'))
- ));
- }
-
- /**
- * @dataProvider getVoteTests
- */
- public function testVote($token, $object, array $attributes, $expected)
- {
- $this->assertSame($expected, $this->voter->vote($token, $object, $attributes));
- }
-
- public function getVoteTests()
- {
- $tests = array();
-
- $tests[] = array(
- $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'),
- new \stdClass(),
- array('ROLE_FOO'),
- VoterInterface::ACCESS_ABSTAIN,
- );
-
- $tests[] = array(
- $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')
- ->disableOriginalConstructor()->getMock(),
- new \stdClass(),
- array(new Expression('isAnonymous()')),
- VoterInterface::ACCESS_GRANTED,
- );
-
- $tests[] = array(
- $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')
- ->disableOriginalConstructor()->getMock(),
- new \stdClass(),
- array(new Expression('isAuthenticated()')),
- VoterInterface::ACCESS_DENIED,
- );
-
- return $tests;
- }
-
- public function testSupportsAttribute()
- {
- $this->assertFalse($this->voter->supportsAttribute('ROLE_FOO'));
- $this->assertFalse($this->voter->supportsAttribute('A'));
- $this->assertTrue($this->voter->supportsAttribute(new Expression('A')));
- }
-
- public function testSupportsClass()
- {
- $this->assertTrue($this->voter->supportsClass('stdClass'));
- }
-
- protected function setUp()
- {
- $handler = new DefaultExpressionHandler(new AuthenticationTrustResolver(
- 'Symfony\Component\Security\Core\Authentication\Token\AnonymousToken',
- 'Symfony\Component\Security\Core\Authentication\Token\RememberMeToken'));
-
- $this->voter = new ExpressionVoter($handler);
- $this->voter->setCompiler(new ExpressionCompiler());
-
- $this->fs = new Filesystem();
- $this->cacheDir = sys_get_temp_dir().'/'.uniqid('expression_voter', true);
-
- if (is_dir($this->cacheDir)) {
- $this->fs->remove($this->cacheDir);
- }
-
- if (false === @mkdir($this->cacheDir, 0777, true)) {
- throw new \RuntimeException(sprintf('Could not create cache dir "%s".', $this->cacheDir));
- }
- }
-
- protected function tearDown()
- {
- if (null !== $this->fs) {
- $this->fs->remove($this->cacheDir);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authorization\Expression\Fixture\Issue22;
-
-class Project
-{
- public $company;
-
- public function __construct()
- {
- $this->company = new \stdClass;
- }
-
- public function getCompany()
- {
- return $this->company;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authorization\Expression\Fixture\Issue22;
-
-class SecuredObject
-{
- /**
- * @PreAuthorize("hasPermission(#project.getCompany(), 'OPERATOR')")
- */
- public function delete(Project $project)
- {
- return true;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authorization\Expression;
-
-use CG\Proxy\MethodInvocation;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Expression;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Compiler\ParameterExpressionCompiler;
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\ExpressionCompiler;
-
-class ParameterExpressionCompilerTest extends \PHPUnit_Framework_TestCase
-{
- private $compiler;
-
- public function testCompile()
- {
- $evaluator = eval($source = $this->compiler->compileExpression(new Expression(
- '#foo == "bar"')));
-
- $object = new ParameterAccessTest;
- $reflection = new \ReflectionMethod($object, 'secure');
- $invocation = new MethodInvocation($reflection, $object, array('bar'), array());
- $this->assertTrue($evaluator(array('object' => $invocation)));
-
- $invocation->arguments = array('foo');
- $this->assertFalse($evaluator(array('object' => $invocation)));
- }
-
- /**
- * @expectedException \RuntimeException
- */
- public function testCompileThrowsExceptionWhenNoMethodInvocation()
- {
- $evaluator = eval($this->compiler->compileExpression(new Expression(
- '#foo == "fofo"')));
-
- $evaluator(array('object' => new \stdClass));
- }
-
- protected function setUp()
- {
- $this->compiler = new ExpressionCompiler();
- $this->compiler->addTypeCompiler(new ParameterExpressionCompiler());
- }
-}
-
-class ParameterAccessTest
-{
- public function secure($foo)
- {
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/*
- * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authorization\Interception;
-
-use JMS\SecurityExtraBundle\Exception\RuntimeException;
-use JMS\SecurityExtraBundle\Metadata\MethodMetadata;
-
-use JMS\SecurityExtraBundle\Metadata\ClassMetadata;
-
-use Metadata\MetadataFactoryInterface;
-
-use JMS\SecurityExtraBundle\Security\Authentication\Token\RunAsUserToken;
-use Symfony\Component\Security\Core\Exception\AuthenticationException;
-use JMS\SecurityExtraBundle\Security\Authorization\Interception\MethodSecurityInterceptor;
-use CG\Proxy\MethodInvocation;
-
-class MethodSecurityInterceptorTest extends \PHPUnit_Framework_TestCase
-{
- /**
- * @expectedException Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
- */
- public function testInvokeThrowsExceptionWhenSecurityContextHasNoToken()
- {
- list($interceptor, $securityContext,,,,) = $this->getInterceptor();
-
- $securityContext
- ->expects($this->once())
- ->method('getToken')
- ->will($this->returnValue(null))
- ;
-
- $this->getInvocation($interceptor)->proceed();
- }
-
- /**
- * @expectedException Symfony\Component\Security\Core\Exception\AuthenticationException
- */
- public function testInvokeAuthenticatesTokenIfItIsNotYetAuthenticated()
- {
- list($interceptor, $securityContext, $authManager,,,) = $this->getInterceptor();
-
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
- $token
- ->expects($this->once())
- ->method('isAuthenticated')
- ->will($this->returnValue(false))
- ;
-
- $securityContext
- ->expects($this->once())
- ->method('getToken')
- ->will($this->returnValue($token))
- ;
-
- $authManager
- ->expects($this->once())
- ->method('authenticate')
- ->will($this->throwException(new AuthenticationException('Could not authenticate.')))
- ;
-
- $this->getInvocation($interceptor)->proceed();
- }
-
- /**
- * @expectedException Symfony\Component\Security\Core\Exception\AuthenticationException
- */
- public function testInvokeAuthenticatesTokenIfAlwaysAuthenticateIsTrue()
- {
- list($interceptor, $securityContext, $authManager,,,) = $this->getInterceptor();
-
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
-
- $securityContext
- ->expects($this->once())
- ->method('getToken')
- ->will($this->returnValue($token))
- ;
-
- $authManager
- ->expects($this->once())
- ->method('authenticate')
- ->will($this->throwException(new AuthenticationException('Could not authenticate.')))
- ;
-
- $invocation = $this->getInvocation($interceptor);
- $interceptor->setAlwaysAuthenticate(true);
-
- $invocation->proceed();
- }
-
- /**
- * @expectedException Symfony\Component\Security\Core\Exception\AccessDeniedException
- */
- public function testInvokeCallsADMForRolesAndThrowsExceptionWhenInsufficientPriviledges()
- {
- $factory = $this->getMock('Metadata\MetadataFactoryInterface');
- $metadata = new ClassMetadata('JMS\SecurityExtraBundle\Tests\Security\Authorization\Interception\SecureService');
- $metadata->methodMetadata['foo'] = new MethodMetadata('JMS\SecurityExtraBundle\Tests\Security\Authorization\Interception\SecureService', 'foo');
- $metadata->methodMetadata['foo']->roles = array('ROLE_FOO');
- $factory
- ->expects($this->once())
- ->method('getMetadataForClass')
- ->with($this->equalTo($metadata->reflection->name))
- ->will($this->returnValue($metadata))
- ;
-
- list($interceptor, $context, $authManager, $adm,,) = $this->getInterceptor($factory);
-
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
- $token
- ->expects($this->once())
- ->method('isAuthenticated')
- ->will($this->returnValue(false))
- ;
-
- $context
- ->expects($this->once())
- ->method('getToken')
- ->will($this->returnValue($token))
- ;
- $context
- ->expects($this->once())
- ->method('setToken')
- ->with($this->equalTo($token))
- ;
-
- $authManager
- ->expects($this->once())
- ->method('authenticate')
- ->will($this->returnValue($token))
- ;
-
- $invocation = $this->getInvocation($interceptor);
- $adm
- ->expects($this->once())
- ->method('decide')
- ->with($this->equalTo($token), $this->equalTo(array('ROLE_FOO')), $this->equalTo($invocation))
- ->will($this->returnValue(false))
- ;
-
- $invocation->proceed();
- }
-
- /**
- * @expectedException Symfony\Component\Security\Core\Exception\AccessDeniedException
- */
- public function testInvokeCallsADMForEachParamPermissionsAndThrowsExceptionOnInsufficientPermissions()
- {
- $factory = $this->getMock('Metadata\MetadataFactoryInterface');
- $metadata = new ClassMetadata('JMS\SecurityExtraBundle\Tests\Security\Authorization\Interception\SecureService');
- $metadata->methodMetadata['foo'] = new MethodMetadata('JMS\SecurityExtraBundle\Tests\Security\Authorization\Interception\SecureService', 'foo');
- $metadata->methodMetadata['foo']->paramPermissions = array(
- $p0 = array('ROLE_FOO', 'ROLE_ASDF'),
- $p1 = array('ROLE_MOO'),
- );
- $factory
- ->expects($this->once())
- ->method('getMetadataForClass')
- ->with($this->equalTo($metadata->reflection->name))
- ->will($this->returnValue($metadata))
- ;
-
- list($interceptor, $context,, $adm,,) = $this->getInterceptor($factory);
-
- $context
- ->expects($this->once())
- ->method('getToken')
- ->will($this->returnValue($token = $this->getToken()))
- ;
-
- $invocation = $this->getInvocation($interceptor);
- $adm
- ->expects($this->at(0))
- ->method('decide')
- ->with($this->equalTo($token), $this->equalTo($p0), $this->equalTo(new \stdClass()))
- ->will($this->returnValue(true))
- ;
- $adm
- ->expects($this->at(1))
- ->method('decide')
- ->with($this->equalTo($token), $this->equalTo($p1), $this->equalTo(new \stdClass()))
- ->will($this->returnValue(false))
- ;
-
- $invocation->proceed();
- }
-
- /**
- * @expectedException \RuntimeException
- */
- public function testInvokehandlesExceptionsFromWithintheInvokedMethodGracefully()
- {
- $factory = $this->getMock('Metadata\MetadataFactoryInterface');
- $metadata = new ClassMetadata('JMS\SecurityExtraBundle\Tests\Security\Authorization\Interception\SecureService');
- $metadata->methodMetadata['throwException'] = new MethodMetadata('JMS\SecurityExtraBundle\Tests\Security\Authorization\Interception\SecureService', 'foo');
- $metadata->methodMetadata['throwException']->runAsRoles = array('ROLE_FOO');
- $factory
- ->expects($this->once())
- ->method('getMetadataForClass')
- ->with($this->equalTo($metadata->reflection->name))
- ->will($this->returnValue($metadata))
- ;
-
- list($interceptor, $context,,,, $runAsManager) = $this->getInterceptor($factory);
- $invocation = $this->getInvocation($interceptor, 'throwException');
-
- $token = $this->getToken();
- $context
- ->expects($this->once())
- ->method('getToken')
- ->will($this->returnValue($token))
- ;
-
- $runAsToken = new RunAsUserToken('asdf', 'user', 'foo', array('ROLE_FOO'), $token);
- $runAsManager
- ->expects($this->once())
- ->method('buildRunAs')
- ->will($this->returnValue($runAsToken))
- ;
-
- $context
- ->expects($this->exactly(2))
- ->method('setToken')
- ;
-
- $invocation->proceed();
- }
-
- protected function getToken($isAuthenticated = true)
- {
- $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
- $token
- ->expects($this->once())
- ->method('isAuthenticated')
- ->will($this->returnValue($isAuthenticated))
- ;
-
- return $token;
- }
-
- protected function getInterceptor(MetadataFactoryInterface $metadataFactory = null)
- {
- if (null === $metadataFactory) {
- $metadataFactory = $this->getMock('Metadata\MetadataFactoryInterface');
-
- $metadata = new ClassMetadata('JMS\SecurityExtraBundle\Tests\Security\Authorization\Interception\SecureService');
- $metadata->methodMetadata['foo'] = new MethodMetadata('JMS\SecurityExtraBundle\Tests\Security\Authorization\Interception\SecureService', 'foo');
-
- $metadataFactory
- ->expects($this->once())
- ->method('getMetadataForClass')
- ->with($this->equalTo('JMS\SecurityExtraBundle\Tests\Security\Authorization\Interception\SecureService'))
- ->will($this->returnValue($metadata))
- ;
- }
-
- $securityContext = $this->getMockBuilder('Symfony\Component\Security\Core\SecurityContext')
- ->disableOriginalConstructor()
- ->getMock();
-
- $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
- $accessDecisionManager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface');
- $afterInvocationManager = $this->getMock('JMS\SecurityExtraBundle\Security\Authorization\AfterInvocation\AfterInvocationManagerInterface');
- $runAsManager = $this->getMock('JMS\SecurityExtraBundle\Security\Authorization\RunAsManagerInterface');
-
- return array(
- new MethodSecurityInterceptor($securityContext, $authenticationManager, $accessDecisionManager, $afterInvocationManager, $runAsManager, $metadataFactory),
- $securityContext,
- $authenticationManager,
- $accessDecisionManager,
- $afterInvocationManager,
- $runAsManager,
- );
- }
-
- protected function getInvocation(MethodSecurityInterceptor $interceptor, $method = 'foo', $arguments = array())
- {
- if ('foo' === $method && 0 === count($arguments)) {
- $arguments = array(new \stdClass(), new \stdClass());
- }
- $object = new SecureService();
-
- return new MethodInvocation(new \ReflectionMethod($object, $method), $object, $arguments, array($interceptor));
- }
-}
-
-class SecureService
-{
- public function foo($param, $other)
- {
- return $param;
- }
-
- public function throwException()
- {
- throw new RuntimeException;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Tests\Security\Authorization\Interception;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Interception\SecurityPointcut;
-
-class SecurityPointcutTest extends \PHPUnit_Framework_TestCase
-{
- private $metadataFactory;
-
- public function testMatchesAllClassesIfNotExplicitlyGiven()
- {
- $pointcut = new SecurityPointcut($this->metadataFactory, false, array(
- 'Foo::bar' => 'foo',
- 'login$' => 'foo',
- ));
-
- $this->assertTrue($pointcut->matchesClass(new \ReflectionClass('stdClass')));
- }
-
- public function testMatchesClassReturnsFalseForControllerNotation()
- {
- $pointcut = new SecurityPointcut($this->metadataFactory, false, array(
- 'AcmeFooBundle:Foo:foo' => 'foo',
- ));
-
- $this->assertFalse($pointcut->matchesClass(new \ReflectionClass('stdClass')));
- }
-
- protected function setUp()
- {
- $this->metadataFactory = $this->getMock('Metadata\MetadataFactoryInterface');
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-namespace JMS\SecurityExtraBundle\Twig;
-
-use JMS\SecurityExtraBundle\Security\Authorization\Expression\Expression;
-use Symfony\Component\Security\Core\SecurityContextInterface;
-
-class SecurityExtension extends \Twig_Extension
-{
- private $context;
-
- public function __construct(SecurityContextInterface $context)
- {
- $this->context = $context;
- }
-
- public function getFunctions()
- {
- return array(
- 'is_expr_granted' => new \Twig_Function_Method($this, 'isExprGranted', array(
- 'is_safe' => true,
- )),
- );
- }
-
- public function isExprGranted($expr, $object = null)
- {
- return $this->context->isGranted(array(new Expression($expr)), $object);
- }
-
- public function getName()
- {
- return 'jms_security_extra';
- }
-}
\ No newline at end of file
+++ /dev/null
-{
- "name": "jms/security-extra-bundle",
- "description": "Enhances the Symfony2 Security Component by adding several new features",
- "keywords": ["annotations","authorization"],
- "type": "symfony-bundle",
- "license": "Apache",
- "authors": [
- {
- "name": "Johannes M. Schmitt",
- "email": "schmittjoh@gmail.com"
- }
- ],
- "require": {
- "symfony/framework-bundle": "2.*",
- "jms/metadata": "1.1.*",
- "jms/aop-bundle": "1.0.*"
- },
- "recommend": {
- "jms/di-extra-bundle": "1.0.*"
- },
- "autoload": {
- "psr-0": { "JMS\\SecurityExtraBundle": "" }
- },
- "target-dir": "JMS/SecurityExtraBundle"
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-\r
-<phpunit backupGlobals="false"\r
- backupStaticAttributes="false"\r
- colors="true"\r
- convertErrorsToExceptions="true"\r
- convertNoticesToExceptions="true"\r
- convertWarningsToExceptions="true"\r
- processIsolation="false"\r
- stopOnFailure="false"\r
- syntaxCheck="false"\r
- bootstrap="./../../../../app/bootstrap.php.cache"\r
->\r
- <testsuites>\r
- <testsuite name="SecurityExtraBbundle Test Suite">\r
- <directory>./Tests</directory>\r
- </testsuite>\r
- </testsuites>\r
-</phpunit>\r
+++ /dev/null
-Subproject commit d6f89a3170c5280ad554347dc113eb25fdf00ad7
+++ /dev/null
-Subproject commit b704c49a3051536f67f2d39f13568f74615b9922
+++ /dev/null
-Subproject commit 77323c97860fc2f73d988b2020ae414faebed153
+++ /dev/null
-Subproject commit e9ac8f1a911ed29e30296c7f1549f53d4c94eddf
+++ /dev/null
-Subproject commit 43ed45c48db18e4a0e48aec0c098f42e56e22d36
+++ /dev/null
-Subproject commit 982b4c9498b7dd85e70f6d35e65d909c888e6345
+++ /dev/null
-Subproject commit 0ab776227a0d6586c9f1be379926acaa94f64a01
+++ /dev/null
-Subproject commit f43cc520d6abb3868d36a3011874afbf13166317
+++ /dev/null
-/*
-Copyright (c) 2010, Yahoo! Inc. All rights reserved.
-Code licensed under the BSD License:
-http://developer.yahoo.com/yui/license.html
-version: 2.8.2r1
-
-Reset
-*/
-
-html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var,optgroup{font-style:inherit;font-weight:inherit;}del,ins{text-decoration:none;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:baseline;}sub{vertical-align:baseline;}legend{color:#000;}input,button,textarea,select,optgroup,option{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;}input,button,textarea,select{*font-size:100%;}
-
-html, body
-{
- background-color: #EFEFEF;
-}
-
-body
-{
- font-size: 14px;
- font-family: "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
- color: #313131;
-}
-
-a
-{
- color: #08C;
- text-decoration: none;
-}
-
-a:hover
-{
- text-decoration: underline;
-}
-
-strong
-{
- font-weight: bold;
-}
-
-em
-{
- font-style: italic;
-}
-
-h1, h2, h3
-{
- font-family: Georgia, "Times New Roman", Times, serif;
- color: #404040;
-}
-
-h1
-{
- font-size: 45px;
- padding-bottom: 30px;
-}
-
-h2
-{
- font-weight: bold;
- color: #FFFFFF;
- /* Font is duplicated of body (sans-serif) */
- font-family: "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
-
- margin-bottom: 10px;
- background-color: #aacd4e;
- padding: 2px 4px;
- display: inline-block;
- text-transform: uppercase;
-
-}
-
-p
-{
- line-height: 20px;
- padding-bottom: 20px;
-}
-
-ul#demo-list a
-{
- background: url(../images/blue-arrow.png) no-repeat right 6px;
- padding-right: 10px;
-}
-
-ul, ol
-{
- padding-left: 20px;
-}
-
-li
-{
- padding-bottom: 18px;
-}
-
-ol li
-{
- list-style-type: decimal;
-}
-
-ul li
-{
- list-style-type: none;
-}
-
-#symfony-header
-{
- position: relative;
- padding: 30px 30px 20px 30px;
-}
-
-#symfony-wrapper
-{
- width: 970px;
- margin: 0 auto;
-}
-
-.symfony-content
-{
- background-color: white;
- border: 1px solid #DFDFDF;
- padding: 50px;
- -moz-border-radius: 16px;
- -webkit-border-radius: 16px;
- border-radius: 16px;
- margin-bottom: 20px;
- word-wrap: break-word;
-}
-
-#symfony-search
-{
- position: absolute;
- top: 50px;
- right: 30px;
-}
-
-#symfony-search input[type="search"]
-{
- -webkit-appearance: textfield;
-}
-
-#symfony-search-field
-{
- width: 190px;
-}
-
-#symfony-search label
-{
- display: block;
- float: left;
- width: 20px;
- height: 25px;
- background: url(../images/search.png) no-repeat left 5px;
-}
-
-#symfony-search label span
-{
- display: none;
-}
-
-input[type=text], input[type=password]
-{
- border: 1px solid #DADADA;
- background: white url(../images/field-background.gif) repeat-x left top;
- padding: 5px 6px;
- color: #565656;
- font-family: 'Lucida Sans Unicode', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif;
- font-size: 12px;
-}
-
-.symfony-button-grey,
-.symfony-button-green
-{
- font-size: 0.85em;
- font-weight: bold;
-
- cursor: pointer;
-
- display: inline-block;
- outline: none;
-
- text-align: center;
- text-transform: uppercase;
-
- padding: 3px 10px;
-
- text-shadow: 0 1px 1px rgba(0,0,0,.3);
-
- -webkit-border-radius: 4px;
- -moz-border-radius: 4px;
- border-radius: 4px;
-}
-
-.symfony-button-grey
-{
- color: #868686;
- font-weight: normal;
-
- padding: 5px 10px;
- border: solid 1px #d7d7d7;
- background: #ffffff;
- background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#d7d7d7));
- background: -moz-linear-gradient(top, #ffffff, #d7d7d7);
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#d7d7d7');
-}
-
-.symfony-button-green
-{
- padding: 5px 12px;
-
- color: white;
-
- border: solid 1px #a7da39;
- background: #a7da39;
- background: -webkit-gradient(linear, left top, left bottom, from(#a7da39), to(#6a9211));
- background: -moz-linear-gradient(top, #a7da39, #6a9211);
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#a7da39', endColorstr='#6a9211');
-}
-
-.symfony-blocks-welcome
-{
- overflow: hidden;
-}
-
-.symfony-blocks-welcome > div
-{
- background-color: whitesmoke;
- float: left;
- width: 240px;
- margin-right: 14px;
- text-align: center;
- padding: 26px 20px;
-}
-
-.symfony-blocks-welcome > div.block-demo
-{
- margin-right: 0;
-}
-
-.symfony-blocks-welcome .illustration
-{
- padding-bottom: 20px;
-}
-
-.symfony-blocks-help
-{
- overflow: hidden;
-}
-
-.symfony-blocks-help
-{
- margin-top: 30px;
- padding: 18px;
- border: 1px solid #E6E6E6;
-}
-
-.symfony-blocks-help > div
-{
- width: 254px;
- float: left;
-}
-
-.flash-message
-{
- padding: 10px;
- margin: 5px;
- margin-top: 15px;
- background-color: #ffe;
-}
-
-.error
-{
- color: red;
-}
-
-#login label, #contact_form label
-{
- display: block;
- float: left;
- width: 90px;
-}
-
-ul#menu
-{
- float: right;
- margin-bottom: 20px;
- padding-left: 0;
-}
-
-#menu li
-{
- padding-left: 0;
- margin-right: 10px;
- display: inline;
-}
+++ /dev/null
-/*
-Copyright (c) 2010, Yahoo! Inc. All rights reserved.
-Code licensed under the BSD License:
-http://developer.yahoo.com/yui/license.html
-version: 3.1.2
-build: 56
-*/
-.sf-exceptionreset html{color:#000;background:#FFF;}.sf-exceptionreset body,.sf-exceptionreset div,.sf-exceptionreset dl,.sf-exceptionreset dt,.sf-exceptionreset dd,.sf-exceptionreset ul,.sf-exceptionreset ol,.sf-exceptionreset li,.sf-exceptionreset h1,.sf-exceptionreset h2,.sf-exceptionreset h3,.sf-exceptionreset h4,.sf-exceptionreset h5,.sf-exceptionreset h6,.sf-exceptionreset pre,.sf-exceptionreset code,.sf-exceptionreset form,.sf-exceptionreset fieldset,.sf-exceptionreset legend,.sf-exceptionreset input,.sf-exceptionreset textarea,.sf-exceptionreset p,.sf-exceptionreset blockquote,.sf-exceptionreset th,.sf-exceptionreset td{margin:0;padding:0;}.sf-exceptionreset table{border-collapse:collapse;border-spacing:0;}.sf-exceptionreset fieldset,.sf-exceptionreset img{border:0;}.sf-exceptionreset address,.sf-exceptionreset caption,.sf-exceptionreset cite,.sf-exceptionreset code,.sf-exceptionreset dfn,.sf-exceptionreset em,.sf-exceptionreset strong,.sf-exceptionreset th,.sf-exceptionreset var{font-style:normal;font-weight:normal;}.sf-exceptionreset li{list-style:none;}.sf-exceptionreset caption,.sf-exceptionreset th{text-align:left;}.sf-exceptionreset h1,.sf-exceptionreset h2,.sf-exceptionreset h3,.sf-exceptionreset h4,.sf-exceptionreset h5,.sf-exceptionreset h6{font-size:100%;font-weight:normal;}.sf-exceptionreset q:before,.sf-exceptionreset q:after{content:'';}.sf-exceptionreset abbr,.sf-exceptionreset acronym{border:0;font-variant:normal;}.sf-exceptionreset sup{vertical-align:text-top;}.sf-exceptionreset sub{vertical-align:text-bottom;}.sf-exceptionreset input,.sf-exceptionreset textarea,.sf-exceptionreset select{font-family:inherit;font-size:inherit;font-weight:inherit;}.sf-exceptionreset input,.sf-exceptionreset textarea,.sf-exceptionreset select{*font-size:100%;}.sf-exceptionreset legend{color:#000;}
-
-.sf-exceptionreset html,
-.sf-exceptionreset body {
- width: 100%;
- min-height: 100%;
- _height: 100%;
- margin: 0;
- padding: 0;
-}
-.sf-exceptionreset body {
- font: 1em "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
- text-align: left;
- background-color: #efefef;
-}
-
-.sf-exceptionreset abbr {
- border-bottom: 1px dotted #000;
- cursor: help;
-}
-
-.sf-exceptionreset p {
- font-size: 14px;
- line-height: 20px;
- color: #868686;
- padding-bottom: 20px;
-}
-
-.sf-exceptionreset strong {
- color: #313131;
- font-weight: bold;
-}
-
-.sf-exceptionreset a {
- color: #6c6159;
-}
-.sf-exceptionreset a img {
- border: none;
-}
-.sf-exceptionreset a:hover {
- text-decoration: underline;
-}
-
-.sf-exceptionreset em {
- font-style: italic;
-}
-
-.sf-exceptionreset h2,
-.sf-exceptionreset h3 {
- font-weight: bold;
-}
-.sf-exceptionreset h1 {
- font-family: Georgia, "Times New Roman", Times, serif;
- font-size: 20px;
- color: #313131;
-}
-
-.sf-exceptionreset li {
- padding-bottom: 10px;
-}
-
-.sf-exceptionreset .traces {
- padding-bottom: 14px;
-}
-.sf-exceptionreset .traces li {
- font-size: 12px;
- color: #868686;
- padding: 5px 4px;
- list-style-type: decimal;
- margin-left: 20px;
-}
-.sf-exceptionreset #logs .traces li.error {
- font-style: normal;
- color: #AA3333;
- background: #f9ecec;
-}
-/* fix for Opera not liking empty <li> */
-.sf-exceptionreset .traces li:after {
- content: "\00A0";
-}
-
-.sf-exceptionreset .trace {
- border: 1px solid #D3D3D3;
- padding: 10px;
- overflow: auto;
- margin: 10px 0 20px;
-}
-
-.sf-exceptionreset .block,
-.sf-exceptionreset .block_exception {
- -moz-border-radius: 16px;
- -webkit-border-radius: 16px;
- border-radius: 16px;
- margin-bottom: 20px;
-}
-.sf-exceptionreset .block {
- background-color: #FFFFFF;
- border: 1px solid #dfdfdf;
- padding: 40px 50px;
-}
-.sf-exceptionreset .block_exception {
- background-color: #f6f6f6;
- border: 1px solid #dfdfdf;
- padding: 30px 28px;
-}
-.sf-exceptionreset .block_exception div {
- color: #313131;
- font-size: 10px;
-}
-
-.sf-exceptionreset .block_exception_detected .illustration_exception,
-.sf-exceptionreset .block_exception_detected .text_exception {
- float: left;
-}
-.sf-exceptionreset .block_exception_detected .illustration_exception {
- width: 152px;
-}
-.sf-exceptionreset .block_exception_detected .text_exception {
- width: 670px;
- padding: 30px 44px 24px 46px;
- position: relative;
-}
-
-.sf-exceptionreset .text_exception .open_quote,
-.sf-exceptionreset .text_exception .close_quote {
- position: absolute;
-}
-.sf-exceptionreset .open_quote {
- top: 0;
- left: 0;
-}
-.sf-exceptionreset .close_quote {
- bottom: 0;
- right: 50px;
-}
-
-.sf-exceptionreset .block_exception p {
- font-family: Arial, Helvetica, sans-serif;
-}
-.sf-exceptionreset .block_exception p a,
-.sf-exceptionreset .block_exception p a:hover {
- color: #565656;
-}
-
-.sf-exceptionreset h2 {
- font-size: 16px;
- font-family: Arial, Helvetica, sans-serif;
- padding-bottom: 16px;
-}
-
-.sf-exceptionreset li a {
- background: none;
- color: #868686;
- text-decoration: none;
-}
-
-.sf-exceptionreset li a:hover {
- background: none;
- color: #313131;
- text-decoration: underline;
-}
-
-.sf-exceptionreset .logs h2 {
- float: left;
- width: 654px;
-}
-
-.sf-exceptionreset .error_count {
- float: right;
- width: 170px;
- text-align: right;
-}
-
-.sf-exceptionreset .error_count span {
- display: inline-block;
- background-color: #aacd4e;
- -moz-border-radius: 6px;
- -webkit-border-radius: 6px;
- border-radius: 6px;
- padding: 4px;
- color: white;
- margin-right: 2px;
- font-size: 11px;
- font-weight: bold;
-}
-
-.sf-exceptionreset .toggle {
- vertical-align: middle;
-}
-
-.sf-exceptionreset .linked ul,
-.sf-exceptionreset .linked li {
- display: inline;
-}
-
-.sf-exceptionreset #output_content {
- color: #000;
- font-size: 12px;
-}
-
-.sf-exceptionreset ol {
- padding: 10px 0;
-}
-.sf-exceptionreset ol li {
- list-style: decimal;
- margin-left: 20px;
- padding: 2px;
- padding-bottom: 20px;
-}
-.sf-exceptionreset ol ol li {
- list-style-position: inside;
- margin-left: 0;
- white-space: nowrap;
- font-size: 12px;
- padding-bottom: 0;
-}
-.sf-exceptionreset li .selected {
- background-color: #ffd;
-}
+++ /dev/null
-html {
- background: #eee;
-}
-
-body {
- font: 11px Verdana, Arial, sans-serif;
- color: #333;
-}
-
-.sf-exceptionreset, .sf-exceptionreset .block, .sf-exceptionreset #message {
- margin: auto;
-}
-
-img {
- border: 0;
-}
-
-.clear {
- clear: both;
- height: 0;
- font-size: 0;
- line-height: 0;
-}
-
-.clear_fix:after {
- content: "\0020";
- display: block;
- height: 0;
- clear: both;
- visibility: hidden;
-}
-.clear_fix {
- display: inline-block;
-}
-* html .clear_fix {
- height: 1%;
-}
-.clear_fix {
- display: block;
-}
-
-.header {
- padding: 30px 30px 20px 30px;
-}
-
-.header_logo {
- float: left;
-}
-
-.search {
- float: right;
- padding-top: 20px;
-}
-
-.search label {
- line-height: 28px;
- vertical-align: middle;
-}
-
-.search input {
- width: 188px;
- margin-right: 10px;
- font-size: 12px;
- border: 1px solid #dadada;
- background: #FFFFFF url(../images/input_bg.gif) repeat-x left top;
- padding: 5px 6px;
- color: #565656;
-}
-
-.search input[type="search"] {
- -webkit-appearance: textfield;
-}
-
-.search button {
- -webkit-appearance: button-bevel;
- float: none;
- padding: 0;
- margin: 0;
- overflow: visible;
- width: auto;
- text-decoration: none;
- cursor: pointer;
- white-space: nowrap;
- display: inline-block;
- text-align: center;
- vertical-align: middle;
- border: 0;
- background: none;
-}
-
-.search button:-moz-focus-inner {
- padding: 0;
- border: none;
-}
-
-.search button:hover {
- text-decoration: none;
-}
-
-.search button span span,
-.search button span span span {
- position: static;
-}
-
-.search button span {
- position: relative;
- text-decoration: none;
- display: block;
- height: 28px;
- float: left;
- padding: 0 0 0 8px;
- background: transparent url(../images/border_l.png) no-repeat top left;
-}
-
-.search button span span {
- padding: 0 8px 0 0;
- background: transparent url(../images/border_r.png) right top no-repeat;
-}
-
-.search button span span span {
- padding: 0 7px;
- font: bold 11px Arial, Helvetica, sans-serif;
- color: #6b6b6b;
- line-height: 28px;
- background: transparent url(../images/btn_bg.png) repeat-x top left;
-}
-
-#content {
- width: 970px;
- margin: 0 auto;
-}
+++ /dev/null
-/*
-Copyright (c) 2010, Yahoo! Inc. All rights reserved.
-Code licensed under the BSD License:
-http://developer.yahoo.com/yui/license.html
-version: 2.8.2r1
-
-Reset
-*/
-
-html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var,optgroup{font-style:inherit;font-weight:inherit;}del,ins{text-decoration:none;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:baseline;}sub{vertical-align:baseline;}legend{color:#000;}input,button,textarea,select,optgroup,option{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;}input,button,textarea,select{*font-size:100%;}
-
-html, body
-{
- background-color: #EFEFEF;
-}
-
-body
-{
- font-size: 14px;
- font-family: "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
- color: #313131;
-}
-
-a
-{
- color: #08C;
- text-decoration: none;
-}
-
-a:hover
-{
- text-decoration: underline;
-}
-
-strong
-{
- font-weight: bold;
-}
-
-em
-{
- font-style: italic;
-}
-
-h1, h2, h3
-{
- font-family: Georgia, "Times New Roman", Times, serif;
- color: #404040;
-}
-
-h1
-{
- font-size: 45px;
- padding-bottom: 30px;
-}
-
-h2
-{
- font-weight: bold;
- color: #FFFFFF;
- /* Font is duplicated of body (sans-serif) */
- font-family: "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
-
- margin-bottom: 10px;
- background-color: #aacd4e;
- padding: 2px 4px;
- display: inline-block;
- text-transform: uppercase;
-
-}
-
-h2.configure-error
-{
- background-color: #CC514F;
-}
-
-p
-{
- line-height: 20px;
- padding-bottom: 20px;
-}
-
-ul a
-{
- background: url(../images/blue-arrow.png) no-repeat right 6px;
- padding-right: 10px;
-}
-
-ul, ol
-{
- padding-left: 20px;
-}
-
-li
-{
- padding-bottom: 18px;
-}
-
-ol li
-{
- list-style-type: decimal;
-}
-
-ul li
-{
- list-style-type: none;
-}
-
-#symfony-header
-{
- position: relative;
- padding: 30px 30px 20px 30px;
-}
-
-#symfony-wrapper
-{
- width: 970px;
- margin: 0 auto;
-}
-
-#symfony-content
-{
- background-color: white;
- border: 1px solid #DFDFDF;
- padding: 50px;
- -moz-border-radius: 16px;
- -webkit-border-radius: 16px;
- border-radius: 16px;
- margin-bottom: 20px;
-}
-
-#symfony-header
-{
- position: relative;
- padding: 30px 30px 20px 30px;
-}
-
-#symfony-wrapper
-{
- width: 970px;
- margin: 0 auto;
-}
-
-#symfony-content
-{
- background-color: white;
- border: 1px solid #DFDFDF;
- padding: 50px;
- -moz-border-radius: 16px;
- -webkit-border-radius: 16px;
- border-radius: 16px;
- margin-bottom: 20px;
-}
-html, body
-{
- background-color: #EFEFEF;
-}
-
-body
-{
- font-size: 14px;
- font-family: "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
- color: #313131;
-}
-
-a
-{
- color: #08C;
- text-decoration: none;
-}
-
-a:hover
-{
- text-decoration: underline;
-}
-
-strong
-{
- font-weight: bold;
-}
-
-#symfony-header
-{
- position: relative;
- padding: 30px 30px 20px 30px;
-}
-
-#symfony-wrapper
-{
- width: 970px;
- margin: 0 auto;
-}
-
-#symfony-content
-{
- background-color: white;
- border: 1px solid #DFDFDF;
- padding: 50px;
- -moz-border-radius: 16px;
- -webkit-border-radius: 16px;
- border-radius: 16px;
- margin-bottom: 20px;
-}
-html, body
-{
- background-color: #EFEFEF;
-}
-
-body
-{
- font-size: 14px;
- font-family: "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
- color: #313131;
-}
-
-a
-{
- color: #08C;
- text-decoration: none;
-}
-
-a:hover
-{
- text-decoration: underline;
-}
-
-strong
-{
- font-weight: bold;
-}
-
-#symfony-header
-{
- position: relative;
- padding: 30px 30px 20px 30px;
-}
-
-#symfony-wrapper
-{
- width: 970px;
- margin: 0 auto;
-}
-
-#symfony-content
-{
- background-color: white;
- border: 1px solid #DFDFDF;
- padding: 50px;
- -moz-border-radius: 16px;
- -webkit-border-radius: 16px;
- border-radius: 16px;
- margin-bottom: 5px;
-}
-
-#symfony-search
-{
- position: absolute;
-
- top: 50px;
- right: 30px;
-}
-
-#symfony-search-field
-{
- width: 190px;
-}
-
-#symfony-search label
-{
- display: block;
- float: left;
- width: 20px;
- height: 25px;
- background: url(../images/search.png) no-repeat left 5px;
-}
-
-#symfony-search label span
-{
- display: none;
-}
-
-input[type=text]
-{
- border: 1px solid #DADADA;
- background: white url(../images/field-background.gif) repeat-x left top;
- padding: 5px 6px;
- color: #565656;
- font-family: 'Lucida Sans Unicode', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif;
- font-size: 12px;
-}
-
-.symfony-button-grey,
-.symfony-button-green
-{
- font-size: 0.85em;
- font-weight: bold;
-
- cursor: pointer;
-
- display: inline-block;
- outline: none;
-
- text-align: center;
- text-transform: uppercase;
-
- padding: 3px 10px;
-
- text-shadow: 0 1px 1px rgba(0,0,0,.3);
-
- -webkit-border-radius: 4px;
- -moz-border-radius: 4px;
- border-radius: 4px;
-}
-
-.symfony-button-grey
-{
- color: #868686;
- font-weight: normal;
-
- padding: 5px 10px;
- border: solid 1px #d7d7d7;
- background: #ffffff;
- background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#d7d7d7));
- background: -moz-linear-gradient(top, #ffffff, #d7d7d7);
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#d7d7d7');
-}
-
-.symfony-button-green
-{
- padding: 5px 12px;
-
- color: white;
-
- border: solid 1px #a7da39;
- background: #a7da39;
- background: -webkit-gradient(linear, left top, left bottom, from(#a7da39), to(#6a9211));
- background: -moz-linear-gradient(top, #a7da39, #6a9211);
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#a7da39', endColorstr='#6a9211');
-}
-
-.symfony-block-steps span
-{
- display: inline-block;
- padding: 2px 3px;
- font-size: 11px;
- line-height: 15px;
- color: #868686;
- font-weight: bold;
- text-transform: uppercase;
-}
-
-.symfony-block-steps span.selected
-{
- background-color: #aacd4e;
- color: #FFFFFF;
-}
-
-h1
-{
- margin-top: 10px;
- font-size: 26px;
-}
-
-.symfony-form-row
-{
- padding-bottom: 40px;
-}
-
-.symfony-form-column
-{
- width: 430px;
- float: left;
-}
-
-.symfony-form-footer
-{
- padding-top: 20px;
- clear: both;
-}
-
-.symfony-form-field
-{
- height: 20px;
-}
-
-.symfony-form-row label
-{
- display: block;
- padding-bottom: 8px;
-}
-
-.symfony-form-field input[type=text],
-.symfony-form-field input[type=password],
-.symfony-form-field textarea,
-.symfony-form-field select
-{
- font-size: 13px;
- color: #565656;
- width: 200px;
-}
-
-.symfony-form-field input[type=text],
-.symfony-form-field input[type=password],
-.symfony-form-field textarea
-{
- border: 1px solid #dadada;
- background: #FFFFFF url(../images/background-textfield.gif) repeat-x left top;
- width: 194px;
- padding: 5px 6px;
-}
-
-.symfony-form-errors ul
-{
- padding: 0;
-}
-
-.symfony-form-errors li
-{
- background: url(../images/notification.gif) no-repeat left 6px;
- font-size: 11px;
- line-height: 16px;
- color: #759e1a;
- padding: 10px 25px;
-}
-
-.symfony-configuration
-{
- margin: 10px 0;
- width: 100%;
- height: 240px;
-}
-
-.version
-{
- text-align: right;
- font-size: 10px;
- margin-right: 20px;
-}
+++ /dev/null
-/*
-Copyright (c) 2010, Yahoo! Inc. All rights reserved.
-Code licensed under the BSD License:
-http://developer.yahoo.com/yui/license.html
-version: 2.8.2r1
-
-Reset
-*/
-
-html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var,optgroup{font-style:inherit;font-weight:inherit;}del,ins{text-decoration:none;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:baseline;}sub{vertical-align:baseline;}legend{color:#000;}input,button,textarea,select,optgroup,option{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;}input,button,textarea,select{*font-size:100%;}
-
-html, body
-{
- background-color: #EFEFEF;
-}
-
-body
-{
- font-size: 14px;
- font-family: "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
- color: #313131;
-}
-
-a
-{
- color: #08C;
- text-decoration: none;
-}
-
-a:hover
-{
- text-decoration: underline;
-}
-
-strong
-{
- font-weight: bold;
-}
-
-em
-{
- font-style: italic;
-}
-
-h1, h2, h3
-{
- font-family: Georgia, "Times New Roman", Times, serif;
- color: #404040;
-}
-
-h1
-{
- font-size: 45px;
- padding-bottom: 30px;
-}
-
-h2
-{
- font-weight: bold;
- color: #FFFFFF;
- /* Font is duplicated of body (sans-serif) */
- font-family: "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
-
- margin-bottom: 10px;
- background-color: #aacd4e;
- padding: 2px 4px;
- display: inline-block;
- text-transform: uppercase;
-
-}
-
-p
-{
- line-height: 20px;
- padding-bottom: 20px;
-}
-
-ul a
-{
- background: url(../images/blue-arrow.png) no-repeat right 6px;
- padding-right: 10px;
-}
-
-ul, ol
-{
- padding-left: 20px;
-}
-
-li
-{
- padding-bottom: 18px;
-}
-
-ol li
-{
- list-style-type: decimal;
-}
-
-ul li
-{
- list-style-type: none;
-}
-
-#symfony-header
-{
- position: relative;
- padding: 30px 30px 20px 30px;
-}
-
-#symfony-wrapper
-{
- width: 970px;
- margin: 0 auto;
-}
-
-#symfony-content
-{
- background-color: white;
- border: 1px solid #DFDFDF;
- padding: 50px;
- -moz-border-radius: 16px;
- -webkit-border-radius: 16px;
- border-radius: 16px;
- margin-bottom: 20px;
-}
-
-#symfony-header
-{
- position: relative;
- padding: 30px 30px 20px 30px;
-}
-
-#symfony-wrapper
-{
- width: 970px;
- margin: 0 auto;
-}
-
-#symfony-content
-{
- background-color: white;
- border: 1px solid #DFDFDF;
- padding: 50px;
- -moz-border-radius: 16px;
- -webkit-border-radius: 16px;
- border-radius: 16px;
- margin-bottom: 20px;
-}
-html, body
-{
- background-color: #EFEFEF;
-}
-
-body
-{
- font-size: 14px;
- font-family: "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
- color: #313131;
-}
-
-a
-{
- color: #08C;
- text-decoration: none;
-}
-
-a:hover
-{
- text-decoration: underline;
-}
-
-strong
-{
- font-weight: bold;
-}
-
-#symfony-header
-{
- position: relative;
- padding: 30px 30px 20px 30px;
-}
-
-#symfony-wrapper
-{
- width: 970px;
- margin: 0 auto;
-}
-
-#symfony-content
-{
- background-color: white;
- border: 1px solid #DFDFDF;
- padding: 50px;
- -moz-border-radius: 16px;
- -webkit-border-radius: 16px;
- border-radius: 16px;
- margin-bottom: 20px;
-}
-html, body
-{
- background-color: #EFEFEF;
-}
-
-body
-{
- font-size: 14px;
- font-family: "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
- color: #313131;
-}
-
-a
-{
- color: #08C;
- text-decoration: none;
-}
-
-a:hover
-{
- text-decoration: underline;
-}
-
-strong
-{
- font-weight: bold;
-}
-
-#symfony-header
-{
- position: relative;
- padding: 30px 30px 20px 30px;
-}
-
-#symfony-wrapper
-{
- width: 970px;
- margin: 0 auto;
-}
-
-#symfony-content
-{
- background-color: white;
- border: 1px solid #DFDFDF;
- padding: 50px;
- -moz-border-radius: 16px;
- -webkit-border-radius: 16px;
- border-radius: 16px;
- margin-bottom: 5px;
-}
-
-#symfony-search
-{
- position: absolute;
-
- top: 50px;
- right: 30px;
-}
-
-#symfony-search-field
-{
- width: 190px;
-}
-
-#symfony-search label
-{
- display: block;
- float: left;
- width: 20px;
- height: 25px;
- background: url(../images/search.png) no-repeat left 5px;
-}
-
-#symfony-search label span
-{
- display: none;
-}
-
-input[type=text]
-{
- border: 1px solid #DADADA;
- background: white url(../images/field-background.gif) repeat-x left top;
- padding: 5px 6px;
- color: #565656;
- font-family: 'Lucida Sans Unicode', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif;
- font-size: 12px;
-}
-
-.symfony-button-grey,
-.symfony-button-green
-{
- font-size: 0.85em;
- font-weight: bold;
-
- cursor: pointer;
-
- display: inline-block;
- outline: none;
-
- text-align: center;
- text-transform: uppercase;
-
- padding: 3px 10px;
-
- text-shadow: 0 1px 1px rgba(0,0,0,.3);
-
- -webkit-border-radius: 4px;
- -moz-border-radius: 4px;
- border-radius: 4px;
-}
-
-.symfony-button-grey
-{
- color: #868686;
- font-weight: normal;
-
- padding: 5px 10px;
- border: solid 1px #d7d7d7;
- background: #ffffff;
- background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#d7d7d7));
- background: -moz-linear-gradient(top, #ffffff, #d7d7d7);
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#d7d7d7');
-}
-
-.symfony-button-green
-{
- padding: 5px 12px;
-
- color: white;
-
- border: solid 1px #a7da39;
- background: #a7da39;
- background: -webkit-gradient(linear, left top, left bottom, from(#a7da39), to(#6a9211));
- background: -moz-linear-gradient(top, #a7da39, #6a9211);
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#a7da39', endColorstr='#6a9211');
-}
-
-#symfony-wrapper
-{
- padding-top: 50px;
-}
-
-.symfony-blocks-install
-{
- overflow:hidden;
-}
-
-.symfony-blocks-install .symfony-block-logo
-{
- float: left;
- width: 358px;
-}
-
-.symfony-blocks-install .symfony-block-content
-{
- float: left;
- width: 510px;
-}
-
-.symfony-install-continue
-{
- font-size: 0.95em;
- padding-left: 0;
-}
-
-.symfony-install-continue li
-{
- padding-bottom: 10px;
-}
-
-.version
-{
- text-align: right;
- font-size: 10px;
- margin-right: 20px;
-}
+++ /dev/null
-/*
-Copyright (c) 2008, Yahoo! Inc. All rights reserved.
-Code licensed under the BSD License:
-http://developer.yahoo.net/yui/license.txt
-version: 2.6.0
-*/
-html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var,optgroup{font-style:inherit;font-weight:inherit;}del,ins{text-decoration:none;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:baseline;}sub{vertical-align:baseline;}legend{color:#000;}input,button,textarea,select,optgroup,option{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;}input,button,textarea,select{*font-size:100%;}
-
-html, body {
- background-color: #efefef;
-}
-body {
- font: 1em "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
- text-align: left;
-}
-
-p {
- font-size: 14px;
- line-height: 20px;
- color: #313131;
- padding-bottom: 20px
-}
-
-strong {
- color: #313131;
- font-weight: bold;
-}
-em {
- font-style: italic;
-}
-
-a {
- color: #6c6159;
-}
-a img {
- border: none;
-}
-a:hover {
- text-decoration: underline;
-}
-
-button::-moz-focus-inner {
- padding: 0;
- border: none;
-}
-button {
- overflow: visible;
- width: auto;
- background-color: transparent;
- font-weight: bold;
-}
-
-caption {
- margin-bottom: 7px;
-}
-table, tr, th, td {
- border-collapse: collapse;
- border: 1px solid #d0dbb3;
-}
-table {
- width: 100%;
- margin: 10px 0 30px;
-}
-table th {
- font-weight: bold;
- background-color: #f1f7e2;
-}
-table th, table td {
- font-size: 12px;
- padding: 8px 10px;
-}
-
-fieldset {
- border: none;
-}
-
-abbr {
- border-bottom: 1px dotted #000;
- cursor: help;
-}
-
-.clear {
- clear: both;
- height: 0;
- font-size: 0;
- line-height: 0;
-}
-.clear_fix:after
-{
- content: "\0020";
- display: block;
- height: 0;
- clear: both;
- visibility: hidden;
-}
-* html .clear_fix
-{
- height: 1%;
-}
-.clear_fix
-{
- display: block;
-}
-
-#content {
- padding: 0 50px;
- margin: 0 auto;
- font-family: Arial, Helvetica, sans-serif;
- min-width: 970px;
-}
-
-#header {
- padding: 30px 30px 20px;
-}
-
-#header h1 {
- float: left;
-}
-
-.search {
- float: right;
-}
-
-#menu_profiler {
- border-right: 1px solid #dfdfdf;
-}
-
-#menu_profiler li {
- border-bottom: 1px solid #dfdfdf;
- position: relative;
- padding-bottom: 0;
- display: block;
- background-color: #f6f6f6;
-}
-
-#menu_profiler li a {
- color: #404040;
- display: block;
- font-size: 13px;
- text-transform: uppercase;
- text-decoration: none;
- cursor: pointer;
-}
-
-#menu_profiler li a span.label {
- display: block;
- padding: 20px 20px 16px 65px;
- min-height: 24px;
- _height: 24px;
-}
-
-#menu_profiler li a span.icon {
- display: block;
- position: absolute;
- left: 0;
- top: 12px;
- width: 60px;
- text-align: center;
-}
-
-#menu_profiler li.selected a,
-#menu_profiler li a:hover {
- background: #d1d1d1 url(../images/profiler/bg_submenu.gif) repeat-x 0 0;
-}
-
-#navigation div:first-child,
-#menu_profiler li:first-child,
-#menu_profiler li:first-child a,
-#menu_profiler li:first-child a span.label {
- -moz-border-radius: 16px 0 0 0;
- -webkit-border-radius: 16px 0 0 0;
- border-radius: 16px 0 0 0;
-}
-
-#menu_profiler li a span.count {
- padding: 0;
- position: absolute;
- right: 10px;
- top: 20px;
-}
-
-#collector_wrapper {
- float: left;
- width: 100%;
-}
-
-#collector_content {
- margin-left: 250px;
- padding: 40px 50px;
-}
-
-#navigation {
- float: left;
- width: 250px;
- margin-left: -100%;
-}
-
-#collector_content table td {
- background-color: white;
-}
-
-h1 {
- font-family: Georgia, "Times New Roman", Times, serif;
- color: #404040;
-}
-h2, h3 {
- font-weight: bold;
- margin-bottom: 20px;
-}
-
-li {
- padding-bottom: 10px;
-
-}
-
-#main, #resume {
- -moz-border-radius: 16px;
- -webkit-border-radius: 16px;
- border-radius: 16px;
- margin-bottom: 20px;
-}
-
-#menu_profiler span.count span {
- display: inline-block;
- background-color: #aacd4e;
- -moz-border-radius: 6px;
- -webkit-border-radius: 6px;
- border-radius: 6px;
- padding: 4px;
- color: white;
- margin-right: 2px;
- font-size: 11px;
-}
-
-#resume {
- background-color: #f6f6f6;
- border: 1px solid #dfdfdf;
- padding: 16px 28px;
-}
-
-#resume p {
- color: #313131;
- font-size: 12px;
-}
-
-#resume .date {
- display: block;
-}
-
-table th.value {
- width: 450px;
- background-color: #dfeeb8;
-}
-
-#content h2 {
- font-size: 24px;
- color: #313131;
- font-weight: bold;
-}
-
-#content #main {
- padding: 0;
- background-color: #FFF;
- border: 1px solid #dfdfdf;
-}
-
-#content #main p {
- color: #313131;
- font-size: 14px;
- padding-bottom: 20px;
-}
-
-.sf-toolbarreset {
- border-top: 0;
- padding: 0;
-}
-
-.sf-exceptionreset .block_exception_detected .text_exception {
- width: 520px;
-}
-
-.sf-exceptionreset .block_exception_detected .illustration_exception {
- display: none;
-}
-
-ul.alt {
- margin: 10px 0 30px;
-}
-
-ul.alt li {
- padding: 5px 7px;
- font-size: 13px;
-}
-
-ul.alt li.even {
- background: #f1f7e2;
-}
-
-ul.alt li.error {
- background-color: #f66;
- margin-bottom: 1px;
-}
-
-td.main, td.menu {
- text-align: left;
- margin: 0;
- padding: 0;
- border: 0;
- vertical-align: top;
-}
-
-.search {
- padding-top: 20px;
-}
-
-.search label {
- line-height: 28px;
- vertical-align: middle;
-}
-
-.search input {
- width: 188px;
- margin-right: 10px;
- font-size: 12px;
- border: 1px solid #dadada;
- background: #FFF url(../images/profiler/input_bg.gif) repeat-x left top;
- padding: 5px 6px;
- color: #565656;
-}
-
-.search input[type="search"] {
- -webkit-appearance: textfield;
-}
-
-.search button {
- -webkit-appearance: button-bevel;
- float: none;
- padding: 0;
- margin: 0;
- border: 0;
- text-decoration: none;
- cursor: pointer;
- white-space: nowrap;
- display: inline-block;
- text-align: center;
- vertical-align: middle;
- background: none;
-}
-
-.search button:hover {
- text-decoration: none;
-}
-
-.search button span span,
-.search button span span span {
- position: static;
-}
-
-.search button span {
- position: relative;
- text-decoration: none;
- display: block;
- height: 28px;
- float: left;
- padding: 0 0 0 8px;
- background: transparent url(../images/profiler/border_l.png) no-repeat top left;
-}
-
-.search button span span {
- padding: 0 8px 0 0;
- background: transparent url(../images/profiler/border_r.png) right top no-repeat;
-}
-
-.search button span span span {
- padding: 0 7px;
- font: bold 11px Arial, Helvetica, sans-serif;
- color: #6b6b6b;
- line-height: 28px;
- background: transparent url(../images/profiler/btn_bg.png) repeat-x top left;
-}
-
-#navigation div:first-child {
- margin: 0 0 20px;
- border-top: 0;
-}
-
-#navigation .search {
- padding-top: 15px;
- float: none;
- background: #f6f6f6;
- color: #333;
- margin: 20px 0;
- border: 1px solid #dfdfdf;
- border-left: none;
-}
-
-#navigation .search h3 {
- font-family: Arial, Helvetica, sans-serif;
- text-transform: uppercase;
- margin-left: 10px;
- font-size: 13px;
-}
-
-#navigation .search form {
- padding: 15px 0;
-}
-
-#navigation .search button {
- float: right;
- margin-right: 20px;
-}
-
-#navigation .search label {
- display: block;
- float: left;
- width: 50px;
-}
-
-#navigation .search input,
-#navigation .search select,
-#navigation .search label,
-#navigation .search a {
- font-size: 12px;
-}
-
-#navigation .search form {
- padding-left: 10px;
-}
-
-#navigation .search input {
- width: 160px;
-}
-
-#navigation .import label {
- float: none;
- display: inline;
-}
-
-#navigation .import input {
- margin: 5px 0;
- width: 210px;
-}
\ No newline at end of file
+++ /dev/null
-/*
-Copyright (c) 2010, Yahoo! Inc. All rights reserved.
-Code licensed under the BSD License:
-http://developer.yahoo.com/yui/license.html
-version: 3.1.2
-build: 56
-*/
-.sf-toolbarreset div,.sf-toolbarreset dl,.sf-toolbarreset dt,.sf-toolbarreset dd,.sf-toolbarreset ul,.sf-toolbarreset ol,.sf-toolbarreset li,.sf-toolbarreset h1,.sf-toolbarreset h2,.sf-toolbarreset h3,.sf-toolbarreset h4,.sf-toolbarreset h5,.sf-toolbarreset h6,.sf-toolbarreset pre,.sf-toolbarreset code,.sf-toolbarreset form,.sf-toolbarreset fieldset,.sf-toolbarreset legend,.sf-toolbarreset input,.sf-toolbarreset textarea,.sf-toolbarreset p,.sf-toolbarreset blockquote,.sf-toolbarreset th,.sf-toolbarreset td{margin:0;padding:0;}.sf-toolbarreset table{border-collapse:collapse;border-spacing:0;}.sf-toolbarreset fieldset,.sf-toolbarreset img{border:0;}.sf-toolbarreset address,.sf-toolbarreset caption,.sf-toolbarreset cite,.sf-toolbarreset code,.sf-toolbarreset dfn,.sf-toolbarreset em,.sf-toolbarreset strong,.sf-toolbarreset th,.sf-toolbarreset var{font-style:normal;font-weight:normal;}.sf-toolbarreset li{list-style:none;}.sf-toolbarreset caption,.sf-toolbarreset th{text-align:left;}.sf-toolbarreset h1,.sf-toolbarreset h2,.sf-toolbarreset h3,.sf-toolbarreset h4,.sf-toolbarreset h5,.sf-toolbarreset h6{font-size:100%;font-weight:normal;}.sf-toolbarreset q:before,.sf-toolbarreset q:after{content:'';}.sf-toolbarreset abbr,.sf-toolbarreset acronym{border:0;font-variant:normal;}.sf-toolbarreset sup{vertical-align:text-top;}.sf-toolbarreset sub{vertical-align:text-bottom;}.sf-toolbarreset input,.sf-toolbarreset textarea,.sf-toolbarreset select{font-family:inherit;font-size:inherit;font-weight:inherit;}.sf-toolbarreset input,.sf-toolbarreset textarea,.sf-toolbarreset select{*font-size:100%;}.sf-toolbarreset legend{color:#000;}
-
-.sf-toolbarreset {
- background: #cbcbcb;
- background-image: -moz-linear-gradient(-90deg, #e8e8e8, #cbcbcb);
- background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#e8e8e8), to(#cbcbcb));
- bottom: 0;
- left: 0;
- z-index: 6000000;
- width: 100%;
- border-top: 1px solid #bbb;
- padding: 5px 0;
- margin: 0;
- font: 11px Verdana, Arial, sans-serif;
- color: #000;
-}
-
-.sf-toolbarreset abbr {
- border-bottom: 1px dotted #000000;
- cursor: help;
-}