.gitignore 0000666 00000000043 13164775705 0006554 0 ustar 00 composer.lock
phpunit.xml
vendor/
.travis.yml 0000666 00000000422 13164775705 0006676 0 ustar 00 language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
- hhvm
before_script:
- curl -s http://getcomposer.org/installer | php
- php composer.phar install
script: phpunit --coverage-clover clover
after_success:
- curl -sL https://bit.ly/artifact-uploader | php
LICENSE 0000666 00000026134 13164775705 0005602 0 ustar 00 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. README.rst 0000666 00000000443 13164775705 0006257 0 ustar 00 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.
composer.json 0000666 00000001063 13164775705 0007311 0 ustar 00 {
"name": "jms/cg",
"description": "Toolset for generating PHP code",
"keywords": ["code generation"],
"type": "library",
"license": "Apache2",
"authors": [
{
"name": "Johannes M. Schmitt",
"email": "schmittjoh@gmail.com"
}
],
"require": {
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": ">=4.5"
},
"autoload": {
"psr-0": { "CG\\": "src/" }
},
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
}
}
phpunit.xml.dist 0000666 00000001233 13164775705 0007741 0 ustar 00
./tests/CG/
performance
src/CG/Core/AbstractClassGenerator.php 0000666 00000003374 13164775705 0013657 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
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;
}
/**
* @return string
*/
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);
}
}
src/CG/Core/ClassGeneratorInterface.php 0000666 00000001605 13164775705 0014007 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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;
/**
* Interface for class generators.
*
* @author Johannes M. Schmitt
*/
interface ClassGeneratorInterface
{
/**
* Generates the PHP class.
*
* @return string
*/
public function generateClass();
} src/CG/Core/ClassUtils.php 0000666 00000002052 13164775705 0011335 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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 ClassUtils
{
/**
* @param string $className
*/
public static function getUserClass($className)
{
if (false === $pos = strrpos($className, '\\'.NamingStrategyInterface::SEPARATOR.'\\')) {
return $className;
}
return substr($className, $pos + NamingStrategyInterface::SEPARATOR_LENGTH + 2);
}
final private function __construct() {}
}
src/CG/Core/DefaultGeneratorStrategy.php 0000666 00000003542 13164775705 0014232 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
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();
}
}
src/CG/Core/DefaultNamingStrategy.php 0000666 00000002212 13164775705 0013506 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
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;
}
} src/CG/Core/GeneratorStrategyInterface.php 0000666 00000001710 13164775705 0014541 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
interface GeneratorStrategyInterface
{
public function generate(PhpClass $class);
}
src/CG/Core/NamingStrategyInterface.php 0000666 00000003245 13164775705 0014031 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
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
*/
public function getClassName(\ReflectionClass $class);
} src/CG/Core/ReflectionUtils.php 0000666 00000003243 13164775705 0012365 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
{
/**
* @param boolean $publicOnly
*/
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(); }
);
}
/**
* @param string $docComment
*/
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;
}
final private function __construct() { }
}
src/CG/Generator/AbstractBuilder.php 0000666 00000002121 13164775705 0013354 0 ustar 00 attributes[$key] = $value;
return $this;
}
public function removeAttribute($key)
{
unset($this->attributes[$key]);
}
public function getAttribute($key)
{
if ( ! isset($this->attributes[$key])) {
throw new \InvalidArgumentException(sprintf('There is no attribute named "%s".', $key));
}
return $this->attributes[$key];
}
/**
* @param string $key
*/
public function getAttributeOrElse($key, $default)
{
if ( ! isset($this->attributes[$key])) {
return $default;
}
return $this->attributes[$key];
}
public function hasAttribute($key)
{
return isset($this->attributes[$key]);
}
public function setAttributes(array $attrs)
{
$this->attributes = $attrs;
return $this;
}
public function getAttributes()
{
return $this->attributes;
}
} src/CG/Generator/AbstractPhpMember.php 0000666 00000004510 13164775705 0013651 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
abstract class AbstractPhpMember extends AbstractBuilder
{
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);
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @param string $visibility
*/
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;
}
/**
* @param boolean $bool
*/
public function setStatic($bool)
{
$this->static = (Boolean) $bool;
return $this;
}
/**
* @param string|null $doc
*/
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;
}
}
src/CG/Generator/BuiltinType.php 0000666 00000000542 13164775705 0012557 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
class DefaultNavigator
{
private $constantSortFunc;
private $propertySortFunc;
private $methodSortFunc;
/**
* Sets a custom constant sorting function.
*
* @param null|\Closure $func
*/
public function setConstantSortFunc(\Closure $func = null)
{
$this->constantSortFunc = $func;
}
/**
* Sets a custom property sorting function.
*
* @param null|\Closure $func
*/
public function setPropertySortFunc(\Closure $func = null)
{
$this->propertySortFunc = $func;
}
/**
* Sets a custom method sorting function.
*
* @param null|\Closure $func
*/
public function setMethodSortFunc(\Closure $func = null)
{
$this->methodSortFunc = $func;
}
public function accept(DefaultVisitorInterface $visitor, PhpClass $class)
{
$visitor->startVisitingClass($class);
$constants = $class->getConstants(true);
if (!empty($constants)) {
uksort($constants, $this->getConstantSortFunc());
$visitor->startVisitingClassConstants();
foreach ($constants as $constant) {
$visitor->visitClassConstant($constant);
}
$visitor->endVisitingClassConstants();
}
$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;
}
}
src/CG/Generator/DefaultVisitor.php 0000666 00000020425 13164775705 0013255 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
class DefaultVisitor implements DefaultVisitorInterface
{
protected $writer;
private $isInterface;
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) {
if ($file instanceof RelativePath) {
$this->writer->writeln('require_once __DIR__ . '.var_export('/'.$file->getRelativePath(), true).';');
continue;
}
$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->writeln($docblock);
}
if ($class->isAbstract()) {
$this->writer->write('abstract ');
}
if ($class->isFinal()) {
$this->writer->write('final ');
}
// TODO: Interfaces should be modeled as separate classes.
$this->isInterface = $class->getAttributeOrElse('interface', false);
$this->writer->write($this->isInterface ? 'interface ' : 'class ');
$this->writer->write($class->getShortName());
if ( ! $this->isInterface) {
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($this->isInterface ? ' extends ' : ' implements ');
$this->writer->write(implode(', ', $interfaceNames));
}
$this->writer
->write("\n{\n")
->indent()
;
}
public function startVisitingClassConstants()
{
}
public function visitClassConstant(PhpConstant $constant)
{
$this->writer->writeln('const '.$constant->getName().' = '.var_export($constant->getValue(), true).';');
}
public function endVisitingClassConstants()
{
$this->writer->write("\n");
}
public function startVisitingProperties()
{
}
public function visitProperty(PhpProperty $property)
{
if ($docblock = $property->getDocblock()) {
$this->writer->writeln($docblock)->rtrim();
}
$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 ');
if ($method->isReferenceReturned()) {
$this->writer->write('& ');
}
$this->writer->write($method->getName().'(');
$this->writeParameters($method->getParameters());
$this->writer->write(")");
if ($method->hasReturnType()) {
$type = $method->getReturnType();
$this->writer->write(': ');
if (!$method->hasBuiltInReturnType() && '\\' !== $type[0]) {
$this->writer->write('\\');
}
$this->writer->write($type);
}
if ($method->isAbstract() || $this->isInterface) {
$this->writer->write(";\n\n");
return;
}
$this->writer
->writeln("\n{")
->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");
}
if ($docblock = $function->getDocblock()) {
$this->writer->writeln($docblock)->rtrim();
}
$this->writer->write("function {$function->getName()}(");
$this->writeParameters($function->getParameters());
$this->writer->write(')');
if ($function->hasReturnType()) {
$type = $function->getReturnType();
$this->writer->write(': ');
if (!$function->hasBuiltinReturnType() && '\\' !== $type[0]) {
$this->writer->write('\\');
}
$this->writer->write($type);
}
$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 ($parameter->hasType()) {
$type = $parameter->getType();
if (!$parameter->hasBuiltinType() && '\\' !== $type[0]) {
$this->writer->write('\\');
}
$this->writer->write($type . ' ');
}
if ($parameter->isPassedByReference()) {
$this->writer->write('&');
}
$this->writer->write('$'.$parameter->getName());
if ($parameter->hasDefaultValue()) {
$this->writer->write(' = ');
$defaultValue = $parameter->getDefaultValue();
if (is_array($defaultValue) && empty($defaultValue)) {
$this->writer->write('array()');
} else {
$this->writer->write(var_export($defaultValue, true));
}
}
}
}
}
src/CG/Generator/DefaultVisitorInterface.php 0000666 00000004026 13164775705 0015075 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
interface DefaultVisitorInterface
{
/**
* Resets the visitors internal state to allow re-using the same instance.
*
* @return void
*/
public function reset();
/**
* @return void
*/
public function startVisitingClass(PhpClass $class);
/**
* @return void
*/
public function startVisitingClassConstants();
/**
* @param PhpConstant $constant
* @return void
*/
public function visitClassConstant(PhpConstant $constant);
/**
* @return void
*/
public function endVisitingClassConstants();
/**
* @return void
*/
public function startVisitingProperties();
/**
* @return void
*/
public function visitProperty(PhpProperty $property);
/**
* @return void
*/
public function endVisitingProperties();
/**
* @return void
*/
public function startVisitingMethods();
/**
* @return void
*/
public function visitMethod(PhpMethod $method);
/**
* @return void
*/
public function endVisitingMethods();
/**
* @return void
*/
public function endVisitingClass(PhpClass $class);
/**
* @return void
*/
public function visitFunction(PhpFunction $function);
}
src/CG/Generator/GeneratorUtils.php 0000666 00000002222 13164775705 0013253 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
abstract class GeneratorUtils
{
final private 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).')';
}
}
src/CG/Generator/PhpClass.php 0000666 00000026006 13164775705 0012027 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
class PhpClass extends AbstractBuilder
{
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;
}
/**
* @return PhpMethod
*/
protected static function createMethod(\ReflectionMethod $method)
{
return PhpMethod::fromReflection($method);
}
/**
* @return PhpProperty
*/
protected static function createProperty(\ReflectionProperty $property)
{
return PhpProperty::fromReflection($property);
}
public function __construct($name = null)
{
$this->name = $name;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @param string|null $name
*/
public function setParentClassName($name)
{
$this->parentClassName = $name;
return $this;
}
public function setInterfaceNames(array $names)
{
$this->interfaceNames = $names;
return $this;
}
/**
* @param string $name
*/
public function addInterfaceName($name)
{
$this->interfaceNames[] = $name;
return $this;
}
public function setRequiredFiles(array $files)
{
$this->requiredFiles = $files;
return $this;
}
/**
* @param string $file
*/
public function addRequiredFile($file)
{
$this->requiredFiles[] = $file;
return $this;
}
public function setUseStatements(array $useStatements)
{
foreach ($useStatements as $alias => $namespace) {
if (!is_string($alias)) {
$alias = null;
}
$this->addUseStatement($namespace, $alias);
}
return $this;
}
/**
* @param string $namespace
* @param string|null $alias
*/
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)
{
$normalizedConstants = array();
foreach ($constants as $name => $value) {
if ( ! $value instanceof PhpConstant) {
$constValue = $value;
$value = new PhpConstant($name);
$value->setValue($constValue);
}
$normalizedConstants[$name] = $value;
}
$this->constants = $normalizedConstants;
return $this;
}
/**
* @param string|PhpConstant $name
* @param string $value
*/
public function setConstant($nameOrConstant, $value = null)
{
if ($nameOrConstant instanceof PhpConstant) {
if (null !== $value) {
throw new \InvalidArgumentException('If a PhpConstant object is passed, $value must be null.');
}
$name = $nameOrConstant->getName();
$constant = $nameOrConstant;
} else {
$name = $nameOrConstant;
$constant = new PhpConstant($nameOrConstant);
$constant->setValue($value);
}
$this->constants[$name] = $constant;
return $this;
}
/**
* @param string $name
*
* @return boolean
*/
public function hasConstant($name)
{
return array_key_exists($name, $this->constants);
}
/**
* Returns a constant.
*
* @param string $name
*
* @return PhpConstant
*/
public function getConstant($name)
{
if ( ! isset($this->constants[$name])) {
throw new \InvalidArgumentException(sprintf('The constant "%s" does not exist.'));
}
return $this->constants[$name];
}
/**
* @param string $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;
}
/**
* @param string $property
*/
public function hasProperty($property)
{
if ($property instanceof PhpProperty) {
$property = $property->getName();
}
return isset($this->properties[$property]);
}
/**
* @param string $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 getMethod($method)
{
if ( ! isset($this->methods[$method])) {
throw new \InvalidArgumentException(sprintf('The method "%s" does not exist.', $method));
}
return $this->methods[$method];
}
/**
* @param string|PhpMethod $method
*/
public function hasMethod($method)
{
if ($method instanceof PhpMethod) {
$method = $method->getName();
}
return isset($this->methods[$method]);
}
/**
* @param string|PhpMethod $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;
}
/**
* @param boolean $bool
*/
public function setAbstract($bool)
{
$this->abstract = (Boolean) $bool;
return $this;
}
/**
* @param boolean $bool
*/
public function setFinal($bool)
{
$this->final = (Boolean) $bool;
return $this;
}
/**
* @param string $block
*/
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($asObjects = false)
{
if ($asObjects) {
return $this->constants;
}
return array_map(function(PhpConstant $constant) {
return $constant->getValue();
}, $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;
}
public function hasUseStatements()
{
return count($this->getUseStatements()) > 0;
}
public function uses($typeDef)
{
if (empty($typeDef)) {
throw new \InvalidArgumentException("Empty type definition name given in " . __METHOD__);
}
if (!$this->hasUseStatements()) {
return false;
}
if ('\\' === $typeDef[0]) {
return false; // typedef references the root
}
$parts = explode('\\', $typeDef);
$typeDef = array_shift($parts);
return isset($this->useStatements[$typeDef]);
}
}
src/CG/Generator/PhpConstant.php 0000666 00000001113 13164775705 0012543 0 ustar 00 name = $name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function setValue($value)
{
$this->value = $value;
return $this;
}
public function getName()
{
return $this->name;
}
public function getValue()
{
return $this->value;
}
} src/CG/Generator/PhpFunction.php 0000666 00000014530 13164775705 0012546 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
use CG\Core\ReflectionUtils;
class PhpFunction extends AbstractBuilder
{
private $name;
private $namespace;
private $parameters = array();
private $body = '';
private $referenceReturned = false;
private $docblock;
private $returnType;
private $returnTypeBuiltin = false;
public static function fromReflection(\ReflectionFunction $ref)
{
$function = new static();
if (false === $pos = strrpos($ref->name, '\\')) {
$function->setName(substr($ref->name, $pos + 1));
$function->setNamespace(substr($ref->name, $pos));
} else {
$function->setName($ref->name);
}
if (method_exists($ref, 'getReturnType')) {
if ($type = $ref->getReturnType()) {
$function->setReturnType((string)$type);
}
}
$function->referenceReturned = $ref->returnsReference();
$function->docblock = ReflectionUtils::getUnindentedDocComment($ref->getDocComment());
foreach ($ref->getParameters() as $refParam) {
assert($refParam instanceof \ReflectionParameter);
$param = PhpParameter::fromReflection($refParam);
$function->addParameter($param);
}
return $function;
}
public static function create($name = null)
{
return new static($name);
}
public function __construct($name = null)
{
$this->name = $name;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @param string $namespace
*/
public function setNamespace($namespace)
{
$this->namespace = $namespace;
return $this;
}
/**
* In contrast to getName(), this method accepts the fully qualified name
* including the namespace.
*
* @param string $name
*/
public function setQualifiedName($name)
{
if (false !== $pos = strrpos($name, '\\')) {
$this->namespace = substr($name, 0, $pos);
$this->name = substr($name, $pos + 1);
return $this;
}
$this->namespace = null;
$this->name = $name;
return $this;
}
public function setParameters(array $parameters)
{
$this->parameters = $parameters;
return $this;
}
/**
* @param boolean $bool
*/
public function setReferenceReturned($bool)
{
$this->referenceReturned = (Boolean) $bool;
return $this;
}
public function setReturnType($type)
{
$this->returnType = $type;
$this->returnTypeBuiltin = BuiltinType::isBuiltIn($type);
return $this;
}
/**
* @param integer $position
*/
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;
}
/**
* @param string|integer $nameOrIndex
*
* @return PhpParameter
*/
public function getParameter($nameOrIndex)
{
if (is_int($nameOrIndex)) {
if ( ! isset($this->parameters[$nameOrIndex])) {
throw new \InvalidArgumentException(sprintf('There is no parameter at position %d (0-based).', $nameOrIndex));
}
return $this->parameters[$nameOrIndex];
}
foreach ($this->parameters as $param) {
assert($param instanceof PhpParameter);
if ($param->getName() === $nameOrIndex) {
return $param;
}
}
throw new \InvalidArgumentException(sprintf('There is no parameter named "%s".', $nameOrIndex));
}
/**
* @param integer $position
*/
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;
}
/**
* @param string $body
*/
public function setBody($body)
{
$this->body = $body;
return $this;
}
/**
* @param string $docBlock
*/
public function setDocblock($docBlock)
{
$this->docblock = $docBlock;
return $this;
}
public function getName()
{
return $this->name;
}
public function getNamespace()
{
return $this->namespace;
}
public function getQualifiedName()
{
if ($this->namespace) {
return $this->namespace.'\\'.$this->name;
}
return $this->name;
}
public function getParameters()
{
return $this->parameters;
}
public function getBody()
{
return $this->body;
}
public function getDocblock()
{
return $this->docblock;
}
public function isReferenceReturned()
{
return $this->referenceReturned;
}
public function getReturnType()
{
return $this->returnType;
}
public function hasReturnType()
{
return null !== $this->getReturnType();
}
public function hasBuiltinReturnType()
{
return $this->returnTypeBuiltin;
}
}
src/CG/Generator/PhpMethod.php 0000666 00000013173 13164775705 0012203 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
class PhpMethod extends AbstractPhpMember
{
private $final = false;
private $abstract = false;
private $parameters = array();
private $referenceReturned = false;
private $returnType = null;
private $returnTypeBuiltin = false;
private $body = '';
/**
* @param string|null $name
*/
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 (method_exists($ref, 'getReturnType')) {
if ($type = $ref->getReturnType()) {
$method->setReturnType((string)$type);
}
}
if ($docComment = $ref->getDocComment()) {
$method->setDocblock(ReflectionUtils::getUnindentedDocComment($docComment));
}
foreach ($ref->getParameters() as $param) {
$method->addParameter(static::createParameter($param));
}
// FIXME: Extract body?
return $method;
}
/**
* @return PhpParameter
*/
protected static function createParameter(\ReflectionParameter $parameter)
{
return PhpParameter::fromReflection($parameter);
}
/**
* @param boolean $bool
*/
public function setFinal($bool)
{
$this->final = (Boolean) $bool;
return $this;
}
/**
* @param boolean $bool
*/
public function setAbstract($bool)
{
$this->abstract = $bool;
return $this;
}
/**
* @param boolean $bool
*/
public function setReferenceReturned($bool)
{
$this->referenceReturned = (Boolean) $bool;
return $this;
}
/**
* @param string $body
*/
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 setReturnType($type)
{
$this->returnType = $type;
$this->returnTypeBuiltin = BuiltinType::isBuiltin($type);
return $this;
}
/**
* @param string|integer $nameOrIndex
*
* @return PhpParameter
*/
public function getParameter($nameOrIndex)
{
if (is_int($nameOrIndex)) {
if ( ! isset($this->parameters[$nameOrIndex])) {
throw new \InvalidArgumentException(sprintf('There is no parameter at position %d (0-based).', $nameOrIndex));
}
return $this->parameters[$nameOrIndex];
}
foreach ($this->parameters as $param) {
assert($param instanceof PhpParameter);
if ($param->getName() === $nameOrIndex) {
return $param;
}
}
throw new \InvalidArgumentException(sprintf('There is no parameter named "%s".', $nameOrIndex));
}
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;
}
/**
* @param integer $position
*/
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;
}
public function getReturnType()
{
return $this->returnType;
}
public function hasReturnType()
{
return null !== $this->getReturnType();
}
public function hasBuiltInReturnType()
{
return $this->returnTypeBuiltin;
}
}
src/CG/Generator/PhpParameter.php 0000666 00000006677 13164775705 0012716 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
class PhpParameter extends AbstractBuilder
{
private $name;
private $defaultValue;
private $hasDefaultValue = false;
private $passedByReference = false;
private $type;
private $typeBuiltin;
/**
* @param string|null $name
*/
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 (method_exists($ref, 'getType')) {
if ($type = $ref->getType()) {
$parameter->setType((string)$type);
}
} else {
if ($ref->isArray()) {
$parameter->setType('array');
} elseif ($class = $ref->getClass()) {
$parameter->setType($class->name);
} elseif (method_exists($ref, 'isCallable') && $ref->isCallable()) {
$parameter->setType('callable');
}
}
return $parameter;
}
public function __construct($name = null)
{
$this->name = $name;
}
/**
* @param string $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;
}
/**
* @param boolean $bool
*/
public function setPassedByReference($bool)
{
$this->passedByReference = (Boolean) $bool;
return $this;
}
/**
* @param string $type
*/
public function setType($type)
{
$this->type = $type;
$this->typeBuiltin = BuiltinType::isBuiltIn($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;
}
public function hasType()
{
return null !== $this->type;
}
public function hasBuiltinType()
{
return $this->typeBuiltin;
}
}
src/CG/Generator/PhpProperty.php 0000666 00000004443 13164775705 0012607 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
class PhpProperty extends AbstractPhpMember
{
private $hasDefaultValue = false;
private $defaultValue;
/**
* @param string|null $name
*/
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;
}
/**
* @param string|false $value
*/
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;
}
}
src/CG/Generator/RelativePath.php 0000666 00000000421 13164775705 0012673 0 ustar 00 relativePath = $relativePath;
}
public function getRelativePath()
{
return $this->relativePath;
}
} src/CG/Generator/Writer.php 0000666 00000004716 13164775705 0011572 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
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;
}
/**
* @param string $content
*/
public function writeln($content)
{
$this->write($content."\n");
return $this;
}
/**
* @param string $content
*/
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;
}
}
src/CG/Proxy/Enhancer.php 0000666 00000011514 13164775705 0011226 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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\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
*/
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, "generateClass());
}
/**
* Creates a new enhanced class
*
* @return string
*/
final public 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.')
->write(' */')
;
$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;
}
}
src/CG/Proxy/GeneratorInterface.php 0000666 00000002121 13164775705 0013244 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
interface GeneratorInterface
{
/**
* Generates the necessary changes in the class.
*
* @param \ReflectionClass $originalClass
* @param PhpClass $generatedClass The generated class
* @return void
*/
public function generate(\ReflectionClass $originalClass, PhpClass $generatedClass);
} src/CG/Proxy/InterceptionGenerator.php 0000666 00000007110 13164775705 0014012 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
class InterceptionGenerator implements GeneratorInterface
{
private $prefix = '__CGInterception__';
private $filter;
private $requiredFile;
public function setRequiredFile($file)
{
$this->requiredFile = $file;
}
/**
* @param string $prefix
*/
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);
}
}
}
src/CG/Proxy/InterceptorLoaderInterface.php 0000666 00000002072 13164775705 0014750 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
interface InterceptorLoaderInterface
{
/**
* Loads interceptors.
*
* @param \ReflectionMethod $method
* @return MethodInterceptorInterface[]
*/
function loadInterceptors(\ReflectionMethod $method);
} src/CG/Proxy/LazyInitializerGenerator.php 0000666 00000012035 13164775705 0014474 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
class LazyInitializerGenerator implements GeneratorInterface
{
private $writer;
private $prefix = '__CG__';
private $markerInterface;
public function __construct()
{
$this->writer = new Writer();
}
/**
* @param string $prefix
*/
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);
}
}
}
src/CG/Proxy/LazyInitializerInterface.php 0000666 00000002011 13164775705 0014437 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
interface LazyInitializerInterface
{
/**
* Initializes the passed object.
*
* @param object $object
* @return void
*/
public function initializeObject($object);
} src/CG/Proxy/MethodInterceptorInterface.php 0000666 00000002561 13164775705 0014765 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
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
*/
public function intercept(MethodInvocation $invocation);
}
src/CG/Proxy/MethodInvocation.php 0000666 00000005530 13164775705 0012756 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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
*/
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;
}
public function getNamedArgument($name)
{
foreach ($this->reflection->getParameters() as $i => $param) {
if ($param->name !== $name) {
continue;
}
if ( ! array_key_exists($i, $this->arguments)) {
if ($param->isDefaultValueAvailable()) {
return $param->getDefaultValue();
}
throw new \RuntimeException(sprintf('There was no value given for parameter "%s".', $param->name));
}
return $this->arguments[$i];
}
throw new \InvalidArgumentException(sprintf('The parameter "%s" does not exist.', $name));
}
/**
* 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);
}
}
src/CG/Proxy/RegexInterceptionLoader.php 0000666 00000002620 13164775705 0014266 0 ustar 00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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;
}
}
src/CG/Version.php 0000666 00000000110 13164775705 0007775 0 ustar 00 assertEquals('Foo', ClassUtils::getUserClass('Foo'));
$this->assertEquals('Bar', ClassUtils::getUserClass('FOO\__CG__\Bar'));
}
} tests/CG/Tests/Core/DefaultGeneratorStrategyTest.php 0000666 00000003674 13164775705 0016555 0 ustar 00 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())
);
}
/**
* @param string $file
*/
private function getContent($file)
{
return file_get_contents(__DIR__.'/generated/'.$file);
}
/**
* @return PhpClass
*/
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;
}
}
tests/CG/Tests/Core/ReflectionUtilsTest.php 0000666 00000002422 13164775705 0014700 0 ustar 00 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() { }
final public function b() { }
public static function c() { }
abstract public function d();
protected function e() { }
final protected function f() {}
protected static function g() { }
abstract protected function h();
private function i() { }
}
tests/CG/Tests/Core/generated/GenerationTestClass_A.php 0000666 00000000260 13164775705 0017042 0 ustar 00 class GenerationTestClass
{
const a = 'foo';
const b = 'bar';
public $a;
public $b;
public function a()
{
}
public function b()
{
}
} tests/CG/Tests/Core/generated/GenerationTestClass_B.php 0000666 00000000260 13164775705 0017043 0 ustar 00 class GenerationTestClass
{
const b = 'bar';
const a = 'foo';
public $a;
public $b;
public function a()
{
}
public function b()
{
}
} tests/CG/Tests/Generator/AbstractPhpMemberTest.php 0000666 00000003141 13164775705 0016165 0 ustar 00 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');
}
}
tests/CG/Tests/Generator/DefaultVisitorTest.php 0000666 00000007436 13164775705 0015601 0 ustar 00 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());
}
public function testVisitMethod()
{
$method = new PhpMethod();
$visitor = new DefaultVisitor();
$method
->setName('foo')
->setReferenceReturned(true);
$visitor->visitMethod($method);
$this->assertEquals($this->getContent('reference_returned_method.php'), $visitor->getContent());
}
public function testVisitMethodWithCallable()
{
if (PHP_VERSION_ID < 50400) {
$this->markTestSkipped('`callable` is only supported in PHP >=5.4.0');
}
$method = new PhpMethod();
$parameter = new PhpParameter('bar');
$parameter->setType('callable');
$method
->setName('foo')
->addParameter($parameter);
$visitor = new DefaultVisitor();
$visitor->visitMethod($method);
$this->assertEquals($this->getContent('callable_parameter.php'), $visitor->getContent());
}
public function testVisitClassWithPhp7Features()
{
if (PHP_VERSION_ID < 70000) {
$this->markTestSkipped('Test only valid for PHP >=7.0');
}
$ref = new \ReflectionClass('CG\Tests\Generator\Fixture\EntityPhp7');
$class = PhpClass::fromReflection($ref);
$generator = new DefaultGeneratorStrategy();
$content = $generator->generate($class);
$this->assertEquals($this->getContent('php7_class.php'), $content);
}
/**
* @dataProvider visitFunctionWithPhp7FeaturesDataProvider
*/
public function testVisitFunctionWithPhp7Features($filename, $function)
{
if (PHP_VERSION_ID < 70000) {
$this->markTestSkipped('Test only valid for PHP >=7.0');
}
$visitor = new DefaultVisitor();
$visitor->visitFunction($function);
$this->assertEquals($this->getContent($filename.'.php'), $visitor->getContent());
}
public function visitFunctionWithPhp7FeaturesDataProvider()
{
$builtinReturn = PhpFunction::create('foo')
->setReturnType('bool');
$nonbuiltinReturn = PhpFunction::create('foo')
->setReturnType('\Foo');
return array(
array('php7_builtin_return', $builtinReturn),
array('php7_func_nonbuiltin_return', $nonbuiltinReturn),
);
}
/**
* @param string $filename
*/
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);
}
}
tests/CG/Tests/Generator/Fixture/Entity.php 0000666 00000001112 13164775705 0014660 0 ustar 00
*/
abstract class Entity
{
/**
* @var integer
*/
private $id;
private $enabled = false;
/**
* Another doc comment.
*
* @param unknown_type $a
* @param array $b
* @param \stdClass $c
* @param string $d
*/
final public function __construct($a, array &$b, \stdClass $c, $d = 'foo')
{
}
abstract protected function foo();
private static function bar()
{
}
}
tests/CG/Tests/Generator/Fixture/EntityPhp7.php 0000666 00000002107 13164775705 0015424 0 ustar 00
*/
class EntityPhp7
{
/**
* @var integer
*/
private $id = 0;
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
* @return EntityPhp7
*/
public function setId(int $id = null): self
{
$this->id = $id;
return $this;
}
public function getTime(): DateTime
{
}
public function getTimeZone(): \DateTimeZone
{
}
public function setTime(DateTime $time)
{
}
public function setTimeZone(\DateTimeZone $timezone)
{
}
public function setArray(array &$array = null): array
{
}
public function getFoo(): Foo
{
}
public function getBar(): Sub\Bar
{
}
public function getBaz(): \CG\Tests\Generator\Fixture\SubFixture\Baz
{
}
}
tests/CG/Tests/Generator/Fixture/SubFixture/Bar.php 0000666 00000000105 13164775705 0016211 0 ustar 00
*/
class EntityPhp7
{
/**
* @var integer
*/
private $id = 0;
public function setTimeZone(\DateTimeZone $timezone)
{
}
public function setTime(\DateTime $time)
{
}
/**
* @param int $id
* @return EntityPhp7
*/
public function setId(int $id = NULL): self
{
}
public function setArray(array &$array = NULL): array
{
}
public function getTimeZone(): \DateTimeZone
{
}
public function getTime(): \DateTime
{
}
/**
* @return int
*/
public function getId(): int
{
}
public function getFoo(): \CG\Tests\Generator\Fixture\SubFixture\Foo
{
}
public function getBaz(): \CG\Tests\Generator\Fixture\SubFixture\Baz
{
}
public function getBar(): \CG\Tests\Generator\Fixture\SubFixture\Bar
{
}
} tests/CG/Tests/Generator/Fixture/generated/php7_func_nonbuiltin_return.php 0000666 00000000030 13164775705 0023071 0 ustar 00 function foo(): \Foo
{
} tests/CG/Tests/Generator/Fixture/generated/reference_returned_method.php 0000666 00000000035 13164775705 0022553 0 ustar 00 public function & foo()
{
}
tests/CG/Tests/Generator/Php7ClassTest.php 0000666 00000006414 13164775705 0014434 0 ustar 00 markTestSkipped("Test is only valid for PHP >=7");
}
$class = new PhpClass();
$class
->setName('CG\Tests\Generator\Fixture\EntityPhp7')
->setDocblock('/**
* Doc Comment.
*
* @author Johannes M. Schmitt
*/')
->setProperty(PhpProperty::create('id')
->setVisibility('private')
->setDefaultValue(0)
->setDocblock('/**
* @var integer
*/')
);
$class->setMethod(PhpMethod::create()
->setName('getId')
->setDocblock('/**
* @return int
*/')
->setVisibility('public')
->setReturnType('int')
);
$class->setMethod(PhpMethod::create()
->setName('setId')
->setVisibility('public')
->setDocBlock('/**
* @param int $id
* @return EntityPhp7
*/')
->addParameter(PhpParameter::create()
->setName('id')
->setType('int')
->setDefaultValue(null)
)
->setReturnType('self')
);
$class->setMethod(PhpMethod::create()
->setName('getTime')
->setVisibility('public')
->setReturnType('DateTime')
);
$class->setMethod(PhpMethod::create()
->setName('getTimeZone')
->setVisibility('public')
->setReturnType('DateTimeZone')
);
$class->setMethod(PhpMethod::create()
->setName('setTime')
->setVisibility('public')
->addParameter(PhpParameter::create()
->setName('time')
->setType('DateTime')
)
);
$class->setMethod(PhpMethod::create()
->setName('setTimeZone')
->setVisibility('public')
->addParameter(PhpParameter::create()
->setName('timezone')
->setType('DateTimeZone')
)
);
$class->setMethod(PhpMethod::create()
->setName('setArray')
->setVisibility('public')
->setReturnType('array')
->addParameter(PhpParameter::create()
->setName('array')
->setDefaultValue(null)
->setPassedByReference(true)
->setType('array')
)
);
$class->setMethod(PhpMethod::create()
->setName('getFoo')
->setReturnType('CG\Tests\Generator\Fixture\SubFixture\Foo')
);
$class->setMethod(PhpMethod::create()
->setName('getBar')
->setReturnType('CG\Tests\Generator\Fixture\SubFixture\Bar')
);
$class->setMethod(PhpMethod::create()
->setName('getBaz')
->setReturnType('CG\Tests\Generator\Fixture\SubFixture\Baz')
);
$this->assertEquals($class, PhpClass::fromReflection(new \ReflectionClass('CG\Tests\Generator\Fixture\EntityPhp7')));
}
}
tests/CG/Tests/Generator/PhpClassTest.php 0000666 00000020232 13164775705 0014337 0 ustar 00 setName('CG\Tests\Generator\Fixture\Entity')
->setAbstract(true)
->setDocblock('/**
* Doc Comment.
*
* @author Johannes M. Schmitt
*/')
->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 string $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());
}
/**
* @dataProvider usesClassDataProvider
*/
public function testUsesClass($usage, $typedef, $expected)
{
$class = new PhpClass();
$class->addUseStatement($usage);
$this->assertEquals($class->uses($typedef), $expected);
}
public function usesClassDataProvider()
{
return array(
array('\DateTime', '\DateTime', false), // using fqdn from root ignores use statements
array('\DateTime', 'DateTime', true),
array('Foo\Bar\Baz', 'Baz', true),
array('Foo\Bar\Baz', 'Bar', false),
array('Foo\Bar\Baz', 'Foo', false),
array('Foo\Bar', 'Bar\Baz', true),
array('Foo\Bar', '\Bar\Baz', false)
);
}
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());
}
}
tests/CG/Tests/Generator/PhpFunctionTest.php 0000666 00000005713 13164775705 0015066 0 ustar 00 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 testSetGetQualifiedName()
{
$func = new PhpFunction();
$this->assertSame($func, $func->setQualifiedName('foo\bar'));
$this->assertEquals('foo', $func->getNamespace());
$this->assertEquals('bar', $func->getName());
$this->assertEquals('foo\bar', $func->getQualifiedName());
$this->assertSame($func, $func->setQualifiedName('foo'));
$this->assertNull($func->getNamespace());
$this->assertEquals('foo', $func->getName());
$this->assertEquals('foo', $func->getQualifiedName());
}
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());
}
} tests/CG/Tests/Generator/PhpMethodTest.php 0000666 00000004577 13164775705 0014530 0 ustar 00 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());
}
} tests/CG/Tests/Generator/PhpParameterTest.php 0000666 00000003114 13164775705 0015212 0 ustar 00 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());
}
} tests/CG/Tests/Generator/PhpPropertyTest.php 0000666 00000001247 13164775705 0015123 0 ustar 00 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());
}
} tests/CG/Tests/Proxy/EnhancerTest.php 0000666 00000007525 13164775705 0013552 0 ustar 00 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;
}
/**
* @param string $file
*/
private function getContent($file)
{
return file_get_contents(__DIR__.'/Fixture/generated/'.$file.'.php.gen');
}
/**
* @param string $name
* @return null|\CG\Core\NamingStrategyInterface
*/
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;
}
}
tests/CG/Tests/Proxy/Fixture/Entity.php 0000666 00000000402 13164775705 0014054 0 ustar 00 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();
}
} tests/CG/Tests/Proxy/Fixture/generated/Entity__CG__LazyInitializing.php.gen 0000666 00000002057 13164775705 0023013 0 ustar 00 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;
}
} tests/CG/Tests/Proxy/Fixture/generated/SimpleClass__CG__Enhanced.php.gen 0000666 00000000513 13164775705 0022164 0 ustar 00 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
{
} tests/CG/Tests/Proxy/Fixture/generated/SimpleClass__CG__Sluggable.php.gen 0000666 00000000571 13164775705 0022370 0 ustar 00 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()
{
}
} tests/bootstrap.php 0000666 00000001645 13164775705 0010465 0 ustar 00
*
*/
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;
}
} elseif (0 === strpos($class, 'CG\\')) {
$path = __DIR__.'/../src/'.($class = strtr($class, '\\', '/')).'.php';
if (file_exists($path) && is_readable($path)) {
require_once $path;
return true;
}
} elseif (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;
}
}
});