Initial commit with Symfony 2.1+Vendors

Signed-off-by: Gergely POLONKAI (W00d5t0ck) <polesz@w00d5t0ck.info>
This commit is contained in:
Polonkai Gergely
2012-07-01 09:52:20 +02:00
commit 082a0130c2
5381 changed files with 416709 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
<?php
namespace JMS\DiExtraBundle\Annotation;
/**
* @Annotation
* @Target("METHOD")
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
final class AfterSetup
{
}

View File

@@ -0,0 +1,74 @@
<?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'];
}
}
}

View File

@@ -0,0 +1,37 @@
<?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'];
}
}
}

View File

@@ -0,0 +1,27 @@
<?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
{
}

View File

@@ -0,0 +1,57 @@
<?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;
}
}
}
}

View File

@@ -0,0 +1,27 @@
<?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
{
}

View File

@@ -0,0 +1,62 @@
<?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'];
}
}
}

View File

@@ -0,0 +1,54 @@
<?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'];
}
}
}

View File

@@ -0,0 +1,87 @@
<?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'];
}
}
}

View File

@@ -0,0 +1,60 @@
<?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'];
}
}
}

View File

@@ -0,0 +1,51 @@
<?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'];
}
}

View File

@@ -0,0 +1,78 @@
<?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);
}
}

View File

@@ -0,0 +1,52 @@
<?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);
}
}

View File

@@ -0,0 +1,120 @@
<?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];
}
}

View File

@@ -0,0 +1,55 @@
<?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%');
}
}
}
}

View File

@@ -0,0 +1,81 @@
<?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);
}
}

View File

@@ -0,0 +1,69 @@
<?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;
}
}

View File

@@ -0,0 +1,84 @@
<?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);
}
}

View File

@@ -0,0 +1,24 @@
<?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();
}

View File

@@ -0,0 +1,58 @@
<?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);
}
}
}
}

View File

@@ -0,0 +1,50 @@
<?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);
}
}

View File

@@ -0,0 +1,28 @@
<?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
{
}

View File

@@ -0,0 +1,28 @@
<?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
{
}

View File

@@ -0,0 +1,29 @@
<?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);
}
}

View File

@@ -0,0 +1,28 @@
<?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
{
}

View File

@@ -0,0 +1,201 @@
<?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;
}
}
}

View File

@@ -0,0 +1,192 @@
<?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)));
}
}

View File

@@ -0,0 +1,119 @@
<?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)));
}
}

View File

@@ -0,0 +1,79 @@
<?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;
}
}
}

View File

@@ -0,0 +1,179 @@
<?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')));
}
}

View File

@@ -0,0 +1,50 @@
<?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);
}
}

View File

@@ -0,0 +1,74 @@
<?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);
}
}

View File

@@ -0,0 +1,220 @@
<?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, '\\', '.'));
}
}

View File

@@ -0,0 +1,85 @@
<?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;
}
}

View File

@@ -0,0 +1,8 @@
For documentation, see:
Resources/doc
For license, see:
Resources/meta/LICENSE

View File

@@ -0,0 +1,50 @@
<?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>

View File

@@ -0,0 +1,290 @@
========
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.

View File

@@ -0,0 +1,201 @@
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.

View File

@@ -0,0 +1,21 @@
{
"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"
}