Vendor update && Started using DoctrineMigrations

This commit is contained in:
Polonkai Gergely
2012-07-23 17:09:03 +02:00
parent 7c36f93436
commit bf46316347
1102 changed files with 103189 additions and 7 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,64 @@
<?php
/*
* Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace JMS\AopBundle\Tests\Aop;
use JMS\AopBundle\Aop\PointcutContainer;
use JMS\AopBundle\Aop\InterceptorLoader;
class InterceptorLoaderTest extends \PHPUnit_Framework_TestCase
{
public function testLoadInterceptors()
{
$interceptor = $this->getMock('CG\Proxy\MethodInterceptorInterface');
list($loader, $container) = $this->getLoader(array(
'JMS\AopBundle\Tests\Aop\InterceptorLoaderTestClass' => array(
'foo' => array('foo'),
),
));
$container
->expects($this->once())
->method('get')
->with($this->equalTo('foo'))
->will($this->returnValue($interceptor))
;
$method = new \ReflectionMethod('JMS\AopBundle\Tests\Aop\InterceptorLoaderTestClass', 'foo');
$this->assertSame(array($interceptor), $loader->loadInterceptors($method));
// yes, twice
$this->assertSame(array($interceptor), $loader->loadInterceptors($method));
}
private function getLoader(array $interceptors = array())
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
return array(new InterceptorLoader($container, $interceptors), $container);
}
}
class InterceptorLoaderTestClass
{
public function foo()
{
}
}

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 JMS\AopBundle\Tests\Aop;
use JMS\AopBundle\Aop\RegexPointcut;
class RegexPointcutTest extends \PHPUnit_Framework_TestCase
{
public function testMatchesClass()
{
$pointcut = new RegexPointcut('');
$this->assertTrue($pointcut->matchesClass(new \ReflectionClass('stdClass')));
}
public function testMatchesMethod()
{
$pointcut = new RegexPointcut('foo$');
$method = new \ReflectionMethod('JMS\AopBundle\Tests\Aop\RegexPointcutTestClass', 'foo');
$this->assertTrue($pointcut->matchesMethod($method));
$method = new \ReflectionMethod('JMS\AopBundle\Tests\Aop\RegexPointcutTestClass', 'bar');
$this->assertFalse($pointcut->matchesMethod($method));
}
}
class RegexPointcutTestClass
{
public function foo() {}
public function bar() {}
}

View File

@@ -0,0 +1,39 @@
<?php
/*
* Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture;
use CG\Proxy\MethodInvocation;
use CG\Proxy\MethodInterceptorInterface;
class LoggingInterceptor implements MethodInterceptorInterface
{
private $log = array();
public function getLog()
{
return $this->log;
}
public function intercept(MethodInvocation $invocation)
{
$this->log[] = $invocation->reflection->name;
return $invocation->proceed();
}
}

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\Tests\DependencyInjection\Compiler\Fixture;
use JMS\AopBundle\Aop\PointcutInterface;
class LoggingPointcut implements PointcutInterface
{
public function matchesClass(\ReflectionClass $class)
{
return true;
}
public function matchesMethod(\ReflectionMethod $method)
{
return false !== strpos($method->name, 'delete');
}
}

View File

@@ -0,0 +1,32 @@
<?php
/*
* Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture;
class TestService
{
public function add()
{
return true;
}
public function delete()
{
return true;
}
}

View File

@@ -0,0 +1,96 @@
<?php
/*
* Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace JMS\AopBundle\Tests\DependencyInjection\Compiler;
use JMS\AopBundle\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Compiler\ResolveParameterPlaceHoldersPass;
use JMS\AopBundle\DependencyInjection\JMSAopExtension;
use JMS\AopBundle\DependencyInjection\Compiler\PointcutMatchingPass;
use Symfony\Component\HttpKernel\Util\Filesystem;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class PointcutMatchingPassTest extends \PHPUnit_Framework_TestCase
{
private $cacheDir;
private $fs;
public function testProcess()
{
$container = $this->getContainer();
$container
->register('pointcut', 'JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture\LoggingPointcut')
->addTag('jms_aop.pointcut', array('interceptor' => 'interceptor'))
;
$container
->register('interceptor', 'JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture\LoggingInterceptor')
;
$container
->register('test', 'JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture\TestService')
;
$this->process($container);
$service = $container->get('test');
$this->assertInstanceOf('JMS\AopBundle\Tests\DependencyInjection\Compiler\Fixture\TestService', $service);
$this->assertTrue($service->add());
$this->assertTrue($service->delete());
$this->assertEquals(array('delete'), $container->get('interceptor')->getLog());
}
protected function setUp()
{
$this->cacheDir = sys_get_temp_dir().'/jms_aop_test';
$this->fs = new Filesystem();
if (is_dir($this->cacheDir)) {
$this->fs->remove($this->cacheDir);
}
if (false === @mkdir($this->cacheDir, 0777, true)) {
throw new RuntimeException(sprintf('Could not create cache dir "%s".', $this->cacheDir));
}
}
protected function tearDown()
{
$this->fs->remove($this->cacheDir);
}
private function getContainer()
{
$container = new ContainerBuilder();
$extension = new JMSAopExtension();
$extension->load(array(array(
'cache_dir' => $this->cacheDir,
)), $container);
return $container;
}
private function process(ContainerBuilder $container)
{
$pass = new ResolveParameterPlaceHoldersPass();
$pass->process($container);
$pass = new PointcutMatchingPass();
$pass->process($container);
}
}

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

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="./../../../../app/bootstrap.php.cache"
>
<testsuites>
<testsuite name="AopBundle Test Suite">
<directory>./Tests</directory>
</testsuite>
</testsuites>
<groups>
<exclude>
<group>performance</group>
</exclude>
</groups>
</phpunit>

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,9 @@
CG library provides a toolset for generating PHP code
=====================================================
Overview
--------
This library provides some tools that you commonly need for generating PHP code.
One of it's strength lies in the enhancement of existing classes with behaviors.

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,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="tests/bootstrap.php"
>
<testsuites>
<testsuite name="CG Test Suite">
<directory>./tests/CG/</directory>
</testsuite>
</testsuites>
<groups>
<exclude>
<group>performance</group>
</exclude>
</groups>
</phpunit>

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

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

View File

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

View File

@@ -0,0 +1,14 @@
<?php
namespace CG\Tests\Core;
use CG\Core\ClassUtils;
class ClassUtilsTest extends \PHPUnit_Framework_TestCase
{
public function testGetUserClassName()
{
$this->assertEquals('Foo', ClassUtils::getUserClass('Foo'));
$this->assertEquals('Bar', ClassUtils::getUserClass('FOO\__CG__\Bar'));
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace CG\Tests\Core;
use CG\Core\DefaultGeneratorStrategy;
use CG\Generator\PhpProperty;
use CG\Generator\PhpMethod;
use CG\Generator\PhpClass;
class DefaultGeneratorStrategyTest extends \PHPUnit_Framework_TestCase
{
public function testGenerate()
{
$strategy = new DefaultGeneratorStrategy();
$strategy->setConstantSortFunc(function($a, $b) {
return strcasecmp($a, $b);
});
$strategy->setMethodSortFunc($func = function($a, $b) {
return strcasecmp($a->getName(), $b->getName());
});
$strategy->setPropertySortFunc($func);
$this->assertEquals(
$this->getContent('GenerationTestClass_A.php'),
$strategy->generate($this->getClass())
);
}
public function testGenerateChangedConstantOrder()
{
$strategy = new DefaultGeneratorStrategy();
$strategy->setConstantSortFunc(function($a, $b) {
return -1 * strcasecmp($a, $b);
});
$strategy->setMethodSortFunc($func = function($a, $b) {
return strcasecmp($a->getName(), $b->getName());
});
$strategy->setPropertySortFunc($func);
$this->assertEquals(
$this->getContent('GenerationTestClass_B.php'),
$strategy->generate($this->getClass())
);
}
private function getContent($file)
{
return file_get_contents(__DIR__.'/generated/'.$file);
}
private function getClass()
{
$class = PhpClass::create()
->setName('GenerationTestClass')
->setMethod(PhpMethod::create('a'))
->setMethod(PhpMethod::create('b'))
->setProperty(PhpProperty::create('a'))
->setProperty(PhpProperty::create('b'))
->setConstant('a', 'foo')
->setConstant('b', 'bar')
;
return $class;
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace CG\Tests\Core;
use CG\Generator\Writer;
use CG\Core\ReflectionUtils;
class ReflectionUtilsTest extends \PHPUnit_Framework_TestCase
{
public function testGetOverridableMethods()
{
$ref = new \ReflectionClass('CG\Tests\Core\OverridableReflectionTest');
$methods = ReflectionUtils::getOverrideableMethods($ref);
$this->assertEquals(4, count($methods));
$methods = array_map(function($v) { return $v->name; }, $methods);
sort($methods);
$this->assertEquals(array('a', 'd', 'e', 'h'), $methods);
}
public function testGetUnindentedDocComment()
{
$writer = new Writer();
$comment = $writer
->writeln('/**')
->indent()
->writeln(' * Foo.')
->write(' */')
->getContent()
;
$this->assertEquals("/**\n * Foo.\n */", ReflectionUtils::getUnindentedDocComment($comment));
}
}
abstract class OverridableReflectionTest
{
public function a() { }
public final function b() { }
public static function c() { }
abstract public function d();
protected function e() { }
protected final function f() {}
protected static function g() { }
abstract protected function h();
private function i() { }
}

