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,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\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;
}
}

View File

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

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\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);
}

View File

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

View File

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

View File

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

View File

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

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\AopBundle\Exception;
/**
* Base exception for the AopBundle.
*
* @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\AopBundle\Exception;
/**
* RuntimeException for the AopBundle.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class RuntimeException extends \RuntimeException implements Exception
{
}

View File

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

View File

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

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<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>

View File

@@ -0,0 +1,252 @@
========
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;
}
}
}

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/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"
}

201
vendor/jms/cg/LICENSE vendored Normal file
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.

19
vendor/jms/cg/composer.json vendored Normal file
View File

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

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 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);
}
}

View File

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

View File

@@ -0,0 +1,35 @@
<?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.'\\')) {
return $className;
}
return substr($className, $pos + NamingStrategyInterface::SEPARATOR_LENGTH + 2);
}
private final function __construct() {}
}

View File

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

View File

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

View File

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

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 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);
}

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 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() { }
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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 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;
}
}

View File

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

158
vendor/jms/cg/src/CG/Proxy/Enhancer.php vendored Normal file
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

8
vendor/jms/cg/src/CG/Version.php vendored Normal file
View File

@@ -0,0 +1,8 @@
<?php
namespace CG;
class Version
{
const VERSION = '1.0.0';
}

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"
}

18
vendor/jms/metadata/CHANGELOG.md vendored Normal file
View File

@@ -0,0 +1,18 @@
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)

201
vendor/jms/metadata/LICENSE vendored Normal file
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.

19
vendor/jms/metadata/composer.json vendored Normal file
View File

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

View File

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

View File

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

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 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;
}
}

View File

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

View File

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

View File

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

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 Metadata\Driver;
interface DriverInterface
{
function loadMetadataForClass(\ReflectionClass $class);
}

View File

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

View File

@@ -0,0 +1,8 @@
<?php
namespace Metadata\Driver;
interface FileLocatorInterface
{
function findFileForClass(\ReflectionClass $class, $extension);
}

View File

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

View File

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

View File

@@ -0,0 +1,8 @@
<?php
namespace Metadata;
interface MergeableInterface
{
function merge(MergeableInterface $object);
}

Some files were not shown because too many files have changed in this diff Show More