View File

@@ -0,0 +1,16 @@
class GenerationTestClass
{
const a = 'foo';
const b = 'bar';
public $a;
public $b;
public function a()
{
}
public function b()
{
}
}

View File

@@ -0,0 +1,16 @@
class GenerationTestClass
{
const b = 'bar';
const a = 'foo';
public $a;
public $b;
public function a()
{
}
public function b()
{
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace CG\Tests\Generator;
class AbstractPhpMemberTest extends \PHPUnit_Framework_TestCase
{
public function testSetGetStatic()
{
$member = $this->getMember();
$this->assertFalse($member->isStatic());
$this->assertSame($member, $member->setStatic(true));
$this->assertTrue($member->isStatic());
$this->assertSame($member, $member->setStatic(false));
$this->assertFalse($member->isStatic());
}
public function testSetGetVisibility()
{
$member = $this->getMember();
$this->assertEquals('public', $member->getVisibility());
$this->assertSame($member, $member->setVisibility('private'));
$this->assertEquals('private', $member->getVisibility());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testSetVisibilityThrowsExOnInvalidValue()
{
$member = $this->getMember();
$member->setVisibility('foo');
}
public function testSetGetName()
{
$member = $this->getMember();
$this->assertNull($member->getName());
$this->assertSame($member, $member->setName('foo'));
$this->assertEquals('foo', $member->getName());
}
public function testSetGetDocblock()
{
$member = $this->getMember();
$this->assertNull($member->getDocblock());
$this->assertSame($member, $member->setDocblock('foo'));
$this->assertEquals('foo', $member->getDocblock());
}
private function getMember()
{
return $this->getMockForAbstractClass('CG\Generator\AbstractPhpMember');
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace CG\Tests\Generator;
use CG\Generator\DefaultVisitor;
use CG\Generator\PhpParameter;
use CG\Generator\Writer;
use CG\Generator\PhpFunction;
class DefaultVisitorTest extends \PHPUnit_Framework_TestCase
{
public function testVisitFunction()
{
$writer = new Writer();
$function = new PhpFunction();
$function
->setName('foo')
->addParameter(PhpParameter::create('a'))
->addParameter(PhpParameter::create('b'))
->setBody(
$writer
->writeln('if ($a === $b) {')
->indent()
->writeln('throw new \InvalidArgumentException(\'$a is not allowed to be the same as $b.\');')
->outdent()
->write("}\n\n")
->write('return $b;')
->getContent()
)
;
$visitor = new DefaultVisitor();
$visitor->visitFunction($function);
$this->assertEquals($this->getContent('a_b_function.php'), $visitor->getContent());
}
private function getContent($filename)
{
if (!is_file($path = __DIR__.'/Fixture/generated/'.$filename)) {
throw new \InvalidArgumentException(sprintf('The file "%s" does not exist.', $path));
}
return file_get_contents($path);
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace CG\Tests\Generator\Fixture;
/**
* Doc Comment.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
abstract class Entity
{
/**
* @var integer
*/
private $id;
private $enabled = false;
/**
* Another doc comment.
*
* @param unknown_type $a
* @param array $b
* @param \stdClass $c
* @param unknown_type $d
*/
public final function __construct($a, array &$b, \stdClass $c, $d = 'foo')
{
}
abstract protected function foo();
private static function bar()
{
}
}

View File

@@ -0,0 +1,8 @@
function foo($a, $b)
{
if ($a === $b) {
throw new \InvalidArgumentException('$a is not allowed to be the same as $b.');
}
return $b;
}

View File

@@ -0,0 +1,215 @@
<?php
namespace CG\Tests\Generator;
use CG\Generator\PhpProperty;
use CG\Generator\PhpParameter;
use CG\Generator\PhpMethod;
use CG\Generator\PhpClass;
class PhpClassTest extends \PHPUnit_Framework_TestCase
{
public function testFromReflection()
{
$class = new PhpClass();
$class
->setName('CG\Tests\Generator\Fixture\Entity')
->setAbstract(true)
->setDocblock('/**
* Doc Comment.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/')
->setProperty(PhpProperty::create('id')
->setVisibility('private')
->setDocblock('/**
* @var integer
*/')
)
->setProperty(PhpProperty::create('enabled')
->setVisibility('private')
->setDefaultValue(false)
)
;
$method = PhpMethod::create()
->setName('__construct')
->setFinal(true)
->addParameter(new PhpParameter('a'))
->addParameter(PhpParameter::create()
->setName('b')
->setType('array')
->setPassedByReference(true)
)
->addParameter(PhpParameter::create()
->setName('c')
->setType('stdClass')
)
->addParameter(PhpParameter::create()
->setName('d')
->setDefaultValue('foo')
)->setDocblock('/**
* Another doc comment.
*
* @param unknown_type $a
* @param array $b
* @param \stdClass $c
* @param unknown_type $d
*/')
;
$class->setMethod($method);
$class->setMethod(PhpMethod::create()
->setName('foo')
->setAbstract(true)
->setVisibility('protected')
);
$class->setMethod(PhpMethod::create()
->setName('bar')
->setStatic(true)
->setVisibility('private')
);
$this->assertEquals($class, PhpClass::fromReflection(new \ReflectionClass('CG\Tests\Generator\Fixture\Entity')));
}
public function testGetSetName()
{
$class = new PhpClass();
$this->assertNull($class->getName());
$class = new PhpClass('foo');
$this->assertEquals('foo', $class->getName());
$this->assertSame($class, $class->setName('bar'));
$this->assertEquals('bar', $class->getName());
}
public function testSetGetConstants()
{
$class = new PhpClass();
$this->assertEquals(array(), $class->getConstants());
$this->assertSame($class, $class->setConstants(array('foo' => 'bar')));
$this->assertEquals(array('foo' => 'bar'), $class->getConstants());
$this->assertSame($class, $class->setConstant('bar', 'baz'));
$this->assertEquals(array('foo' => 'bar', 'bar' => 'baz'), $class->getConstants());
$this->assertSame($class, $class->removeConstant('foo'));
$this->assertEquals(array('bar' => 'baz'), $class->getConstants());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testRemoveConstantThrowsExceptionWhenConstantDoesNotExist()
{
$class = new PhpClass();
$class->removeConstant('foo');
}
public function testSetIsAbstract()
{
$class = new PhpClass();
$this->assertFalse($class->isAbstract());
$this->assertSame($class, $class->setAbstract(true));
$this->assertTrue($class->isAbstract());
$this->assertSame($class, $class->setAbstract(false));
$this->assertFalse($class->isAbstract());
}
public function testSetIsFinal()
{
$class = new PhpClass();
$this->assertFalse($class->isFinal());
$this->assertSame($class, $class->setFinal(true));
$this->assertTrue($class->isFinal());
$this->assertSame($class, $class->setFinal(false));
$this->assertFalse($class->isFinal());
}
public function testSetGetParentClassName()
{
$class = new PhpClass();
$this->assertNull($class->getParentClassName());
$this->assertSame($class, $class->setParentClassName('stdClass'));
$this->assertEquals('stdClass', $class->getParentClassName());
$this->assertSame($class, $class->setParentClassName(null));
$this->assertNull($class->getParentClassName());
}
public function testSetGetInterfaceNames()
{
$class = new PhpClass();
$this->assertEquals(array(), $class->getInterfaceNames());
$this->assertSame($class, $class->setInterfaceNames(array('foo', 'bar')));
$this->assertEquals(array('foo', 'bar'), $class->getInterfaceNames());
$this->assertSame($class, $class->addInterfaceName('stdClass'));
$this->assertEquals(array('foo', 'bar', 'stdClass'), $class->getInterfaceNames());
}
public function testSetGetUseStatements()
{
$class = new PhpClass();
$this->assertEquals(array(), $class->getUseStatements());
$this->assertSame($class, $class->setUseStatements(array('foo' => 'bar')));
$this->assertEquals(array('foo' => 'bar'), $class->getUseStatements());
$this->assertSame($class, $class->addUseStatement('Foo\Bar'));
$this->assertEquals(array('foo' => 'bar', 'Bar' => 'Foo\Bar'), $class->getUseStatements());
$this->assertSame($class, $class->addUseStatement('Foo\Bar', 'Baz'));
$this->assertEquals(array('foo' => 'bar', 'Bar' => 'Foo\Bar', 'Baz' => 'Foo\Bar'), $class->getUseStatements());
}
public function testSetGetProperties()
{
$class = new PhpClass();
$this->assertEquals(array(), $class->getProperties());
$this->assertSame($class, $class->setProperties($props = array('foo' => new PhpProperty())));
$this->assertSame($props, $class->getProperties());
$this->assertSame($class, $class->setProperty($prop = new PhpProperty('foo')));
$this->assertSame(array('foo' => $prop), $class->getProperties());
$this->assertTrue($class->hasProperty('foo'));
$this->assertSame($class, $class->removeProperty('foo'));
$this->assertEquals(array(), $class->getProperties());
}
public function testSetGetMethods()
{
$class = new PhpClass();
$this->assertEquals(array(), $class->getMethods());
$this->assertSame($class, $class->setMethods($methods = array('foo' => new PhpMethod())));
$this->assertSame($methods, $class->getMethods());
$this->assertSame($class, $class->setMethod($method = new PhpMethod('foo')));
$this->assertSame(array('foo' => $method), $class->getMethods());
$this->assertTrue($class->hasMethod('foo'));
$this->assertSame($class, $class->removeMethod('foo'));
$this->assertEquals(array(), $class->getMethods());
}
public function testSetGetDocblock()
{
$class = new PhpClass();
$this->assertNull($class->getDocblock());
$this->assertSame($class, $class->setDocblock('foo'));
$this->assertEquals('foo', $class->getDocblock());
}
public function testSetGetRequiredFiles()
{
$class = new PhpClass();
$this->assertEquals(array(), $class->getRequiredFiles());
$this->assertSame($class, $class->setRequiredFiles(array('foo')));
$this->assertEquals(array('foo'), $class->getRequiredFiles());
$this->assertSame($class, $class->addRequiredFile('bar'));
$this->assertEquals(array('foo', 'bar'), $class->getRequiredFiles());
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace CG\Tests\Generator;
use CG\Generator\PhpParameter;
use CG\Generator\PhpFunction;
class PhpFunctionTest extends \PHPUnit_Framework_TestCase
{
public function testSetGetName()
{
$func = new PhpFunction();
$this->assertNull($func->getName());
$this->assertSame($func, $func->setName('foo'));
$this->assertEquals('foo', $func->getName());
$func = new PhpFunction('foo');
$this->assertEquals('foo', $func->getName());
}
public function testSetGetNamespace()
{
$func = new PhpFunction();
$this->assertNull($func->getNamespace());
$this->assertSame($func, $func->setNamespace('foo'));
$this->assertEquals('foo', $func->getNamespace());
}
public function testSetGetBody()
{
$func = new PhpFunction();
$this->assertSame('', $func->getBody());
$this->assertSame($func, $func->setBody('foo'));
$this->assertEquals('foo', $func->getBody());
}
public function testSetGetParameters()
{
$func = new PhpFunction();
$this->assertEquals(array(), $func->getParameters());
$this->assertSame($func, $func->setParameters(array($param = new PhpParameter())));
$this->assertSame(array($param), $func->getParameters());
$this->assertSame($func, $func->addParameter($param2 = new PhpParameter()));
$this->assertSame(array($param, $param2), $func->getParameters());
$this->assertSame($func, $func->replaceParameter(1, $param3 = new PhpParameter()));
$this->assertSame(array($param, $param3), $func->getParameters());
$this->assertSame($func, $func->removeParameter(0));
$this->assertSame(array($param3), $func->getParameters());
}
public function testSetGetDocblock()
{
$func = new PhpFunction();
$this->assertNull($func->getDocblock());
$this->assertSame($func, $func->setDocblock('foo'));
$this->assertEquals('foo', $func->getDocblock());
}
public function testSetIsReferenceReturned()
{
$func = new PhpFunction();
$this->assertFalse($func->isReferenceReturned());
$this->assertSame($func, $func->setReferenceReturned(true));
$this->assertTrue($func->isReferenceReturned());
$this->assertSame($func, $func->setReferenceReturned(false));
$this->assertFalse($func->isReferenceReturned());
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace CG\Tests\Generator;
use CG\Generator\PhpParameter;
use CG\Generator\PhpMethod;
class PhpMethodTest extends \PHPUnit_Framework_TestCase
{
public function testSetIsFinal()
{
$method = new PhpMethod();
$this->assertFalse($method->isFinal());
$this->assertSame($method, $method->setFinal(true));
$this->assertTrue($method->isFinal());
$this->assertSame($method, $method->setFinal(false));
$this->assertFalse($method->isFinal());
}
public function testSetIsAbstract()
{
$method = new PhpMethod();
$this->assertFalse($method->isAbstract());
$this->assertSame($method, $method->setAbstract(true));
$this->assertTrue($method->isAbstract());
$this->assertSame($method, $method->setAbstract(false));
$this->assertFalse($method->isAbstract());
}
public function testSetGetParameters()
{
$method = new PhpMethod();
$this->assertEquals(array(), $method->getParameters());
$this->assertSame($method, $method->setParameters($params = array(new PhpParameter())));
$this->assertSame($params, $method->getParameters());
$this->assertSame($method, $method->addParameter($param = new PhpParameter()));
$params[] = $param;
$this->assertSame($params, $method->getParameters());
$this->assertSame($method, $method->removeParameter(0));
unset($params[0]);
$this->assertSame(array($param), $method->getParameters());
$this->assertSame($method, $method->addParameter($param = new PhpParameter()));
$params[] = $param;
$params = array_values($params);
$this->assertSame($params, $method->getParameters());
}
public function testSetGetBody()
{
$method = new PhpMethod();
$this->assertSame('', $method->getBody());
$this->assertSame($method, $method->setBody('foo'));
$this->assertEquals('foo', $method->getBody());
}
public function testSetIsReferenceReturned()
{
$method = new PhpMethod();
$this->assertFalse($method->isReferenceReturned());
$this->assertSame($method, $method->setReferenceReturned(true));
$this->assertTrue($method->isReferenceReturned());
$this->assertSame($method, $method->setReferenceReturned(false));
$this->assertFalse($method->isReferenceReturned());
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace CG\Tests\Generator;
use CG\Generator\PhpParameter;
class PhpParameterTest extends \PHPUnit_Framework_TestCase
{
public function testSetGetName()
{
$param = new PhpParameter();
$this->assertNull($param->getName());
$this->assertSame($param, $param->setName('foo'));
$this->assertEquals('foo', $param->getName());
}
public function testSetGetDefaultValue()
{
$param = new PhpParameter();
$this->assertNull($param->getDefaultValue());
$this->assertFalse($param->hasDefaultValue());
$this->assertSame($param, $param->setDefaultValue('foo'));
$this->assertEquals('foo', $param->getDefaultValue());
$this->assertTrue($param->hasDefaultValue());
$this->assertSame($param, $param->unsetDefaultValue());
$this->assertNull($param->getDefaultValue());
$this->assertFalse($param->hasDefaultValue());
}
public function testSetIsPassedByReference()
{
$param = new PhpParameter();
$this->assertFalse($param->isPassedByReference());
$this->assertSame($param, $param->setPassedByReference(true));
$this->assertTrue($param->isPassedByReference());
$this->assertSame($param, $param->setPassedByReference(false));
$this->assertFalse($param->isPassedByReference());
}
public function testSetGetType()
{
$param = new PhpParameter();
$this->assertNull($param->getType());
$this->assertSame($param, $param->setType('array'));
$this->assertEquals('array', $param->getType());
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace CG\Tests\Generator;
use CG\Generator\PhpProperty;
class PhpPropertyTest extends \PHPUnit_Framework_TestCase
{
public function testSetGetDefaultValue()
{
$prop = new PhpProperty();
$this->assertNull($prop->getDefaultValue());
$this->assertFalse($prop->hasDefaultValue());
$this->assertSame($prop, $prop->setDefaultValue('foo'));
$this->assertEquals('foo', $prop->getDefaultValue());
$this->assertTrue($prop->hasDefaultValue());
$this->assertSame($prop, $prop->unsetDefaultValue());
$this->assertNull($prop->getDefaultValue());
$this->assertFalse($prop->hasDefaultValue());
}
}

View File

@@ -0,0 +1,111 @@
<?php
namespace CG\Tests\Proxy;
use CG\Proxy\LazyInitializerInterface;
use CG\Proxy\InterceptionGenerator;
use CG\Proxy\LazyInitializerGenerator;
use CG\Proxy\Enhancer;
use CG\Tests\Proxy\Fixture\TraceInterceptor;
class EnhancerTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider getGenerationTests
*/
public function testGenerateClass($class, $generatedClass, array $interfaces, array $generators)
{
$enhancer = new Enhancer(new \ReflectionClass($class), $interfaces, $generators);
$enhancer->setNamingStrategy($this->getNamingStrategy($generatedClass));
$this->assertEquals($this->getContent(substr($generatedClass, strrpos($generatedClass, '\\') + 1)), $enhancer->generateClass());
}
public function getGenerationTests()
{
return array(
array('CG\Tests\Proxy\Fixture\SimpleClass', 'CG\Tests\Proxy\Fixture\SimpleClass__CG__Enhanced', array('CG\Tests\Proxy\Fixture\MarkerInterface'), array()),
array('CG\Tests\Proxy\Fixture\SimpleClass', 'CG\Tests\Proxy\Fixture\SimpleClass__CG__Sluggable', array('CG\Tests\Proxy\Fixture\SluggableInterface'), array()),
array('CG\Tests\Proxy\Fixture\Entity', 'CG\Tests\Proxy\Fixture\Entity__CG__LazyInitializing', array(), array(
new LazyInitializerGenerator(),
))
);
}
public function testInterceptionGenerator()
{
$enhancer = new Enhancer(new \ReflectionClass('CG\Tests\Proxy\Fixture\Entity'), array(), array(
$generator = new InterceptionGenerator()
));
$enhancer->setNamingStrategy($this->getNamingStrategy('CG\Tests\Proxy\Fixture\Entity__CG__Traceable_'.sha1(microtime(true))));
$generator->setPrefix('');
$traceable = $enhancer->createInstance();
$traceable->setLoader($this->getLoader(array(
$interceptor1 = new TraceInterceptor(),
$interceptor2 = new TraceInterceptor(),
)));
$this->assertEquals('foo', $traceable->getName());
$this->assertEquals('foo', $traceable->getName());
$this->assertEquals(2, count($interceptor1->getLog()));
$this->assertEquals(2, count($interceptor2->getLog()));
}
public function testLazyInitializerGenerator()
{
$enhancer = new Enhancer(new \ReflectionClass('CG\Tests\Proxy\Fixture\Entity'), array(), array(
$generator = new LazyInitializerGenerator(),
));
$generator->setPrefix('');
$entity = $enhancer->createInstance();
$entity->setLazyInitializer($initializer = new Initializer());
$this->assertEquals('foo', $entity->getName());
$this->assertSame($entity, $initializer->getLastObject());
}
private function getLoader(array $interceptors)
{
$loader = $this->getMock('CG\Proxy\InterceptorLoaderInterface');
$loader
->expects($this->any())
->method('loadInterceptors')
->will($this->returnValue($interceptors))
;
return $loader;
}
private function getContent($file)
{
return file_get_contents(__DIR__.'/Fixture/generated/'.$file.'.php.gen');
}
private function getNamingStrategy($name)
{
$namingStrategy = $this->getMock('CG\Core\NamingStrategyInterface');
$namingStrategy
->expects($this->any())
->method('getClassName')
->will($this->returnValue($name))
;
return $namingStrategy;
}
}
class Initializer implements LazyInitializerInterface
{
private $lastObject;
public function initializeObject($object)
{
$this->lastObject = $object;
}
public function getLastObject()
{
return $this->lastObject;
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace CG\Tests\Proxy\Fixture;
class Entity
{
public function getName()
{
return 'foo';
}
public final function getBaz()
{
}
protected function getFoo()
{
}
private function getBar()
{
}
}

View File

@@ -0,0 +1,3 @@
<?php
namespace CG\Tests\Proxy

View File

@@ -0,0 +1,7 @@
<?php
namespace CG\Tests\Proxy\Fixture;
interface MarkerInterface
{
}

View File

@@ -0,0 +1,7 @@
<?php
namespace CG\Tests\Proxy\Fixture;
class SimpleClass
{
}

View File

@@ -0,0 +1,8 @@
<?php
namespace CG\Tests\Proxy\Fixture;
interface SluggableInterface
{
function getSlug();
}

View File

@@ -0,0 +1,29 @@
<?php
namespace CG\Tests\Proxy\Fixture;
use CG\Proxy\MethodInvocation;
use CG\Proxy\MethodInterceptorInterface;
class TraceInterceptor implements MethodInterceptorInterface
{
private $log;
public function getLog()
{
return $this->log;
}
public function intercept(MethodInvocation $method)
{
$message = sprintf('%s::%s(', $method->reflection->class, $method->reflection->name);
$logArgs = array();
foreach ($method->arguments as $arg) {
$logArgs[] = var_export($arg, true);
}
$this->log[] = $message.implode(', ', $logArgs).')';
return $method->proceed();
}
}

View File

@@ -0,0 +1,37 @@
namespace CG\Tests\Proxy\Fixture;
/**
* CG library enhanced proxy class.
*
* This code was generated automatically by the CG library, manual changes to it
* will be lost upon next generation.
*/
class Entity__CG__LazyInitializing extends \CG\Tests\Proxy\Fixture\Entity
{
private $__CG__lazyInitializer;
private $__CG__initialized = false;
public function getName()
{
if (false === $this->__CG__initialized) {
$this->__CG__initialize();
}
return \CG\Tests\Proxy\Fixture\Entity::getName();
}
public function __CG__setLazyInitializer(\CG\Proxy\LazyInitializerInterface $initializer)
{
$this->__CG__lazyInitializer = $initializer;
}
private function __CG__initialize()
{
if (null === $this->__CG__lazyInitializer) {
throw new \RuntimeException("__CG__setLazyInitializer() must be called prior to any other public method on this object.");
}
$this->__CG__lazyInitializer->initializeObject($this);
$this->__CG__initialized = true;
}
}

View File

@@ -0,0 +1,11 @@
namespace CG\Tests\Proxy\Fixture;
/**
* CG library enhanced proxy class.
*
* This code was generated automatically by the CG library, manual changes to it
* will be lost upon next generation.
*/
class SimpleClass__CG__Enhanced extends \CG\Tests\Proxy\Fixture\SimpleClass implements \CG\Tests\Proxy\Fixture\MarkerInterface
{
}

View File

@@ -0,0 +1,14 @@
namespace CG\Tests\Proxy\Fixture;
/**
* CG library enhanced proxy class.
*
* This code was generated automatically by the CG library, manual changes to it
* will be lost upon next generation.
*/
class SimpleClass__CG__Sluggable extends \CG\Tests\Proxy\Fixture\SimpleClass implements \CG\Tests\Proxy\Fixture\SluggableInterface
{
public function getSlug()
{
}
}

View File

@@ -0,0 +1,35 @@
<?php
/*
* This file is part of the CG library.
*
* (C) 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
*
*/
spl_autoload_register(function($class)
{
if (0 === strpos($class, 'CG\Tests\\')) {
$path = __DIR__.'/../tests/'.strtr($class, '\\', '/').'.php';
if (file_exists($path) && is_readable($path)) {
require_once $path;
return true;
}
} else if (0 === strpos($class, 'CG\\')) {
$path = __DIR__.'/../src/'.($class = strtr($class, '\\', '/')).'.php';
if (file_exists($path) && is_readable($path)) {
require_once $path;
return true;
}
} else if (0 === strpos($class, 'Zend\\')) {
$path = __DIR__.'/../../zend-framework2/library/'.($class = strtr($class, '\\', '/')).'.php';
if (file_exists($path) && is_readable($path)) {
require_once $path;
return true;
}
}
});

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

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