Augmentation vers version 3.3.0

This commit is contained in:
Gauvain Boiché
2020-03-31 15:31:03 +02:00
parent d926806907
commit a1864c0414
2618 changed files with 406015 additions and 31377 deletions

View File

@@ -0,0 +1,509 @@
# Changelog
All notable changes to this project will be documented in this file, in reverse chronological order by release.
## 3.4.1 - 2019-12-10
### Added
- [#180](https://github.com/zendframework/zend-code/pull/180) adds support for PHP 7.4.
### Changed
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#179](https://github.com/zendframework/zend-code/pull/179) fixes exception message when invalid value provided in `Zend\Code\Generator\ValueGenerator`.
- [#180](https://github.com/zendframework/zend-code/pull/190) fixes PHP 7.4 compatibility.
## 3.4.0 - 2019-10-06
### Added
- [#170](https://github.com/zendframework/zend-code/pull/170) adds class constant visibility modifiers support.
- [#169](https://github.com/zendframework/zend-code/pull/169) adds the ability to define declare statements.
- [#167](https://github.com/zendframework/zend-code/pull/167) adds the ability to remove doc block of a member.
### Changed
- [#166](https://github.com/zendframework/zend-code/pull/166) changes omitting default property value if it is null.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#172](https://github.com/zendframework/zend-code/pull/172) fixes PHP 7.4 compatibility.
## 3.3.2 - 2019-08-31
### Added
- [#162](https://github.com/zendframework/zend-code/pull/162) adds support for PHP 7.3.
### Changed
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#171](https://github.com/zendframework/zend-code/pull/171) changes
curly braces in array and string offset access to square brackets
in order to prevent issues under the upcoming PHP 7.4 release.
- [#164](https://github.com/zendframework/zend-code/pull/164) fixes indentation in multi-level arrays generated by `ValueGenerator`.
## 3.3.1 - 2018-08-13
### Added
- Nothing.
### Changed
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#158](https://github.com/zendframework/zend-code/pull/158) updates several `switch` cases to use `break` instead of `continue`
in order to prevent issues under the upcoming PHP 7.3 release.
- [#147](https://github.com/zendframework/zend-code/pull/147) fixes the regular expression used for `@var` annotations to
allow omission of the variable name.
- [#146](https://github.com/zendframework/zend-code/pull/146) updates all `@return` annotations to reflect the correct types returned by each method.
- [#144](https://github.com/zendframework/zend-code/pull/144) fixes the class generator such that it now resolves
`setExtendedClass()` arguments to aliases provided to the generator.
- [#140](https://github.com/zendframework/zend-code/pull/140) fixes `MethodScanner::setVisibility()` such that it no longer
casts the provided visibility token to lower case; this fix is necessary, as
the method is supposed to expect only the appropriate
`T_(PUBLIC|PROTECTED|PRIVATE)` token values, which are integers.
- [#140](https://github.com/zendframework/zend-code/pull/140) updates the `MethodScanner::setVisibility()` method to raise
a package-specific `InvalidArgumentException` instead of the non-existent
package `Exception` class when an invalid visibility is provided.
## 3.3.0 - 2017-10-20
### Added
- [#131](https://github.com/zendframework/zend-code/pull/131) added the
ability to omit a parameter type declaration
- [#132](https://github.com/zendframework/zend-code/pull/132) added a
lightweight `MethodGenerator::copyMethodSignature()` constructor that
only copies the method declaration with no body nor docblock.
- [#134](https://github.com/zendframework/zend-code/pull/134) short array
notation is now used by default for generated array values
- [#136](https://github.com/zendframework/zend-code/pull/136) added the
ability to specify an `omitdefaultvalue` key when using
`ParameterGenerator::fromArray()`
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#130](https://github.com/zendframework/zend-code/pull/130) Updated
links to the documentation
- [#133](https://github.com/zendframework/zend-code/pull/133) The default
value of a `ParameterGenerator` is always a `ValueGenerator`
## 3.2.0 - 2017-07-23
### Added
- [#112](https://github.com/zendframework/zend-code/pull/112)
[#110](https://github.com/zendframework/zend-code/pull/110) Introduced
support for the PHP `7.2` `object` type-hint
- [#41](https://github.com/zendframework/zend-code/pull/41) Added `VarTag`
support to the docblock generators and reflectors: allows generating
and parsing `@var` tags.
- [#113](https://github.com/zendframework/zend-code/pull/113) Added
PHP `7.2` to the build matrix
- [#114](https://github.com/zendframework/zend-code/pull/114) Increased
minimum supported PHP version to `^7.1.0`
- [#114](https://github.com/zendframework/zend-code/pull/114) Upgraded
PHPUnit dependency to `^6.2.2`
- [#121](https://github.com/zendframework/zend-code/pull/121) Imported
global functions via `use` statements (experimenting with OpCache
OPCODE inlining optimisations)
### Deprecated
- Nothing.
### Removed
- [#113](https://github.com/zendframework/zend-code/pull/113)
[#118](https://github.com/zendframework/zend-code/pull/118) Removed
HHVM support
- [#122](https://github.com/zendframework/zend-code/pull/122) Removed
IRC notifications for pushes/build statuses
### Fixed
- [#101](https://github.com/zendframework/zend-code/pull/101) avoid
calling `isInternalPhpType` twice in the `TypeGenerator`
- [#115](https://github.com/zendframework/zend-code/pull/115) Replaced
assertions in the test suite with their static counterparts where
applicable
- [#120](https://github.com/zendframework/zend-code/pull/120)
[#109](https://github.com/zendframework/zend-code/pull/109)
[#100](https://github.com/zendframework/zend-code/pull/100) Applied
ZendFramework coding standard to the library code
- [#119](https://github.com/zendframework/zend-code/pull/119) Corrected
test suite errors caused by mismatching parameter order
- [#106](https://github.com/zendframework/zend-code/pull/106)
- [#107](https://github.com/zendframework/zend-code/pull/107) Minor
typing error corrections in documentation and error messages
## 3.1.0 - 2016-10-24
### Added
- [#87](https://github.com/zendframework/zend-code/pull/87) support for
PHP 7.1's `void` return type declaration.
- [#87](https://github.com/zendframework/zend-code/pull/87) support for
PHP 7.1's nullable type declarations.
- [#87](https://github.com/zendframework/zend-code/pull/87) support for
PHP 7.1's `iterable` type declaration.
- [#62](https://github.com/zendframework/zend-code/pull/62) added
`Zend\Code\Generator\MethodGenerator#getReturnType()` accessor.
- [#68](https://github.com/zendframework/zend-code/pull/68)
[#26](https://github.com/zendframework/zend-code/pull/26) added mutators
to allow removing/checking for existence of methods, properties, constants,
parameters and type declarations across all the code generator API.
- [#65](https://github.com/zendframework/zend-code/pull/65) continuous
integration testing now checks locked, newest and oldest dependency
sets.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 3.0.5 - 2016-10-24
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#92](https://github.com/zendframework/zend-code/pull/92) corrected
`Zend\Code\Scanner\ClassScanner` to detect multiple interface inheritance.
- [#95](https://github.com/zendframework/zend-code/pull/95) corrected
`Zend\Code\Generator\ParameterGenerator` to allow copying parameter signatures
for non-optional parameters that are still nullable via a default `= null`
value.
- [#94](https://github.com/zendframework/zend-code/pull/94) corrected
`Zend\Code\Generator\ValueGenerator` so that class constants can now
be generated with arrays as default value (supported since PHP 5.6).
## 3.0.4 - 2016-06-30
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#59](https://github.com/zendframework/zend-code/pull/59) fixes an issue with
detection of multiple trait `use` statements.
- [#75](https://github.com/zendframework/zend-code/pull/75) provides a patch to
ensure that `extends` statements qualify the parent class based on the current
namespace and/or import statements.
## 3.0.3 - 2016-06-27
### Added
- [#66](https://github.com/zendframework/zend-code/pull/66) publishes the
documentation to https://docs.zendframework.com/zend-code/.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#61](https://github.com/zendframework/zend-code/pull/61) fixes an issue with
how parameter typehints were generated; previously, fully-qualified class
names were not being generated with the leading backslash, causing them to
attempt to resolve as if they were relative to the current namespace.
- [#69](https://github.com/zendframework/zend-code/pull/69) fixes an issue with
how class names under the same namespace are generated when generating
typehints, extends, and implements values; they now strip the
common namespace from the class name.
- [#72](https://github.com/zendframework/zend-code/pull/72) fixes an issue
within the `TokenArrayScanner` when scanning closures.
## 3.0.2 - 2016-04-20
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#52](https://github.com/zendframework/zend-code/pull/52) updates several
dependency constraints:
- zend-stdlib now allows either the 2.7 or 3.0 series, as the APIs consumed by
zend-code are compatible across versions.
- PHP now excludes the 7.0.5 release, as it has known issues in its tokenizer
implementation that make the zend-code token scanner unusable.
- [#46](https://github.com/zendframework/zend-code/pull/46) updates all
generators to use `\n` for line endings in generated code, vs `PHP_EOL`,
ensuring cross-platform consistency.
## 3.0.1 - 2016-01-26
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#34](https://github.com/zendframework/zend-code/pull/34) method name cannot be optional when adding a method
to a class generator.
- [#38](https://github.com/zendframework/zend-code/pull/38) PHP_CodeSniffer was moved to dev dependencies
## 3.0.0 - 2016-01-13
### Changed
- [#140](https://github.com/zendframework/zend-code/pull/140) updates the `MethodScanner::setVisibility()` method to raise a package-specific `InvalidArgumentException` instead of
the non-existent package `Exception` class when an invalid visibility is provided.
This section refers to breaking changes: please refer to
[docs/book/migration.md](docs/book/migration.md) for migration instructions.
- Types `string`, `int`, `float`, `bool` passed to `Zend\Code\Generator\ParameterGenerator#setType()`
are no longer ignored in generated code [#30](https://github.com/zendframework/zend-code/pull/30)
- Types declared in DocBlocks are now ignored when creating a `Zend\Code\Generator\ParameterGenerator` via
`Zend\Code\Generator\ParameterGenerator::fromReflection()`. [#30](https://github.com/zendframework/zend-code/pull/30)
- Type strings are now validated: passing an invalid type to any method in the generator API
may lead to a `Zend\Code\Generator\InvalidArgumentException` being thrown.
[#30](https://github.com/zendframework/zend-code/pull/30)
- `Zend\Code\Generator\ParameterGenerator::$simple` was removed. [#30](https://github.com/zendframework/zend-code/pull/30)
- `Zend\Code\Generator\ParameterGenerator#$type` is now a `null|Zend\Code\Generator\TypeGenerator`: was a
`string` before. [#30](https://github.com/zendframework/zend-code/pull/30)
- `Zend\Code\Generator` type-hints are now always prefixed with the namespace separator `\`.
[#30](https://github.com/zendframework/zend-code/pull/30)
- `Zend\Code\Reflection\ParameterReflection#getType()` was renamed
to `Zend\Code\Reflection\ParameterReflection#detectType()` in order to not override the inherited
`ReflectionParameter#getType()`, introduced in PHP 7. [#30](https://github.com/zendframework/zend-code/pull/30)
### Added
- PHP 7 return type hints generation support via `Zend\Code\Generator\MethodGenerator#setReturnType()`.
[#30](https://github.com/zendframework/zend-code/pull/30)
- PHP 7 scalar type hints generation support via `Zend\Code\Generator\ParameterGenerator#setType()` and
`Zend\Code\Generator\ParameterGenerator#getType()`. [#30](https://github.com/zendframework/zend-code/pull/30)
- PHP 5.6 variadic arguments support via `Zend\Code\Generator\ParameterGenerator#setVariadic()` and
`Zend\Code\Generator\ParameterGenerator#getVariadic()`. [#30](https://github.com/zendframework/zend-code/pull/30)
- Generation of methods returning by reference is supported via `Zend\Code\Generator\ParameterGenerator#setReturnsReference()`.
[#30](https://github.com/zendframework/zend-code/pull/30)
### Deprecated
- Nothing.
### Removed
- `Zend\Code\ParameterGenerator::$simple` was removed. [#30](https://github.com/zendframework/zend-code/pull/30)
### Fixed
- Nothing.
## 2.6.2 - 2015-01-05
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#31](https://github.com/zendframework/zend-code/pull/31) updated license year.
## 2.6.2 - 2015-01-05
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#31](https://github.com/zendframework/zend-code/pull/31) updated license year.
## 2.6.1 - 2015-11-24
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#25](https://github.com/zendframework/zend-code/pull/25) changes the
`doctrine/common` suggestion/dev-dependency to the more specific
`doctrine/annotations` package (which is what is actually consumed).
## 2.6.0 - 2015-11-18
### Added
- [#12](https://github.com/zendframework/zend-code/pull/12) adds the ability to
generate arrays using either long/standard syntax (`array(...)`) or short
syntax (`[...]`). This can be accomplished by setting the value type to
`ValueGenerator::TYPE_ARRAY_SHORT` instead of using `TYPE_ARRAY`.
Additionally, you can use `TYPE_ARRAY_LONG` instead of `TYPE_ARRAY`; the two
constants are synonyms.
- [#11](https://github.com/zendframework/zend-code/pull/11) adds the ability to
generate interfaces via the new class `Zend\Code\Generator\InterfaceGenerator`.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#20](https://github.com/zendframework/zend-code/pull/20) updates
the zend-eventmanager dependency to `^2.6|^3.0`, and changes its
internal usage to use the `triggerEventUntil()` signature.
## 2.5.3 - 2015-11-18
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- [#10](https://github.com/zendframework/zend-code/pull/10) removes a
development dependency on zendframework/zend-version.
- [#23](https://github.com/zendframework/zend-code/pull/23) removes a
requirement on zendframework/zend-stdlib. This results in a slight change in
`Zend\Code\Generator\ValueGenerator`: `setConstants()` and `getConstants()`
can now receive/emit *either* an SPL `ArrayObject` or
`Zend\Stdlib\ArrayObject`. Since these are functionally equivalent, however,
you will experience no change in behavior.
### Fixed
- Nothing.

View File

@@ -1,16 +1,15 @@
Copyright (c) 2005-2015, Zend Technologies USA, Inc.
Copyright (c) 2005-2019, Zend Technologies USA, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
- Neither the name of Zend Technologies USA, Inc. nor the names of its
contributors may be used to endorse or promote products derived from this

View File

@@ -1,43 +1,66 @@
{
"name": "zendframework/zend-code",
"description": "provides facilities to generate arbitrary code using an object oriented interface",
"description": "Extensions to the PHP Reflection API, static code scanning, and code generation",
"license": "BSD-3-Clause",
"keywords": [
"zf2",
"zf",
"zendframework",
"code"
],
"homepage": "https://github.com/zendframework/zend-code",
"support": {
"docs": "https://docs.zendframework.com/zend-code/",
"issues": "https://github.com/zendframework/zend-code/issues",
"source": "https://github.com/zendframework/zend-code",
"rss": "https://github.com/zendframework/zend-code/releases.atom",
"chat": "https://zendframework-slack.herokuapp.com",
"forum": "https://discourse.zendframework.com/c/questions/components"
},
"require": {
"php": "^7.1",
"zendframework/zend-eventmanager": "^2.6 || ^3.0"
},
"require-dev": {
"ext-phar": "*",
"doctrine/annotations": "^1.7",
"phpunit/phpunit": "^7.5.16 || ^8.4",
"zendframework/zend-coding-standard": "^1.0",
"zendframework/zend-stdlib": "^2.7 || ^3.0"
},
"conflict": {
"phpspec/prophecy": "<1.9.0"
},
"suggest": {
"doctrine/annotations": "Doctrine\\Common\\Annotations >=1.0 for annotation features",
"zendframework/zend-stdlib": "Zend\\Stdlib component"
},
"autoload": {
"psr-4": {
"Zend\\Code\\": "src/"
}
},
"require": {
"php": ">=5.3.23",
"zendframework/zend-eventmanager": "~2.5"
},
"require-dev": {
"doctrine/common": ">=2.1",
"zendframework/zend-stdlib": "~2.5",
"zendframework/zend-version": "~2.5",
"fabpot/php-cs-fixer": "1.7.*",
"phpunit/PHPUnit": "~4.0"
},
"suggest": {
"doctrine/common": "Doctrine\\Common >=2.1 for annotation features",
"zendframework/zend-stdlib": "Zend\\Stdlib component"
},
"minimum-stability": "dev",
"prefer-stable": true,
"extra": {
"branch-alias": {
"dev-master": "2.5-dev",
"dev-develop": "2.6-dev"
}
},
"autoload-dev": {
"psr-4": {
"ZendTest\\Code\\": "test/"
}
},
"config": {
"sort-packages": true
},
"extra": {
"branch-alias": {
"dev-master": "3.4.x-dev",
"dev-develop": "3.5.x-dev",
"dev-dev-4.0": "4.0.x-dev"
}
},
"scripts": {
"check": [
"@cs-check",
"@test"
],
"cs-check": "phpcs",
"cs-fix": "phpcbf",
"test": "phpunit --colors=always",
"test-coverage": "phpunit --colors=always --coverage-clover clover.xml"
}
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,6 +11,8 @@ namespace Zend\Code\Annotation;
use ArrayObject;
use function get_class;
class AnnotationCollection extends ArrayObject
{
/**

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -15,6 +15,9 @@ use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use function get_class;
use function is_object;
/**
* Pluggable annotation manager
*
@@ -41,10 +44,10 @@ class AnnotationManager implements EventManagerAwareInterface
*/
public function setEventManager(EventManagerInterface $events)
{
$events->setIdentifiers(array(
$events->setIdentifiers([
__CLASS__,
get_class($this),
));
]);
$this->events = $events;
return $this;
@@ -75,7 +78,7 @@ class AnnotationManager implements EventManagerAwareInterface
public function attach(ParserInterface $parser)
{
$this->getEventManager()
->attach(self::EVENT_CREATE_ANNOTATION, array($parser, 'onCreateAnnotation'));
->attach(self::EVENT_CREATE_ANNOTATION, [$parser, 'onCreateAnnotation']);
return $this;
}
@@ -91,19 +94,19 @@ class AnnotationManager implements EventManagerAwareInterface
$event = new Event();
$event->setName(self::EVENT_CREATE_ANNOTATION);
$event->setTarget($this);
$event->setParams(array(
$event->setParams([
'class' => $annotationData[0],
'content' => $annotationData[1],
'raw' => $annotationData[2],
));
]);
$eventManager = $this->getEventManager();
$results = $eventManager->trigger($event, function ($r) {
return (is_object($r));
});
$results = $eventManager->triggerEventUntil(function ($r) {
return is_object($r);
}, $event);
$annotation = $results->last();
return (is_object($annotation) ? $annotation : false);
return is_object($annotation) ? $annotation : false;
}
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -15,6 +15,15 @@ use Traversable;
use Zend\Code\Exception;
use Zend\EventManager\EventInterface;
use function array_shift;
use function class_exists;
use function get_class;
use function gettype;
use function is_array;
use function is_object;
use function preg_replace;
use function sprintf;
/**
* A parser for docblock annotations that utilizes the annotation parser from
* Doctrine\Common.
@@ -29,7 +38,7 @@ class DoctrineAnnotationParser implements ParserInterface
/**
* @var array Annotation classes we support on this iteration
*/
protected $allowedAnnotations = array();
protected $allowedAnnotations = [];
/**
* @var DocParser
@@ -65,7 +74,7 @@ class DoctrineAnnotationParser implements ParserInterface
*/
public function getDocParser()
{
if (!$this->docParser instanceof DocParser) {
if (! $this->docParser instanceof DocParser) {
$this->setDocParser(new DocParser());
}
@@ -81,16 +90,16 @@ class DoctrineAnnotationParser implements ParserInterface
public function onCreateAnnotation(EventInterface $e)
{
$annotationClass = $e->getParam('class', false);
if (!$annotationClass) {
if (! $annotationClass) {
return false;
}
if (!isset($this->allowedAnnotations[$annotationClass])) {
if (! isset($this->allowedAnnotations[$annotationClass])) {
return false;
}
$annotationString = $e->getParam('raw', false);
if (!$annotationString) {
if (! $annotationString) {
return false;
}
@@ -107,7 +116,7 @@ class DoctrineAnnotationParser implements ParserInterface
}
$annotation = array_shift($annotations);
if (!is_object($annotation)) {
if (! is_object($annotation)) {
return false;
}
@@ -136,11 +145,11 @@ class DoctrineAnnotationParser implements ParserInterface
*/
public function registerAnnotations($annotations)
{
if (!is_array($annotations) && !$annotations instanceof Traversable) {
if (! is_array($annotations) && ! $annotations instanceof Traversable) {
throw new Exception\InvalidArgumentException(sprintf(
'%s: expects an array or Traversable; received "%s"',
__METHOD__,
(is_object($annotations) ? get_class($annotations) : gettype($annotations))
is_object($annotations) ? get_class($annotations) : gettype($annotations)
));
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -14,6 +14,19 @@ use Zend\Code\Annotation\AnnotationInterface;
use Zend\Code\Exception;
use Zend\EventManager\EventInterface;
use function array_search;
use function class_exists;
use function get_class;
use function gettype;
use function in_array;
use function is_array;
use function is_object;
use function is_string;
use function sprintf;
use function str_replace;
use function strtolower;
use function trim;
/**
* Generic annotation parser
*
@@ -26,17 +39,17 @@ class GenericAnnotationParser implements ParserInterface
/**
* @var array
*/
protected $aliases = array();
protected $aliases = [];
/**
* @var array
*/
protected $annotationNames = array();
protected $annotationNames = [];
/**
* @var AnnotationInterface[]
*/
protected $annotations = array();
protected $annotations = [];
/**
* Listen to onCreateAnnotation, and attempt to return an annotation object
@@ -53,7 +66,7 @@ class GenericAnnotationParser implements ParserInterface
public function onCreateAnnotation(EventInterface $e)
{
$class = $e->getParam('class', false);
if (!$class || !$this->hasAnnotation($class)) {
if (! $class || ! $this->hasAnnotation($class)) {
return false;
}
@@ -80,7 +93,7 @@ class GenericAnnotationParser implements ParserInterface
*
* @param string|AnnotationInterface $annotation String class name of an
* AnnotationInterface implementation, or actual instance
* @return GenericAnnotationParser
* @return void
* @throws Exception\InvalidArgumentException
*/
public function registerAnnotation($annotation)
@@ -91,12 +104,12 @@ class GenericAnnotationParser implements ParserInterface
$annotation = new $annotation();
}
if (!$annotation instanceof AnnotationInterface) {
if (! $annotation instanceof AnnotationInterface) {
throw new Exception\InvalidArgumentException(sprintf(
'%s: expects an instance of %s\AnnotationInterface; received "%s"',
__METHOD__,
__NAMESPACE__,
(is_object($annotation) ? get_class($annotation) : gettype($annotation))
is_object($annotation) ? get_class($annotation) : gettype($annotation)
));
}
@@ -122,11 +135,11 @@ class GenericAnnotationParser implements ParserInterface
*/
public function registerAnnotations($annotations)
{
if (!is_array($annotations) && !$annotations instanceof Traversable) {
if (! is_array($annotations) && ! $annotations instanceof Traversable) {
throw new Exception\InvalidArgumentException(sprintf(
'%s: expects an array or Traversable; received "%s"',
__METHOD__,
(is_object($annotations) ? get_class($annotations) : gettype($annotations))
is_object($annotations) ? get_class($annotations) : gettype($annotations)
));
}
@@ -166,7 +179,7 @@ class GenericAnnotationParser implements ParserInterface
*/
public function setAlias($alias, $class)
{
if (!in_array($class, $this->annotationNames) && !$this->hasAlias($class)) {
if (! in_array($class, $this->annotationNames) && ! $this->hasAlias($class)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s: Cannot alias "%s" to "%s", as class "%s" is not currently a registered annotation or alias',
__METHOD__,
@@ -190,7 +203,7 @@ class GenericAnnotationParser implements ParserInterface
*/
protected function normalizeAlias($alias)
{
return strtolower(str_replace(array('-', '_', ' ', '\\', '/'), '', $alias));
return strtolower(str_replace(['-', '_', ' ', '\\', '/'], '', $alias));
}
/**
@@ -203,7 +216,7 @@ class GenericAnnotationParser implements ParserInterface
{
$alias = $this->normalizeAlias($alias);
return (isset($this->aliases[$alias]));
return isset($this->aliases[$alias]);
}
/**

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -0,0 +1,116 @@
<?php
namespace Zend\Code;
use Zend\Code\Exception\InvalidArgumentException;
class DeclareStatement
{
public const TICKS = 'ticks';
public const STRICT_TYPES = 'strict_types';
public const ENCODING = 'encoding';
private const ALLOWED = [
self::TICKS => 'integer',
self::STRICT_TYPES => 'integer',
self::ENCODING => 'string',
];
/**
* @var string
*/
protected $directive;
/**
* @var int|string
*/
protected $value;
private function __construct(string $directive, $value)
{
$this->directive = $directive;
$this->value = $value;
}
/**
* @return string
*/
public function getDirective(): string
{
return $this->directive;
}
/**
* @return int|string
*/
public function getValue()
{
return $this->value;
}
/**
* @param int $value
* @return self
*/
public static function ticks(int $value): self
{
return new self(self::TICKS, $value);
}
/**
* @param int $value
* @return self
*/
public static function strictTypes(int $value): self
{
return new self(self::STRICT_TYPES, $value);
}
/**
* @param string $value
* @return self
*/
public static function encoding(string $value): self
{
return new self(self::ENCODING, $value);
}
public static function fromArray(array $config): self
{
$directive = key($config);
$value = $config[$directive];
if (! isset(self::ALLOWED[$directive])) {
throw new InvalidArgumentException(
sprintf(
'Declare directive must be one of: %s.',
implode(', ', array_keys(self::ALLOWED))
)
);
}
if (gettype($value) !== self::ALLOWED[$directive]) {
throw new InvalidArgumentException(
sprintf(
'Declare value invalid. Expected %s, got %s.',
self::ALLOWED[$directive],
gettype($value)
)
);
}
$method = str_replace('_', '', lcfirst(ucwords($directive, '_')));
return self::{$method}($value);
}
/**
* @return string
*/
public function getStatement(): string
{
$value = is_string($this->value) ? '\'' . $this->value . '\'' : $this->value;
return sprintf('declare(%s=%s);', $this->directive, $value);
}
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,6 +11,13 @@ namespace Zend\Code\Generator;
use Traversable;
use function get_class;
use function gettype;
use function is_array;
use function is_object;
use function method_exists;
use function sprintf;
abstract class AbstractGenerator implements GeneratorInterface
{
/**
@@ -31,12 +38,12 @@ abstract class AbstractGenerator implements GeneratorInterface
/**
* @var string
*/
protected $sourceContent = null;
protected $sourceContent;
/**
* @param array $options
*/
public function __construct($options = array())
public function __construct($options = [])
{
if ($options) {
$this->setOptions($options);
@@ -104,11 +111,11 @@ abstract class AbstractGenerator implements GeneratorInterface
*/
public function setOptions($options)
{
if (!is_array($options) && !$options instanceof Traversable) {
if (! is_array($options) && ! $options instanceof Traversable) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects an array or Traversable object; received "%s"',
__METHOD__,
(is_object($options) ? get_class($options) : gettype($options))
is_object($options) ? get_class($options) : gettype($options)
));
}

View File

@@ -3,12 +3,16 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator;
use function is_array;
use function is_string;
use function sprintf;
abstract class AbstractMemberGenerator extends AbstractGenerator
{
/**#@+
@@ -17,6 +21,7 @@ abstract class AbstractMemberGenerator extends AbstractGenerator
const FLAG_ABSTRACT = 0x01;
const FLAG_FINAL = 0x02;
const FLAG_STATIC = 0x04;
const FLAG_INTERFACE = 0x08;
const FLAG_PUBLIC = 0x10;
const FLAG_PROTECTED = 0x20;
const FLAG_PRIVATE = 0x40;
@@ -31,14 +36,14 @@ abstract class AbstractMemberGenerator extends AbstractGenerator
/**#@-*/
/**
* @var DocBlockGenerator
* @var DocBlockGenerator|null
*/
protected $docBlock = null;
protected $docBlock;
/**
* @var string
*/
protected $name = null;
protected $name;
/**
* @var int
@@ -90,7 +95,7 @@ abstract class AbstractMemberGenerator extends AbstractGenerator
*/
public function setAbstract($isAbstract)
{
return (($isAbstract) ? $this->addFlag(self::FLAG_ABSTRACT) : $this->removeFlag(self::FLAG_ABSTRACT));
return $isAbstract ? $this->addFlag(self::FLAG_ABSTRACT) : $this->removeFlag(self::FLAG_ABSTRACT);
}
/**
@@ -101,13 +106,30 @@ abstract class AbstractMemberGenerator extends AbstractGenerator
return (bool) ($this->flags & self::FLAG_ABSTRACT);
}
/**
* @param bool $isInterface
* @return AbstractMemberGenerator
*/
public function setInterface($isInterface)
{
return $isInterface ? $this->addFlag(self::FLAG_INTERFACE) : $this->removeFlag(self::FLAG_INTERFACE);
}
/**
* @return bool
*/
public function isInterface()
{
return (bool) ($this->flags & self::FLAG_INTERFACE);
}
/**
* @param bool $isFinal
* @return AbstractMemberGenerator
*/
public function setFinal($isFinal)
{
return (($isFinal) ? $this->addFlag(self::FLAG_FINAL) : $this->removeFlag(self::FLAG_FINAL));
return $isFinal ? $this->addFlag(self::FLAG_FINAL) : $this->removeFlag(self::FLAG_FINAL);
}
/**
@@ -124,7 +146,7 @@ abstract class AbstractMemberGenerator extends AbstractGenerator
*/
public function setStatic($isStatic)
{
return (($isStatic) ? $this->addFlag(self::FLAG_STATIC) : $this->removeFlag(self::FLAG_STATIC));
return $isStatic ? $this->addFlag(self::FLAG_STATIC) : $this->removeFlag(self::FLAG_STATIC);
}
/**
@@ -165,9 +187,9 @@ abstract class AbstractMemberGenerator extends AbstractGenerator
public function getVisibility()
{
switch (true) {
case ($this->flags & self::FLAG_PROTECTED):
case $this->flags & self::FLAG_PROTECTED:
return self::VISIBILITY_PROTECTED;
case ($this->flags & self::FLAG_PRIVATE):
case $this->flags & self::FLAG_PRIVATE:
return self::VISIBILITY_PRIVATE;
default:
return self::VISIBILITY_PUBLIC;
@@ -201,7 +223,7 @@ abstract class AbstractMemberGenerator extends AbstractGenerator
{
if (is_string($docBlock)) {
$docBlock = new DocBlockGenerator($docBlock);
} elseif (!$docBlock instanceof DocBlockGenerator) {
} elseif (! $docBlock instanceof DocBlockGenerator) {
throw new Exception\InvalidArgumentException(sprintf(
'%s is expecting either a string, array or an instance of %s\DocBlockGenerator',
__METHOD__,
@@ -214,8 +236,13 @@ abstract class AbstractMemberGenerator extends AbstractGenerator
return $this;
}
public function removeDocBlock(): void
{
$this->docBlock = null;
}
/**
* @return DocBlockGenerator
* @return DocBlockGenerator|null
*/
public function getDocBlock()
{

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -14,7 +14,7 @@ class BodyGenerator extends AbstractGenerator
/**
* @var string
*/
protected $content = null;
protected $content;
/**
* @param string $content

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,9 +11,33 @@ namespace Zend\Code\Generator;
use Zend\Code\Reflection\ClassReflection;
class ClassGenerator extends AbstractGenerator
use function array_diff;
use function array_map;
use function array_pop;
use function array_search;
use function array_values;
use function array_walk;
use function explode;
use function get_class;
use function gettype;
use function implode;
use function in_array;
use function is_array;
use function is_scalar;
use function is_string;
use function ltrim;
use function sprintf;
use function str_replace;
use function strpos;
use function strrpos;
use function strstr;
use function strtolower;
use function substr;
class ClassGenerator extends AbstractGenerator implements TraitUsageInterface
{
const OBJECT_TYPE = "class";
const OBJECT_TYPE = 'class';
const IMPLEMENTS_KEYWORD = 'implements';
const FLAG_ABSTRACT = 0x01;
const FLAG_FINAL = 0x02;
@@ -21,22 +45,22 @@ class ClassGenerator extends AbstractGenerator
/**
* @var FileGenerator
*/
protected $containingFileGenerator = null;
protected $containingFileGenerator;
/**
* @var string
*/
protected $namespaceName = null;
protected $namespaceName;
/**
* @var DocBlockGenerator
*/
protected $docBlock = null;
protected $docBlock;
/**
* @var string
*/
protected $name = null;
protected $name;
/**
* @var bool
@@ -46,27 +70,27 @@ class ClassGenerator extends AbstractGenerator
/**
* @var string
*/
protected $extendedClass = null;
protected $extendedClass;
/**
* @var array Array of string names
*/
protected $implementedInterfaces = array();
protected $implementedInterfaces = [];
/**
* @var PropertyGenerator[] Array of properties
*/
protected $properties = array();
protected $properties = [];
/**
* @var PropertyGenerator[] Array of constants
*/
protected $constants = array();
protected $constants = [];
/**
* @var MethodGenerator[] Array of methods
*/
protected $methods = array();
protected $methods = [];
/**
* @var TraitUsageGenerator Object to encapsulate trait usage logic
@@ -77,7 +101,7 @@ class ClassGenerator extends AbstractGenerator
* Build a Code Generation Php Object from a Class Reflection
*
* @param ClassReflection $classReflection
* @return ClassGenerator
* @return self
*/
public static function fromReflection(ClassReflection $classReflection)
{
@@ -107,7 +131,7 @@ class ClassGenerator extends AbstractGenerator
$interfaces = array_diff($interfaces, $parentClass->getInterfaces());
}
$interfaceNames = array();
$interfaceNames = [];
foreach ($interfaces as $interface) {
/* @var \Zend\Code\Reflection\ClassReflection $interface */
$interfaceNames[] = $interface->getName();
@@ -115,7 +139,7 @@ class ClassGenerator extends AbstractGenerator
$cg->setImplementedInterfaces($interfaceNames);
$properties = array();
$properties = [];
foreach ($classReflection->getProperties() as $reflectionProperty) {
if ($reflectionProperty->getDeclaringClass()->getName() == $classReflection->getName()) {
@@ -125,21 +149,21 @@ class ClassGenerator extends AbstractGenerator
$cg->addProperties($properties);
$constants = array();
$constants = [];
foreach ($classReflection->getConstants() as $name => $value) {
$constants[] = array(
$constants[] = [
'name' => $name,
'value' => $value
);
'value' => $value,
];
}
$cg->addConstants($constants);
$methods = array();
$methods = [];
foreach ($classReflection->getMethods() as $reflectionMethod) {
$className = ($cg->getNamespaceName()) ? $cg->getNamespaceName() . "\\" . $cg->getName() : $cg->getName();
$className = $cg->getNamespaceName() ? $cg->getNamespaceName() . '\\' . $cg->getName() : $cg->getName();
if ($reflectionMethod->getDeclaringClass()->getName() == $className) {
$methods[] = MethodGenerator::fromReflection($reflectionMethod);
@@ -166,11 +190,11 @@ class ClassGenerator extends AbstractGenerator
*
* @throws Exception\InvalidArgumentException
* @param array $array
* @return ClassGenerator
* @return self
*/
public static function fromArray(array $array)
{
if (!isset($array['name'])) {
if (! isset($array['name'])) {
throw new Exception\InvalidArgumentException(
'Class generator requires that a name is provided for this object'
);
@@ -179,7 +203,7 @@ class ClassGenerator extends AbstractGenerator
$cg = new static($array['name']);
foreach ($array as $name => $value) {
// normalize key
switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) {
switch (strtolower(str_replace(['.', '-', '_'], '', $name))) {
case 'containingfile':
$cg->setContainingFileGenerator($value);
break;
@@ -187,7 +211,7 @@ class ClassGenerator extends AbstractGenerator
$cg->setNamespaceName($value);
break;
case 'docblock':
$docBlock = ($value instanceof DocBlockGenerator) ? $value : DocBlockGenerator::fromArray($value);
$docBlock = $value instanceof DocBlockGenerator ? $value : DocBlockGenerator::fromArray($value);
$cg->setDocBlock($docBlock);
break;
case 'flags':
@@ -226,9 +250,9 @@ class ClassGenerator extends AbstractGenerator
$namespaceName = null,
$flags = null,
$extends = null,
$interfaces = array(),
$properties = array(),
$methods = array(),
$interfaces = [],
$properties = [],
$methods = [],
$docBlock = null
) {
$this->traitUsageGenerator = new TraitUsageGenerator($this);
@@ -242,7 +266,7 @@ class ClassGenerator extends AbstractGenerator
if ($flags !== null) {
$this->setFlags($flags);
}
if ($properties !== array()) {
if ($properties !== []) {
$this->addProperties($properties);
}
if ($extends !== null) {
@@ -251,7 +275,7 @@ class ClassGenerator extends AbstractGenerator
if (is_array($interfaces)) {
$this->setImplementedInterfaces($interfaces);
}
if ($methods !== array()) {
if ($methods !== []) {
$this->addMethods($methods);
}
if ($docBlock !== null) {
@@ -261,11 +285,11 @@ class ClassGenerator extends AbstractGenerator
/**
* @param string $name
* @return ClassGenerator
* @return self
*/
public function setName($name)
{
if (strstr($name, '\\')) {
if (false !== strpos($name, '\\')) {
$namespace = substr($name, 0, strrpos($name, '\\'));
$name = substr($name, strrpos($name, '\\') + 1);
$this->setNamespaceName($namespace);
@@ -285,7 +309,7 @@ class ClassGenerator extends AbstractGenerator
/**
* @param string $namespaceName
* @return ClassGenerator
* @return self
*/
public function setNamespaceName($namespaceName)
{
@@ -303,7 +327,7 @@ class ClassGenerator extends AbstractGenerator
/**
* @param FileGenerator $fileGenerator
* @return ClassGenerator
* @return self
*/
public function setContainingFileGenerator(FileGenerator $fileGenerator)
{
@@ -321,7 +345,7 @@ class ClassGenerator extends AbstractGenerator
/**
* @param DocBlockGenerator $docBlock
* @return ClassGenerator
* @return self
*/
public function setDocBlock(DocBlockGenerator $docBlock)
{
@@ -339,7 +363,7 @@ class ClassGenerator extends AbstractGenerator
/**
* @param array|string $flags
* @return ClassGenerator
* @return self
*/
public function setFlags($flags)
{
@@ -358,7 +382,7 @@ class ClassGenerator extends AbstractGenerator
/**
* @param string $flag
* @return ClassGenerator
* @return self
*/
public function addFlag($flag)
{
@@ -368,7 +392,7 @@ class ClassGenerator extends AbstractGenerator
/**
* @param string $flag
* @return ClassGenerator
* @return self
*/
public function removeFlag($flag)
{
@@ -378,11 +402,11 @@ class ClassGenerator extends AbstractGenerator
/**
* @param bool $isAbstract
* @return ClassGenerator
* @return self
*/
public function setAbstract($isAbstract)
{
return (($isAbstract) ? $this->addFlag(self::FLAG_ABSTRACT) : $this->removeFlag(self::FLAG_ABSTRACT));
return $isAbstract ? $this->addFlag(self::FLAG_ABSTRACT) : $this->removeFlag(self::FLAG_ABSTRACT);
}
/**
@@ -395,11 +419,11 @@ class ClassGenerator extends AbstractGenerator
/**
* @param bool $isFinal
* @return ClassGenerator
* @return self
*/
public function setFinal($isFinal)
{
return (($isFinal) ? $this->addFlag(self::FLAG_FINAL) : $this->removeFlag(self::FLAG_FINAL));
return $isFinal ? $this->addFlag(self::FLAG_FINAL) : $this->removeFlag(self::FLAG_FINAL);
}
/**
@@ -407,12 +431,12 @@ class ClassGenerator extends AbstractGenerator
*/
public function isFinal()
{
return ($this->flags & self::FLAG_FINAL);
return $this->flags & self::FLAG_FINAL;
}
/**
* @param string $extendedClass
* @return ClassGenerator
* @return self
*/
public function setExtendedClass($extendedClass)
{
@@ -428,12 +452,33 @@ class ClassGenerator extends AbstractGenerator
return $this->extendedClass;
}
/**
* @return bool
*/
public function hasExtentedClass()
{
return ! empty($this->extendedClass);
}
/**
* @return self
*/
public function removeExtentedClass()
{
$this->setExtendedClass(null);
return $this;
}
/**
* @param array $implementedInterfaces
* @return ClassGenerator
* @return self
*/
public function setImplementedInterfaces(array $implementedInterfaces)
{
array_map(function ($implementedInterface) {
return (string) TypeGenerator::fromTypeString($implementedInterface);
}, $implementedInterfaces);
$this->implementedInterfaces = $implementedInterfaces;
return $this;
}
@@ -446,9 +491,29 @@ class ClassGenerator extends AbstractGenerator
return $this->implementedInterfaces;
}
/**
* @param string $implementedInterface
* @return bool
*/
public function hasImplementedInterface($implementedInterface)
{
$implementedInterface = (string) TypeGenerator::fromTypeString($implementedInterface);
return in_array($implementedInterface, $this->implementedInterfaces);
}
/**
* @param string $implementedInterface
* @return self
*/
public function removeImplementedInterface($implementedInterface)
{
$implementedInterface = (string) TypeGenerator::fromTypeString($implementedInterface);
unset($this->implementedInterfaces[array_search($implementedInterface, $this->implementedInterfaces)]);
return $this;
}
/**
* @param string $constantName
*
* @return PropertyGenerator|false
*/
public function getConstant($constantName)
@@ -468,6 +533,17 @@ class ClassGenerator extends AbstractGenerator
return $this->constants;
}
/**
* @param string $constantName
* @return self
*/
public function removeConstant($constantName)
{
unset($this->constants[$constantName]);
return $this;
}
/**
* @param string $constantName
* @return bool
@@ -482,7 +558,7 @@ class ClassGenerator extends AbstractGenerator
*
* @param PropertyGenerator $constant
* @throws Exception\InvalidArgumentException
* @return ClassGenerator
* @return self
*/
public function addConstantFromGenerator(PropertyGenerator $constant)
{
@@ -510,34 +586,33 @@ class ClassGenerator extends AbstractGenerator
/**
* Add Constant
*
* @param string $name
* @param string $value
* @param string $name Non-empty string
* @param string|int|null|float|array $value Scalar
*
* @throws Exception\InvalidArgumentException
* @return ClassGenerator
*
* @return self
*/
public function addConstant($name, $value)
{
if (!is_string($name)) {
if (empty($name) || ! is_string($name)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects string for name',
__METHOD__
));
}
if (empty($value) || !is_string($value)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects value for constant, value must be a string',
__METHOD__
));
}
$this->validateConstantValue($value);
return $this->addConstantFromGenerator(new PropertyGenerator($name, $value, PropertyGenerator::FLAG_CONSTANT));
return $this->addConstantFromGenerator(
new PropertyGenerator($name, new PropertyValueGenerator($value), PropertyGenerator::FLAG_CONSTANT)
);
}
/**
* @param PropertyGenerator[]|array[] $constants
*
* @return ClassGenerator
* @return self
*/
public function addConstants(array $constants)
{
@@ -546,7 +621,7 @@ class ClassGenerator extends AbstractGenerator
$this->addPropertyFromGenerator($constant);
} else {
if (is_array($constant)) {
call_user_func_array(array($this, 'addConstant'), $constant);
$this->addConstant(...array_values($constant));
}
}
}
@@ -556,7 +631,7 @@ class ClassGenerator extends AbstractGenerator
/**
* @param array $properties
* @return ClassGenerator
* @return self
*/
public function addProperties(array $properties)
{
@@ -567,7 +642,7 @@ class ClassGenerator extends AbstractGenerator
if (is_string($property)) {
$this->addProperty($property);
} elseif (is_array($property)) {
call_user_func_array(array($this, 'addProperty'), $property);
$this->addProperty(...array_values($property));
}
}
}
@@ -582,11 +657,11 @@ class ClassGenerator extends AbstractGenerator
* @param string|array $defaultValue
* @param int $flags
* @throws Exception\InvalidArgumentException
* @return ClassGenerator
* @return self
*/
public function addProperty($name, $defaultValue = null, $flags = PropertyGenerator::FLAG_PUBLIC)
{
if (!is_string($name)) {
if (! is_string($name)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s::%s expects string for name',
get_class($this),
@@ -608,7 +683,7 @@ class ClassGenerator extends AbstractGenerator
*
* @param PropertyGenerator $property
* @throws Exception\InvalidArgumentException
* @return ClassGenerator
* @return self
*/
public function addPropertyFromGenerator(PropertyGenerator $property)
{
@@ -659,7 +734,7 @@ class ClassGenerator extends AbstractGenerator
*
* @param string $use
* @param string|null $useAlias
* @return ClassGenerator
* @return self
*/
public function addUse($use, $useAlias = null)
{
@@ -667,6 +742,44 @@ class ClassGenerator extends AbstractGenerator
return $this;
}
/**
* @param string $use
* @return bool
*/
public function hasUse($use)
{
return $this->traitUsageGenerator->hasUse($use);
}
/**
* @param string $use
* @return self
*/
public function removeUse($use)
{
$this->traitUsageGenerator->removeUse($use);
return $this;
}
/**
* @param string $use
* @return bool
*/
public function hasUseAlias($use)
{
return $this->traitUsageGenerator->hasUseAlias($use);
}
/**
* @param string $use
* @return self
*/
public function removeUseAlias($use)
{
$this->traitUsageGenerator->removeUseAlias($use);
return $this;
}
/**
* Returns the "use" classes
*
@@ -677,6 +790,17 @@ class ClassGenerator extends AbstractGenerator
return $this->traitUsageGenerator->getUses();
}
/**
* @param string $propertyName
* @return self
*/
public function removeProperty($propertyName)
{
unset($this->properties[$propertyName]);
return $this;
}
/**
* @param string $propertyName
* @return bool
@@ -688,7 +812,7 @@ class ClassGenerator extends AbstractGenerator
/**
* @param array $methods
* @return ClassGenerator
* @return self
*/
public function addMethods(array $methods)
{
@@ -699,7 +823,7 @@ class ClassGenerator extends AbstractGenerator
if (is_string($method)) {
$this->addMethod($method);
} elseif (is_array($method)) {
call_user_func_array(array($this, 'addMethod'), $method);
$this->addMethod(...array_values($method));
}
}
}
@@ -716,16 +840,16 @@ class ClassGenerator extends AbstractGenerator
* @param string $body
* @param string $docBlock
* @throws Exception\InvalidArgumentException
* @return ClassGenerator
* @return self
*/
public function addMethod(
$name = null,
array $parameters = array(),
$name,
array $parameters = [],
$flags = MethodGenerator::FLAG_PUBLIC,
$body = null,
$docBlock = null
) {
if (!is_string($name)) {
if (! is_string($name)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s::%s expects string for name',
get_class($this),
@@ -741,7 +865,7 @@ class ClassGenerator extends AbstractGenerator
*
* @param MethodGenerator $method
* @throws Exception\InvalidArgumentException
* @return ClassGenerator
* @return self
*/
public function addMethodFromGenerator(MethodGenerator $method)
{
@@ -777,13 +901,11 @@ class ClassGenerator extends AbstractGenerator
/**
* @param string $methodName
* @return ClassGenerator
* @return self
*/
public function removeMethod($methodName)
{
if ($this->hasMethod($methodName)) {
unset($this->methods[strtolower($methodName)]);
}
unset($this->methods[strtolower($methodName)]);
return $this;
}
@@ -798,7 +920,7 @@ class ClassGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function addTrait($trait)
{
@@ -807,7 +929,7 @@ class ClassGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function addTraits(array $traits)
{
@@ -816,7 +938,7 @@ class ClassGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function hasTrait($traitName)
{
@@ -824,7 +946,7 @@ class ClassGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function getTraits()
{
@@ -832,7 +954,7 @@ class ClassGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function removeTrait($traitName)
{
@@ -840,7 +962,7 @@ class ClassGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function addTraitAlias($method, $alias, $visibility = null)
{
@@ -849,7 +971,7 @@ class ClassGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function getTraitAliases()
{
@@ -857,7 +979,7 @@ class ClassGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function addTraitOverride($method, $traitsToReplace)
{
@@ -866,7 +988,7 @@ class ClassGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function removeTraitOverride($method, $overridesToRemove = null)
{
@@ -876,7 +998,7 @@ class ClassGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function getTraitOverrides()
{
@@ -908,13 +1030,13 @@ class ClassGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\GeneratorInterface
* @inheritDoc
*/
public function generate()
{
if (!$this->isSourceDirty()) {
if (! $this->isSourceDirty()) {
$output = $this->getSourceContent();
if (!empty($output)) {
if (! empty($output)) {
return $output;
}
}
@@ -928,7 +1050,7 @@ class ClassGenerator extends AbstractGenerator
$uses = $this->getUses();
if (!empty($uses)) {
if (! empty($uses)) {
foreach ($uses as $use) {
$output .= 'use ' . $use . ';' . self::LINE_FEED;
}
@@ -949,14 +1071,15 @@ class ClassGenerator extends AbstractGenerator
$output .= static::OBJECT_TYPE . ' ' . $this->getName();
if (!empty($this->extendedClass)) {
$output .= ' extends ' . $this->extendedClass;
if (! empty($this->extendedClass)) {
$output .= ' extends ' . $this->generateShortOrCompleteClassname($this->extendedClass);
}
$implemented = $this->getImplementedInterfaces();
if (!empty($implemented)) {
$output .= ' implements ' . implode(', ', $implemented);
if (! empty($implemented)) {
$implemented = array_map([$this, 'generateShortOrCompleteClassname'], $implemented);
$output .= ' ' . static::IMPLEMENTS_KEYWORD . ' ' . implode(', ', $implemented);
}
$output .= self::LINE_FEED . '{' . self::LINE_FEED . self::LINE_FEED;
@@ -984,4 +1107,63 @@ class ClassGenerator extends AbstractGenerator
return $output;
}
/**
* @param mixed $value
*
* @return void
*
* @throws Exception\InvalidArgumentException
*/
private function validateConstantValue($value)
{
if (null === $value || is_scalar($value)) {
return;
}
if (is_array($value)) {
array_walk($value, [$this, 'validateConstantValue']);
return;
}
throw new Exception\InvalidArgumentException(sprintf(
'Expected value for constant, value must be a "scalar" or "null", "%s" found',
gettype($value)
));
}
/**
* @param string $fqnClassName
*
* @return string
*/
private function generateShortOrCompleteClassname($fqnClassName)
{
$fqnClassName = ltrim($fqnClassName, '\\');
$parts = explode('\\', $fqnClassName);
$className = array_pop($parts);
$classNamespace = implode('\\', $parts);
$currentNamespace = (string) $this->getNamespaceName();
if ($this->hasUseAlias($fqnClassName)) {
return $this->traitUsageGenerator->getUseAlias($fqnClassName);
}
if ($this->hasUseAlias($classNamespace)) {
$namespaceAlias = $this->traitUsageGenerator->getUseAlias($classNamespace);
return $namespaceAlias . '\\' . $className;
}
if ($this->traitUsageGenerator->isUseAlias($fqnClassName)) {
return $fqnClassName;
}
if ($this->traitUsageGenerator->isUseAlias($classNamespace)) {
return $fqnClassName;
}
if ($classNamespace === $currentNamespace || in_array($fqnClassName, $this->getUses())) {
return $className;
}
return '\\' . $fqnClassName;
}
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,9 +11,14 @@ namespace Zend\Code\Generator\DocBlock\Tag;
use Zend\Code\Generator\AbstractGenerator;
use function explode;
use function implode;
use function is_string;
/**
* This abstract class can be used as parent for all tags
* that use a type part in their content.
*
* @see http://www.phpdoc.org/docs/latest/for-users/phpdoc/types.html
*/
abstract class AbstractTypeableTag extends AbstractGenerator
@@ -21,31 +26,31 @@ abstract class AbstractTypeableTag extends AbstractGenerator
/**
* @var string
*/
protected $description = null;
protected $description;
/**
* @var array
*/
protected $types = array();
protected $types = [];
/**
* @param array $types
* @param string $description
* @param string|string[] $types
* @param string $description
*/
public function __construct($types = array(), $description = null)
public function __construct($types = [], $description = null)
{
if (!empty($types)) {
if (! empty($types)) {
$this->setTypes($types);
}
if (!empty($description)) {
if (! empty($description)) {
$this->setDescription($description);
}
}
/**
* @param string $description
* @return ReturnTag
* @return AbstractTypeableTag
*/
public function setDescription($description)
{
@@ -66,7 +71,7 @@ abstract class AbstractTypeableTag extends AbstractGenerator
* e.g. array('int', 'null') or "int|null"
*
* @param array|string $types
* @return ReturnTag
* @return AbstractTypeableTag
*/
public function setTypes($types)
{

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -18,12 +18,12 @@ class AuthorTag extends AbstractGenerator implements TagInterface
/**
* @var string
*/
protected $authorName = null;
protected $authorName;
/**
* @var string
*/
protected $authorEmail = null;
protected $authorEmail;
/**
* @param string $authorName
@@ -31,18 +31,18 @@ class AuthorTag extends AbstractGenerator implements TagInterface
*/
public function __construct($authorName = null, $authorEmail = null)
{
if (!empty($authorName)) {
if (! empty($authorName)) {
$this->setAuthorName($authorName);
}
if (!empty($authorEmail)) {
if (! empty($authorEmail)) {
$this->setAuthorEmail($authorEmail);
}
}
/**
* @param ReflectionTagInterface $reflectionTag
* @return ReturnTag
* @return AuthorTag
* @deprecated Deprecated in 2.3. Use TagManager::createTagFromReflection() instead
*/
public static function fromReflection(ReflectionTagInterface $reflectionTag)
@@ -102,8 +102,8 @@ class AuthorTag extends AbstractGenerator implements TagInterface
public function generate()
{
$output = '@author'
. ((!empty($this->authorName)) ? ' ' . $this->authorName : '')
. ((!empty($this->authorEmail)) ? ' <' . $this->authorEmail . '>' : '');
. (! empty($this->authorName) ? ' ' . $this->authorName : '')
. (! empty($this->authorEmail) ? ' <' . $this->authorEmail . '>' : '');
return $output;
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -12,17 +12,19 @@ namespace Zend\Code\Generator\DocBlock\Tag;
use Zend\Code\Generator\AbstractGenerator;
use Zend\Code\Generic\Prototype\PrototypeGenericInterface;
use function ltrim;
class GenericTag extends AbstractGenerator implements TagInterface, PrototypeGenericInterface
{
/**
* @var string
*/
protected $name = null;
protected $name;
/**
* @var string
*/
protected $content = null;
protected $content;
/**
* @param string $name
@@ -30,11 +32,11 @@ class GenericTag extends AbstractGenerator implements TagInterface, PrototypeGen
*/
public function __construct($name = null, $content = null)
{
if (!empty($name)) {
if (! empty($name)) {
$this->setName($name);
}
if (!empty($content)) {
if (! empty($content)) {
$this->setContent($content);
}
}
@@ -81,7 +83,7 @@ class GenericTag extends AbstractGenerator implements TagInterface, PrototypeGen
public function generate()
{
$output = '@' . $this->name
. ((!empty($this->content)) ? ' ' . $this->content : '');
. (! empty($this->content) ? ' ' . $this->content : '');
return $output;
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -18,12 +18,12 @@ class LicenseTag extends AbstractGenerator implements TagInterface
/**
* @var string
*/
protected $url = null;
protected $url;
/**
* @var string
*/
protected $licenseName = null;
protected $licenseName;
/**
* @param string $url
@@ -31,11 +31,11 @@ class LicenseTag extends AbstractGenerator implements TagInterface
*/
public function __construct($url = null, $licenseName = null)
{
if (!empty($url)) {
if (! empty($url)) {
$this->setUrl($url);
}
if (!empty($licenseName)) {
if (! empty($licenseName)) {
$this->setLicenseName($licenseName);
}
}
@@ -102,8 +102,8 @@ class LicenseTag extends AbstractGenerator implements TagInterface
public function generate()
{
$output = '@license'
. ((!empty($this->url)) ? ' ' . $this->url : '')
. ((!empty($this->licenseName)) ? ' ' . $this->licenseName : '');
. (! empty($this->url) ? ' ' . $this->url : '')
. (! empty($this->licenseName) ? ' ' . $this->licenseName : '');
return $output;
}

View File

@@ -3,18 +3,20 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator\DocBlock\Tag;
use function rtrim;
class MethodTag extends AbstractTypeableTag implements TagInterface
{
/**
* @var string
*/
protected $methodName = null;
protected $methodName;
/**
* @var bool
@@ -27,9 +29,9 @@ class MethodTag extends AbstractTypeableTag implements TagInterface
* @param string $description
* @param bool $isStatic
*/
public function __construct($methodName = null, $types = array(), $description = null, $isStatic = false)
public function __construct($methodName = null, $types = [], $description = null, $isStatic = false)
{
if (!empty($methodName)) {
if (! empty($methodName)) {
$this->setMethodName($methodName);
}
@@ -47,7 +49,7 @@ class MethodTag extends AbstractTypeableTag implements TagInterface
}
/**
* @param boolean $isStatic
* @param bool $isStatic
* @return MethodTag
*/
public function setIsStatic($isStatic)
@@ -57,7 +59,7 @@ class MethodTag extends AbstractTypeableTag implements TagInterface
}
/**
* @return boolean
* @return bool
*/
public function isStatic()
{
@@ -88,10 +90,10 @@ class MethodTag extends AbstractTypeableTag implements TagInterface
public function generate()
{
$output = '@method'
. (($this->isStatic) ? ' static' : '')
. ((!empty($this->types)) ? ' ' . $this->getTypesAsString() : '')
. ((!empty($this->methodName)) ? ' ' . $this->methodName . '()' : '')
. ((!empty($this->description)) ? ' ' . $this->description : '');
. ($this->isStatic ? ' static' : '')
. (! empty($this->types) ? ' ' . $this->getTypesAsString() : '')
. (! empty($this->methodName) ? ' ' . $this->methodName . '()' : '')
. (! empty($this->description) ? ' ' . $this->description : '');
return $output;
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -12,21 +12,23 @@ namespace Zend\Code\Generator\DocBlock\Tag;
use Zend\Code\Generator\DocBlock\TagManager;
use Zend\Code\Reflection\DocBlock\Tag\TagInterface as ReflectionTagInterface;
use function ltrim;
class ParamTag extends AbstractTypeableTag implements TagInterface
{
/**
* @var string
*/
protected $variableName = null;
protected $variableName;
/**
* @param string $variableName
* @param array $types
* @param string $description
*/
public function __construct($variableName = null, $types = array(), $description = null)
public function __construct($variableName = null, $types = [], $description = null)
{
if (!empty($variableName)) {
if (! empty($variableName)) {
$this->setVariableName($variableName);
}
@@ -35,7 +37,7 @@ class ParamTag extends AbstractTypeableTag implements TagInterface
/**
* @param ReflectionTagInterface $reflectionTag
* @return ReturnTag
* @return ParamTag
* @deprecated Deprecated in 2.3. Use TagManager::createTagFromReflection() instead
*/
public static function fromReflection(ReflectionTagInterface $reflectionTag)
@@ -73,7 +75,7 @@ class ParamTag extends AbstractTypeableTag implements TagInterface
/**
* @param string $datatype
* @return ReturnTag
* @return ParamTag
* @deprecated Deprecated in 2.3. Use setTypes() instead
*/
public function setDatatype($datatype)
@@ -115,9 +117,9 @@ class ParamTag extends AbstractTypeableTag implements TagInterface
public function generate()
{
$output = '@param'
. ((!empty($this->types)) ? ' ' . $this->getTypesAsString() : '')
. ((!empty($this->variableName)) ? ' $' . $this->variableName : '')
. ((!empty($this->description)) ? ' ' . $this->description : '');
. (! empty($this->types) ? ' ' . $this->getTypesAsString() : '')
. (! empty($this->variableName) ? ' $' . $this->variableName : '')
. (! empty($this->description) ? ' ' . $this->description : '');
return $output;
}

View File

@@ -3,27 +3,29 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator\DocBlock\Tag;
use function ltrim;
class PropertyTag extends AbstractTypeableTag implements TagInterface
{
/**
* @var string
*/
protected $propertyName = null;
protected $propertyName;
/**
* @param string $propertyName
* @param array $types
* @param string $description
*/
public function __construct($propertyName = null, $types = array(), $description = null)
public function __construct($propertyName = null, $types = [], $description = null)
{
if (!empty($propertyName)) {
if (! empty($propertyName)) {
$this->setPropertyName($propertyName);
}
@@ -62,9 +64,9 @@ class PropertyTag extends AbstractTypeableTag implements TagInterface
public function generate()
{
$output = '@property'
. ((!empty($this->types)) ? ' ' . $this->getTypesAsString() : '')
. ((!empty($this->propertyName)) ? ' $' . $this->propertyName : '')
. ((!empty($this->description)) ? ' ' . $this->description : '');
. (! empty($this->types) ? ' ' . $this->getTypesAsString() : '')
. (! empty($this->propertyName) ? ' $' . $this->propertyName : '')
. (! empty($this->description) ? ' ' . $this->description : '');
return $output;
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -60,7 +60,7 @@ class ReturnTag extends AbstractTypeableTag implements TagInterface
{
$output = '@return '
. $this->getTypesAsString()
. ((!empty($this->description)) ? ' ' . $this->description : '');
. (! empty($this->description) ? ' ' . $this->description : '');
return $output;
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -25,8 +25,8 @@ class ThrowsTag extends AbstractTypeableTag implements TagInterface
public function generate()
{
$output = '@throws'
. ((!empty($this->types)) ? ' ' . $this->getTypesAsString() : '')
. ((!empty($this->description)) ? ' ' . $this->description : '');
. (! empty($this->types) ? ' ' . $this->getTypesAsString() : '')
. (! empty($this->description) ? ' ' . $this->description : '');
return $output;
}

View File

@@ -0,0 +1,68 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator\DocBlock\Tag;
class VarTag extends AbstractTypeableTag implements TagInterface
{
/**
* @var string|null
*/
private $variableName;
/**
* @param string|null $variableName
* @param string|string[] $types
* @param string|null $description
*/
public function __construct(?string $variableName = null, $types = [], ?string $description = null)
{
if (null !== $variableName) {
$this->variableName = ltrim($variableName, '$');
}
parent::__construct($types, $description);
}
/**
* {@inheritDoc}
*/
public function getName() : string
{
return 'var';
}
/**
* @internal this code is only public for compatibility with the
* @see \Zend\Code\Generator\DocBlock\TagManager, which
* uses setters
*/
public function setVariableName(?string $variableName) : void
{
if (null !== $variableName) {
$this->variableName = ltrim($variableName, '$');
}
}
public function getVariableName() : ?string
{
return $this->variableName;
}
/**
* {@inheritDoc}
*/
public function generate() : string
{
return '@var'
. ((! empty($this->types)) ? ' ' . $this->getTypesAsString() : '')
. (null !== $this->variableName ? ' $' . $this->variableName : '')
. ((! empty($this->description)) ? ' ' . $this->description : '');
}
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -13,6 +13,11 @@ use Zend\Code\Generator\DocBlock\Tag\TagInterface;
use Zend\Code\Generic\Prototype\PrototypeClassFactory;
use Zend\Code\Reflection\DocBlock\Tag\TagInterface as ReflectionTagInterface;
use function method_exists;
use function substr;
use function strpos;
use function ucfirst;
/**
* This class is used in DocBlockGenerator and creates the needed
* Tag classes depending on the tag. So for example an @author tag
@@ -35,6 +40,7 @@ class TagManager extends PrototypeClassFactory
$this->addPrototype(new Tag\AuthorTag());
$this->addPrototype(new Tag\LicenseTag());
$this->addPrototype(new Tag\ThrowsTag());
$this->addPrototype(new Tag\VarTag());
$this->setGenericPrototype(new Tag\GenericTag());
}
@@ -52,12 +58,12 @@ class TagManager extends PrototypeClassFactory
// transport any properties via accessors and mutators from reflection to codegen object
$reflectionClass = new \ReflectionClass($reflectionTag);
foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
if (substr($method->getName(), 0, 3) == 'get') {
if (0 === strpos($method->getName(), 'get')) {
$propertyName = substr($method->getName(), 3);
if (method_exists($newTag, 'set' . $propertyName)) {
$newTag->{'set' . $propertyName}($reflectionTag->{'get' . $propertyName}());
}
} elseif (substr($method->getName(), 0, 2) == 'is') {
} elseif (0 === strpos($method->getName(), 'is')) {
$propertyName = ucfirst($method->getName());
if (method_exists($newTag, 'set' . $propertyName)) {
$newTag->{'set' . $propertyName}($reflectionTag->{$method->getName()}());

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -14,22 +14,30 @@ use Zend\Code\Generator\DocBlock\Tag\TagInterface;
use Zend\Code\Generator\DocBlock\TagManager;
use Zend\Code\Reflection\DocBlockReflection;
use function explode;
use function is_array;
use function sprintf;
use function str_replace;
use function strtolower;
use function trim;
use function wordwrap;
class DocBlockGenerator extends AbstractGenerator
{
/**
* @var string
*/
protected $shortDescription = null;
protected $shortDescription;
/**
* @var string
*/
protected $longDescription = null;
protected $longDescription;
/**
* @var array
*/
protected $tags = array();
protected $tags = [];
/**
* @var string
@@ -41,6 +49,9 @@ class DocBlockGenerator extends AbstractGenerator
*/
protected $wordwrap = true;
/**
* @var TagManager
*/
protected static $tagManager;
/**
@@ -83,7 +94,7 @@ class DocBlockGenerator extends AbstractGenerator
foreach ($array as $name => $value) {
// normalize key
switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) {
switch (strtolower(str_replace(['.', '-', '_'], '', $name))) {
case 'shortdescription':
$docBlock->setShortDescription($value);
break;
@@ -99,9 +110,12 @@ class DocBlockGenerator extends AbstractGenerator
return $docBlock;
}
/**
* @return TagManager
*/
protected static function getTagManager()
{
if (!isset(static::$tagManager)) {
if (! isset(static::$tagManager)) {
static::$tagManager = new TagManager();
static::$tagManager->initializeDefaultTags();
}
@@ -113,7 +127,7 @@ class DocBlockGenerator extends AbstractGenerator
* @param string $longDescription
* @param array $tags
*/
public function __construct($shortDescription = null, $longDescription = null, array $tags = array())
public function __construct($shortDescription = null, $longDescription = null, array $tags = [])
{
if ($shortDescription) {
$this->setShortDescription($shortDescription);
@@ -183,11 +197,11 @@ class DocBlockGenerator extends AbstractGenerator
public function setTag($tag)
{
if (is_array($tag)) {
// use deprecated Tag class for backward compatiblity to old array-keys
// use deprecated Tag class for backward compatibility to old array-keys
$genericTag = new Tag();
$genericTag->setOptions($tag);
$tag = $genericTag;
} elseif (!$tag instanceof TagInterface) {
} elseif (! $tag instanceof TagInterface) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects either an array of method options or an instance of %s\DocBlock\Tag\TagInterface',
__METHOD__,
@@ -230,7 +244,7 @@ class DocBlockGenerator extends AbstractGenerator
*/
public function generate()
{
if (!$this->isSourceDirty()) {
if (! $this->isSourceDirty()) {
return $this->docCommentize(trim($this->getSourceContent()));
}
@@ -263,7 +277,7 @@ class DocBlockGenerator extends AbstractGenerator
foreach ($lines as $line) {
$output .= $indent . ' *';
if ($line) {
$output .= " $line";
$output .= ' ' . $line;
}
$output .= self::LINE_FEED;
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,51 +3,81 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator;
use Zend\Code\DeclareStatement;
use Zend\Code\Exception\InvalidArgumentException;
use Zend\Code\Reflection\Exception as ReflectionException;
use Zend\Code\Reflection\FileReflection;
use function array_key_exists;
use function array_merge;
use function count;
use function current;
use function dirname;
use function file_put_contents;
use function in_array;
use function is_array;
use function is_string;
use function is_writable;
use function method_exists;
use function preg_match;
use function preg_replace;
use function property_exists;
use function reset;
use function sprintf;
use function str_repeat;
use function str_replace;
use function strrpos;
use function strtolower;
use function substr;
use function token_get_all;
class FileGenerator extends AbstractGenerator
{
/**
* @var string
*/
protected $filename = null;
protected $filename;
/**
* @var DocBlockGenerator
*/
protected $docBlock = null;
protected $docBlock;
/**
* @var array
*/
protected $requiredFiles = array();
protected $requiredFiles = [];
/**
* @var string
*/
protected $namespace = null;
protected $namespace;
/**
* @var array
*/
protected $uses = array();
protected $uses = [];
/**
* @var array
*/
protected $classes = array();
protected $classes = [];
/**
* @var string
*/
protected $body = null;
protected $body;
/**
* @var DeclareStatement[]
*/
protected $declares = [];
/**
* Passes $options to {@link setOptions()}.
@@ -113,7 +143,7 @@ class FileGenerator extends AbstractGenerator
$file->setUses($uses);
}
if (($fileReflection->getDocComment() != '')) {
if ($fileReflection->getDocComment() != '') {
$docBlock = $fileReflection->getDocBlock();
$file->setDocBlock(DocBlockGenerator::fromReflection($docBlock));
}
@@ -127,18 +157,27 @@ class FileGenerator extends AbstractGenerator
*/
public static function fromArray(array $values)
{
$fileGenerator = new static;
$fileGenerator = new static();
foreach ($values as $name => $value) {
switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) {
switch (strtolower(str_replace(['.', '-', '_'], '', $name))) {
case 'filename':
$fileGenerator->setFilename($value);
continue;
break;
case 'class':
$fileGenerator->setClass(($value instanceof ClassGenerator) ? $value : ClassGenerator::fromArray($value));
continue;
$fileGenerator->setClass(
$value instanceof ClassGenerator
? $value
: ClassGenerator::fromArray($value)
);
break;
case 'requiredfiles':
$fileGenerator->setRequiredFiles($value);
continue;
break;
case 'declares':
$fileGenerator->setDeclares(array_map(static function ($directive, $value) {
return DeclareStatement::fromArray([$directive => $value]);
}, array_keys($value), $value));
break;
default:
if (property_exists($fileGenerator, $name)) {
$fileGenerator->{$name} = $value;
@@ -159,12 +198,12 @@ class FileGenerator extends AbstractGenerator
public function setDocBlock($docBlock)
{
if (is_string($docBlock)) {
$docBlock = array('shortDescription' => $docBlock);
$docBlock = ['shortDescription' => $docBlock];
}
if (is_array($docBlock)) {
$docBlock = new DocBlockGenerator($docBlock);
} elseif (!$docBlock instanceof DocBlockGenerator) {
} elseif (! $docBlock instanceof DocBlockGenerator) {
throw new Exception\InvalidArgumentException(sprintf(
'%s is expecting either a string, array or an instance of %s\DocBlockGenerator',
__METHOD__,
@@ -277,8 +316,8 @@ class FileGenerator extends AbstractGenerator
*/
public function setUse($use, $as = null)
{
if (!in_array(array($use, $as), $this->uses)) {
$this->uses[] = array($use, $as);
if (! in_array([$use, $as], $this->uses)) {
$this->uses[] = [$use, $as];
}
return $this;
}
@@ -322,7 +361,7 @@ class FileGenerator extends AbstractGenerator
$class = ClassGenerator::fromArray($class);
} elseif (is_string($class)) {
$class = new ClassGenerator($class);
} elseif (!$class instanceof ClassGenerator) {
} elseif (! $class instanceof ClassGenerator) {
throw new Exception\InvalidArgumentException(sprintf(
'%s is expecting either a string, array or an instance of %s\ClassGenerator',
__METHOD__,
@@ -381,6 +420,25 @@ class FileGenerator extends AbstractGenerator
return $this->body;
}
public function setDeclares(array $declares)
{
foreach ($declares as $declare) {
if (! $declare instanceof DeclareStatement) {
throw new InvalidArgumentException(sprintf(
'%s is expecting an array of %s objects',
__METHOD__,
DeclareStatement::class
));
}
if (! array_key_exists($declare->getDirective(), $this->declares)) {
$this->declares[$declare->getDirective()] = $declare;
}
}
return $this;
}
/**
* @return bool
*/
@@ -425,8 +483,7 @@ class FileGenerator extends AbstractGenerator
if (preg_match('#/\* Zend_Code_Generator_Php_File-(.*?)Marker:#m', $body)) {
$tokens = token_get_all($body);
foreach ($tokens as $token) {
if (is_array($token) && in_array($token[0], array(T_OPEN_TAG, T_COMMENT, T_DOC_COMMENT, T_WHITESPACE))
) {
if (is_array($token) && in_array($token[0], [T_OPEN_TAG, T_COMMENT, T_DOC_COMMENT, T_WHITESPACE])) {
$output .= $token[1];
}
}
@@ -438,7 +495,9 @@ class FileGenerator extends AbstractGenerator
$docBlock->setIndentation('');
if (preg_match('#/\* Zend_Code_Generator_FileGenerator-DocBlockMarker \*/#m', $output)) {
// @codingStandardsIgnoreStart
$output = preg_replace('#/\* Zend_Code_Generator_FileGenerator-DocBlockMarker \*/#m', $docBlock->generate(), $output, 1);
// @codingStandardsIgnoreEnd
} else {
$output .= $docBlock->generate() . self::LINE_FEED;
}
@@ -463,10 +522,32 @@ class FileGenerator extends AbstractGenerator
}
}
// declares, if any
if ($this->declares) {
$declareStatements = '';
foreach ($this->declares as $declare) {
$declareStatements .= $declare->getStatement() . self::LINE_FEED;
}
if (preg_match('#/\* Zend_Code_Generator_FileGenerator-DeclaresMarker \*/#m', $output)) {
$output = preg_replace(
'#/\* Zend_Code_Generator_FileGenerator-DeclaresMarker \*/#m',
$declareStatements,
$output,
1
);
} else {
$output .= $declareStatements;
}
$output .= self::LINE_FEED;
}
// process required files
// @todo marker replacement for required files
$requiredFiles = $this->getRequiredFiles();
if (!empty($requiredFiles)) {
if (! empty($requiredFiles)) {
foreach ($requiredFiles as $requiredFile) {
$output .= 'require_once \'' . $requiredFile . '\';' . self::LINE_FEED;
}
@@ -475,19 +556,19 @@ class FileGenerator extends AbstractGenerator
}
$classes = $this->getClasses();
$classUses = array();
$classUses = [];
//build uses array
foreach ($classes as $class) {
//check for duplicate use statements
$uses = $class->getUses();
if (!empty($uses) && is_array($uses)) {
if (! empty($uses) && is_array($uses)) {
$classUses = array_merge($classUses, $uses);
}
}
// process import statements
$uses = $this->getUses();
if (!empty($uses)) {
if (! empty($uses)) {
$useOutput = '';
foreach ($uses as $use) {
@@ -499,8 +580,8 @@ class FileGenerator extends AbstractGenerator
}
//don't duplicate use statements
if (!in_array($tempOutput, $classUses)) {
$useOutput .= "use ". $tempOutput .";";
if (! in_array($tempOutput, $classUses)) {
$useOutput .= 'use ' . $tempOutput . ';';
$useOutput .= self::LINE_FEED;
}
}
@@ -519,9 +600,11 @@ class FileGenerator extends AbstractGenerator
}
// process classes
if (!empty($classes)) {
if (! empty($classes)) {
foreach ($classes as $class) {
// @codingStandardsIgnoreStart
$regex = str_replace('&', $class->getName(), '/\* Zend_Code_Generator_Php_File-ClassMarker: \{[A-Za-z0-9\\\]+?&\} \*/');
// @codingStandardsIgnoreEnd
if (preg_match('#' . $regex . '#m', $output)) {
$output = preg_replace('#' . $regex . '#', $class->generate(), $output, 1);
} else {
@@ -533,9 +616,9 @@ class FileGenerator extends AbstractGenerator
}
}
if (!empty($body)) {
if (! empty($body)) {
// add an extra space between classes and
if (!empty($classes)) {
if (! empty($classes)) {
$output .= self::LINE_FEED;
}
@@ -551,7 +634,7 @@ class FileGenerator extends AbstractGenerator
*/
public function write()
{
if ($this->filename == '' || !is_writable(dirname($this->filename))) {
if ($this->filename == '' || ! is_writable(dirname($this->filename))) {
throw new Exception\RuntimeException('This code generator object is not writable.');
}
file_put_contents($this->filename, $this->generate());

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,12 +11,14 @@ namespace Zend\Code\Generator;
use Zend\Code\Generator\Exception\RuntimeException;
use function str_replace;
class FileGeneratorRegistry
{
/**
* @var array $fileCodeGenerators
*/
private static $fileCodeGenerators = array();
private static $fileCodeGenerators = [];
/**
* Registry for the Zend\Code package.
@@ -37,7 +39,7 @@ class FileGeneratorRegistry
// cannot use realpath since the file might not exist, but we do need to have the index
// in the same DIRECTORY_SEPARATOR that realpath would use:
$fileName = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $fileName);
$fileName = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $fileName);
static::$fileCodeGenerators[$fileName] = $fileCodeGenerator;
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -0,0 +1,154 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator;
use Zend\Code\Reflection\ClassReflection;
use function sprintf;
use function str_replace;
use function strtolower;
class InterfaceGenerator extends ClassGenerator
{
const OBJECT_TYPE = 'interface';
const IMPLEMENTS_KEYWORD = 'extends';
/**
* Build a Code Generation Php Object from a Class Reflection
*
* @param ClassReflection $classReflection
* @return InterfaceGenerator
*/
public static function fromReflection(ClassReflection $classReflection)
{
if (! $classReflection->isInterface()) {
throw new Exception\InvalidArgumentException(sprintf(
'Class %s is not a interface',
$classReflection->getName()
));
}
// class generator
$cg = new static($classReflection->getName());
$methods = [];
$cg->setSourceContent($cg->getSourceContent());
$cg->setSourceDirty(false);
if ($classReflection->getDocComment() != '') {
$cg->setDocBlock(DocBlockGenerator::fromReflection($classReflection->getDocBlock()));
}
// set the namespace
if ($classReflection->inNamespace()) {
$cg->setNamespaceName($classReflection->getNamespaceName());
}
foreach ($classReflection->getMethods() as $reflectionMethod) {
$className = $cg->getNamespaceName()
? $cg->getNamespaceName() . '\\' . $cg->getName()
: $cg->getName();
if ($reflectionMethod->getDeclaringClass()->getName() == $className) {
$methods[] = MethodGenerator::fromReflection($reflectionMethod);
}
}
foreach ($classReflection->getConstants() as $name => $value) {
$cg->addConstant($name, $value);
}
$cg->addMethods($methods);
return $cg;
}
/**
* Generate from array
*
* @configkey name string [required] Class Name
* @configkey filegenerator FileGenerator File generator that holds this class
* @configkey namespacename string The namespace for this class
* @configkey docblock string The docblock information
* @configkey constants
* @configkey methods
*
* @throws Exception\InvalidArgumentException
* @param array $array
* @return InterfaceGenerator
*/
public static function fromArray(array $array)
{
if (! isset($array['name'])) {
throw new Exception\InvalidArgumentException(
'Class generator requires that a name is provided for this object'
);
}
$cg = new static($array['name']);
foreach ($array as $name => $value) {
// normalize key
switch (strtolower(str_replace(['.', '-', '_'], '', $name))) {
case 'containingfile':
$cg->setContainingFileGenerator($value);
break;
case 'namespacename':
$cg->setNamespaceName($value);
break;
case 'docblock':
$docBlock = $value instanceof DocBlockGenerator ? $value : DocBlockGenerator::fromArray($value);
$cg->setDocBlock($docBlock);
break;
case 'methods':
$cg->addMethods($value);
break;
case 'constants':
$cg->addConstants($value);
break;
}
}
return $cg;
}
/**
* {@inheritDoc}
*/
public function addPropertyFromGenerator(PropertyGenerator $property)
{
return $this;
}
/**
* {@inheritDoc}
*/
public function addMethodFromGenerator(MethodGenerator $method)
{
$method->setInterface(true);
return parent::addMethodFromGenerator($method);
}
/**
* {@inheritDoc}
*/
public function setExtendedClass($extendedClass)
{
return $this;
}
/**
* {@inheritDoc}
*/
public function setAbstract($isAbstract)
{
return $this;
}
}

View File

@@ -3,30 +3,54 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator;
use ReflectionMethod;
use Zend\Code\Reflection\MethodReflection;
use function explode;
use function implode;
use function is_array;
use function is_string;
use function method_exists;
use function preg_replace;
use function sprintf;
use function str_replace;
use function strlen;
use function strtolower;
use function substr;
use function trim;
class MethodGenerator extends AbstractMemberGenerator
{
/**
* @var DocBlockGenerator
*/
protected $docBlock = null;
protected $docBlock;
/**
* @var ParameterGenerator[]
*/
protected $parameters = array();
protected $parameters = [];
/**
* @var string
*/
protected $body = null;
protected $body;
/**
* @var null|TypeGenerator
*/
private $returnType;
/**
* @var bool
*/
private $returnsReference = false;
/**
* @param MethodReflection $reflectionMethod
@@ -34,7 +58,7 @@ class MethodGenerator extends AbstractMemberGenerator
*/
public static function fromReflection(MethodReflection $reflectionMethod)
{
$method = new static();
$method = static::copyMethodSignature($reflectionMethod);
$method->setSourceContent($reflectionMethod->getContents(false));
$method->setSourceDirty(false);
@@ -43,6 +67,23 @@ class MethodGenerator extends AbstractMemberGenerator
$method->setDocBlock(DocBlockGenerator::fromReflection($reflectionMethod->getDocBlock()));
}
$method->setBody(static::clearBodyIndention($reflectionMethod->getBody()));
return $method;
}
/**
* Returns a MethodGenerator based on a MethodReflection with only the signature copied.
*
* This is similar to fromReflection() but without the method body and phpdoc as this is quite heavy to copy.
* It's for example useful when creating proxies where you normally change the method body anyway.
*/
public static function copyMethodSignature(MethodReflection $reflectionMethod): MethodGenerator
{
$method = new static();
$declaringClass = $reflectionMethod->getDeclaringClass();
$method->setReturnType(self::extractReturnTypeFromMethodReflection($reflectionMethod));
$method->setFinal($reflectionMethod->isFinal());
if ($reflectionMethod->isPrivate()) {
@@ -53,16 +94,15 @@ class MethodGenerator extends AbstractMemberGenerator
$method->setVisibility(self::VISIBILITY_PUBLIC);
}
$method->setInterface($declaringClass->isInterface());
$method->setStatic($reflectionMethod->isStatic());
$method->setReturnsReference($reflectionMethod->returnsReference());
$method->setName($reflectionMethod->getName());
foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
$method->setParameter(ParameterGenerator::fromReflection($reflectionParameter));
}
$method->setBody(static::clearBodyIndention($reflectionMethod->getBody()));
return $method;
}
@@ -80,7 +120,7 @@ class MethodGenerator extends AbstractMemberGenerator
return $body;
}
$lines = explode(PHP_EOL, $body);
$lines = explode("\n", $body);
$indention = str_replace(trim($lines[1]), '', $lines[1]);
@@ -90,7 +130,7 @@ class MethodGenerator extends AbstractMemberGenerator
}
}
$body = implode(PHP_EOL, $lines);
$body = implode("\n", $lines);
return $body;
}
@@ -114,7 +154,7 @@ class MethodGenerator extends AbstractMemberGenerator
*/
public static function fromArray(array $array)
{
if (!isset($array['name'])) {
if (! isset($array['name'])) {
throw new Exception\InvalidArgumentException(
'Method generator requires that a name is provided for this object'
);
@@ -123,9 +163,9 @@ class MethodGenerator extends AbstractMemberGenerator
$method = new static($array['name']);
foreach ($array as $name => $value) {
// normalize key
switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) {
switch (strtolower(str_replace(['.', '-', '_'], '', $name))) {
case 'docblock':
$docBlock = ($value instanceof DocBlockGenerator) ? $value : DocBlockGenerator::fromArray($value);
$docBlock = $value instanceof DocBlockGenerator ? $value : DocBlockGenerator::fromArray($value);
$method->setDocBlock($docBlock);
break;
case 'flags':
@@ -143,12 +183,18 @@ class MethodGenerator extends AbstractMemberGenerator
case 'final':
$method->setFinal($value);
break;
case 'interface':
$method->setInterface($value);
break;
case 'static':
$method->setStatic($value);
break;
case 'visibility':
$method->setVisibility($value);
break;
case 'returntype':
$method->setReturnType($value);
break;
}
}
@@ -164,7 +210,7 @@ class MethodGenerator extends AbstractMemberGenerator
*/
public function __construct(
$name = null,
array $parameters = array(),
array $parameters = [],
$flags = self::FLAG_PUBLIC,
$body = null,
$docBlock = null
@@ -214,7 +260,7 @@ class MethodGenerator extends AbstractMemberGenerator
$parameter = ParameterGenerator::fromArray($parameter);
}
if (!$parameter instanceof ParameterGenerator) {
if (! $parameter instanceof ParameterGenerator) {
throw new Exception\InvalidArgumentException(sprintf(
'%s is expecting either a string, array or an instance of %s\ParameterGenerator',
__METHOD__,
@@ -253,6 +299,40 @@ class MethodGenerator extends AbstractMemberGenerator
return $this->body;
}
/**
* @param string|null $returnType
*
* @return MethodGenerator
*/
public function setReturnType($returnType = null)
{
$this->returnType = null === $returnType
? null
: TypeGenerator::fromTypeString($returnType);
return $this;
}
/**
* @return TypeGenerator|null
*/
public function getReturnType()
{
return $this->returnType;
}
/**
* @param bool $returnsReference
*
* @return MethodGenerator
*/
public function setReturnsReference($returnsReference)
{
$this->returnsReference = (bool) $returnsReference;
return $this;
}
/**
* @return string
*/
@@ -272,15 +352,17 @@ class MethodGenerator extends AbstractMemberGenerator
if ($this->isAbstract()) {
$output .= 'abstract ';
} else {
$output .= (($this->isFinal()) ? 'final ' : '');
$output .= $this->isFinal() ? 'final ' : '';
}
$output .= $this->getVisibility()
. (($this->isStatic()) ? ' static' : '')
. ' function ' . $this->getName() . '(';
. ($this->isStatic() ? ' static' : '')
. ' function '
. ($this->returnsReference ? '& ' : '')
. $this->getName() . '(';
$parameters = $this->getParameters();
if (!empty($parameters)) {
if (! empty($parameters)) {
foreach ($parameters as $parameter) {
$parameterOutput[] = $parameter->generate();
}
@@ -290,10 +372,18 @@ class MethodGenerator extends AbstractMemberGenerator
$output .= ')';
if ($this->returnType) {
$output .= ' : ' . $this->returnType->generate();
}
if ($this->isAbstract()) {
return $output . ';';
}
if ($this->isInterface()) {
return $output . ';';
}
$output .= self::LINE_FEED . $indent . '{' . self::LINE_FEED;
if ($this->body) {
@@ -310,4 +400,46 @@ class MethodGenerator extends AbstractMemberGenerator
{
return $this->generate();
}
/**
* @param MethodReflection $methodReflection
*
* @return null|string
*/
private static function extractReturnTypeFromMethodReflection(MethodReflection $methodReflection)
{
$returnType = method_exists($methodReflection, 'getReturnType')
? $methodReflection->getReturnType()
: null;
if (! $returnType) {
return null;
}
if (! method_exists($returnType, 'getName')) {
return self::expandLiteralType((string) $returnType, $methodReflection);
}
return ($returnType->allowsNull() ? '?' : '')
. self::expandLiteralType($returnType->getName(), $methodReflection);
}
/**
* @param string $literalReturnType
* @param ReflectionMethod $methodReflection
*
* @return string
*/
private static function expandLiteralType($literalReturnType, ReflectionMethod $methodReflection)
{
if ('self' === strtolower($literalReturnType)) {
return $methodReflection->getDeclaringClass()->getName();
}
if ('parent' === strtolower($literalReturnType)) {
return $methodReflection->getDeclaringClass()->getParentClass()->getName();
}
return $literalReturnType;
}
}

View File

@@ -3,35 +3,41 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator;
use ReflectionParameter;
use Zend\Code\Reflection\ParameterReflection;
use function is_string;
use function method_exists;
use function str_replace;
use function strtolower;
class ParameterGenerator extends AbstractGenerator
{
/**
* @var string
*/
protected $name = null;
protected $name;
/**
* @var string
* @var TypeGenerator|null
*/
protected $type = null;
protected $type;
/**
* @var string|ValueGenerator
* @var ValueGenerator
*/
protected $defaultValue = null;
protected $defaultValue;
/**
* @var int
*/
protected $position = null;
protected $position;
/**
* @var bool
@@ -39,9 +45,14 @@ class ParameterGenerator extends AbstractGenerator
protected $passedByReference = false;
/**
* @var array
* @var bool
*/
protected static $simple = array('int', 'bool', 'string', 'float', 'resource', 'mixed', 'object');
private $variadic = false;
/**
* @var bool
*/
private $omitDefaultValue = false;
/**
* @param ParameterReflection $reflectionParameter
@@ -50,33 +61,27 @@ class ParameterGenerator extends AbstractGenerator
public static function fromReflection(ParameterReflection $reflectionParameter)
{
$param = new ParameterGenerator();
$param->setName($reflectionParameter->getName());
if ($reflectionParameter->isArray()) {
$param->setType('array');
} elseif (method_exists($reflectionParameter, 'isCallable') && $reflectionParameter->isCallable()) {
$param->setType('callable');
} else {
$typeClass = $reflectionParameter->getClass();
if ($typeClass) {
$parameterType = $typeClass->getName();
$currentNamespace = $reflectionParameter->getDeclaringClass()->getNamespaceName();
if (!empty($currentNamespace) && substr($parameterType, 0, strlen($currentNamespace)) == $currentNamespace) {
$parameterType = substr($parameterType, strlen($currentNamespace) + 1);
} else {
$parameterType = '\\' . trim($parameterType, '\\');
}
$param->setType($parameterType);
}
if ($type = self::extractFQCNTypeFromReflectionType($reflectionParameter)) {
$param->setType($type);
}
$param->setPosition($reflectionParameter->getPosition());
if ($reflectionParameter->isOptional()) {
$param->setDefaultValue($reflectionParameter->getDefaultValue());
$variadic = method_exists($reflectionParameter, 'isVariadic') && $reflectionParameter->isVariadic();
$param->setVariadic($variadic);
if (! $variadic && ($reflectionParameter->isOptional() || $reflectionParameter->isDefaultValueAvailable())) {
try {
$param->setDefaultValue($reflectionParameter->getDefaultValue());
} catch (\ReflectionException $e) {
$param->setDefaultValue(null);
}
}
$param->setPassedByReference($reflectionParameter->isPassedByReference());
return $param;
@@ -85,14 +90,15 @@ class ParameterGenerator extends AbstractGenerator
/**
* Generate from array
*
* @configkey name string [required] Class Name
* @configkey type string
* @configkey defaultvalue null|bool|string|int|float|array|ValueGenerator
* @configkey passedbyreference bool
* @configkey position int
* @configkey sourcedirty bool
* @configkey indentation string
* @configkey sourcecontent string
* @configkey name string [required] Class Name
* @configkey type string
* @configkey defaultvalue null|bool|string|int|float|array|ValueGenerator
* @configkey passedbyreference bool
* @configkey position int
* @configkey sourcedirty bool
* @configkey indentation string
* @configkey sourcecontent string
* @configkey omitdefaultvalue bool
*
* @throws Exception\InvalidArgumentException
* @param array $array
@@ -100,16 +106,16 @@ class ParameterGenerator extends AbstractGenerator
*/
public static function fromArray(array $array)
{
if (!isset($array['name'])) {
if (! isset($array['name'])) {
throw new Exception\InvalidArgumentException(
'Paramerer generator requires that a name is provided for this object'
'Parameter generator requires that a name is provided for this object'
);
}
$param = new static($array['name']);
foreach ($array as $name => $value) {
// normalize key
switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) {
switch (strtolower(str_replace(['.', '-', '_'], '', $name))) {
case 'type':
$param->setType($value);
break;
@@ -131,6 +137,9 @@ class ParameterGenerator extends AbstractGenerator
case 'sourcecontent':
$param->setSourceContent($value);
break;
case 'omitdefaultvalue':
$param->omitDefaultValue($value);
break;
}
}
@@ -174,7 +183,8 @@ class ParameterGenerator extends AbstractGenerator
*/
public function setType($type)
{
$this->type = (string) $type;
$this->type = TypeGenerator::fromTypeString($type);
return $this;
}
@@ -183,7 +193,9 @@ class ParameterGenerator extends AbstractGenerator
*/
public function getType()
{
return $this->type;
return $this->type
? (string) $this->type
: null;
}
/**
@@ -214,7 +226,7 @@ class ParameterGenerator extends AbstractGenerator
*/
public function setDefaultValue($defaultValue)
{
if (!($defaultValue instanceof ValueGenerator)) {
if (! $defaultValue instanceof ValueGenerator) {
$defaultValue = new ValueGenerator($defaultValue);
}
$this->defaultValue = $defaultValue;
@@ -223,7 +235,7 @@ class ParameterGenerator extends AbstractGenerator
}
/**
* @return string
* @return ValueGenerator
*/
public function getDefaultValue()
{
@@ -266,35 +278,146 @@ class ParameterGenerator extends AbstractGenerator
return $this;
}
/**
* @param bool $variadic
*
* @return ParameterGenerator
*/
public function setVariadic($variadic)
{
$this->variadic = (bool) $variadic;
return $this;
}
/**
* @return bool
*/
public function getVariadic()
{
return $this->variadic;
}
/**
* @return string
*/
public function generate()
{
$output = '';
if ($this->type && !in_array($this->type, static::$simple)) {
$output .= $this->type . ' ';
}
$output = $this->generateTypeHint();
if (true === $this->passedByReference) {
$output .= '&';
}
if ($this->variadic) {
$output .= '... ';
}
$output .= '$' . $this->name;
if ($this->defaultValue !== null) {
if ($this->omitDefaultValue) {
return $output;
}
if ($this->defaultValue instanceof ValueGenerator) {
$output .= ' = ';
if (is_string($this->defaultValue)) {
$output .= ValueGenerator::escape($this->defaultValue);
} elseif ($this->defaultValue instanceof ValueGenerator) {
$this->defaultValue->setOutputMode(ValueGenerator::OUTPUT_SINGLE_LINE);
$output .= $this->defaultValue;
} else {
$output .= $this->defaultValue;
}
$this->defaultValue->setOutputMode(ValueGenerator::OUTPUT_SINGLE_LINE);
$output .= $this->defaultValue;
}
return $output;
}
/**
* @param ParameterReflection $reflectionParameter
*
* @return null|string
*/
private static function extractFQCNTypeFromReflectionType(ParameterReflection $reflectionParameter)
{
if (! method_exists($reflectionParameter, 'getType')) {
return self::prePhp7ExtractFQCNTypeFromReflectionType($reflectionParameter);
}
$type = method_exists($reflectionParameter, 'getType')
? $reflectionParameter->getType()
: null;
if (! $type) {
return null;
}
if (! method_exists($type, 'getName')) {
return self::expandLiteralParameterType((string) $type, $reflectionParameter);
}
return ($type->allowsNull() ? '?' : '')
. self::expandLiteralParameterType($type->getName(), $reflectionParameter);
}
/**
* For ancient PHP versions (yes, you should upgrade to 7.0):
*
* @param ParameterReflection $reflectionParameter
*
* @return string|null
*/
private static function prePhp7ExtractFQCNTypeFromReflectionType(ParameterReflection $reflectionParameter)
{
if ($reflectionParameter->isCallable()) {
return 'callable';
}
if ($reflectionParameter->isArray()) {
return 'array';
}
if ($class = $reflectionParameter->getClass()) {
return $class->getName();
}
return null;
}
/**
* @param string $literalParameterType
* @param ReflectionParameter $reflectionParameter
*
* @return string
*/
private static function expandLiteralParameterType($literalParameterType, ReflectionParameter $reflectionParameter)
{
if ('self' === strtolower($literalParameterType)) {
return $reflectionParameter->getDeclaringClass()->getName();
}
if ('parent' === strtolower($literalParameterType)) {
return $reflectionParameter->getDeclaringClass()->getParentClass()->getName();
}
return $literalParameterType;
}
/**
* @return string
*/
private function generateTypeHint()
{
if (null === $this->type) {
return '';
}
return $this->type->generate() . ' ';
}
/**
* @param bool $omit
* @return ParameterGenerator
*/
public function omitDefaultValue(bool $omit = true)
{
$this->omitDefaultValue = $omit;
return $this;
}
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,6 +11,10 @@ namespace Zend\Code\Generator;
use Zend\Code\Reflection\PropertyReflection;
use function sprintf;
use function str_replace;
use function strtolower;
class PropertyGenerator extends AbstractMemberGenerator
{
const FLAG_CONSTANT = 0x08;
@@ -18,12 +22,17 @@ class PropertyGenerator extends AbstractMemberGenerator
/**
* @var bool
*/
protected $isConst = null;
protected $isConst;
/**
* @var PropertyValueGenerator
*/
protected $defaultValue = null;
protected $defaultValue;
/**
* @var bool
*/
private $omitDefaultValue = false;
/**
* @param PropertyReflection $reflectionProperty
@@ -37,7 +46,11 @@ class PropertyGenerator extends AbstractMemberGenerator
$allDefaultProperties = $reflectionProperty->getDeclaringClass()->getDefaultProperties();
$property->setDefaultValue($allDefaultProperties[$reflectionProperty->getName()]);
$defaultValue = $allDefaultProperties[$reflectionProperty->getName()];
$property->setDefaultValue($defaultValue);
if ($defaultValue === null) {
$property->omitDefaultValue = true;
}
if ($reflectionProperty->getDocComment() != '') {
$property->setDocBlock(DocBlockGenerator::fromReflection($reflectionProperty->getDocBlock()));
@@ -63,14 +76,15 @@ class PropertyGenerator extends AbstractMemberGenerator
/**
* Generate from array
*
* @configkey name string [required] Class Name
* @configkey const bool
* @configkey defaultvalue null|bool|string|int|float|array|ValueGenerator
* @configkey flags int
* @configkey abstract bool
* @configkey final bool
* @configkey static bool
* @configkey visibility string
* @configkey name string [required] Class Name
* @configkey const bool
* @configkey defaultvalue null|bool|string|int|float|array|ValueGenerator
* @configkey flags int
* @configkey abstract bool
* @configkey final bool
* @configkey static bool
* @configkey visibility string
* @configkey omitdefaultvalue bool
*
* @throws Exception\InvalidArgumentException
* @param array $array
@@ -78,7 +92,7 @@ class PropertyGenerator extends AbstractMemberGenerator
*/
public static function fromArray(array $array)
{
if (!isset($array['name'])) {
if (! isset($array['name'])) {
throw new Exception\InvalidArgumentException(
'Property generator requires that a name is provided for this object'
);
@@ -87,7 +101,7 @@ class PropertyGenerator extends AbstractMemberGenerator
$property = new static($array['name']);
foreach ($array as $name => $value) {
// normalize key
switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) {
switch (strtolower(str_replace(['.', '-', '_'], '', $name))) {
case 'const':
$property->setConst($value);
break;
@@ -95,7 +109,7 @@ class PropertyGenerator extends AbstractMemberGenerator
$property->setDefaultValue($value);
break;
case 'docblock':
$docBlock = ($value instanceof DocBlockGenerator) ? $value : DocBlockGenerator::fromArray($value);
$docBlock = $value instanceof DocBlockGenerator ? $value : DocBlockGenerator::fromArray($value);
$property->setDocBlock($docBlock);
break;
case 'flags':
@@ -113,6 +127,9 @@ class PropertyGenerator extends AbstractMemberGenerator
case 'visibility':
$property->setVisibility($value);
break;
case 'omitdefaultvalue':
$property->omitDefaultValue($value);
break;
}
}
@@ -144,7 +161,6 @@ class PropertyGenerator extends AbstractMemberGenerator
public function setConst($const)
{
if ($const) {
$this->removeFlag(self::FLAG_PUBLIC | self::FLAG_PRIVATE | self::FLAG_PROTECTED);
$this->setFlags(self::FLAG_CONSTANT);
} else {
$this->removeFlag(self::FLAG_CONSTANT);
@@ -168,9 +184,12 @@ class PropertyGenerator extends AbstractMemberGenerator
*
* @return PropertyGenerator
*/
public function setDefaultValue($defaultValue, $defaultValueType = PropertyValueGenerator::TYPE_AUTO, $defaultValueOutputMode = PropertyValueGenerator::OUTPUT_MULTIPLE_LINE)
{
if (!($defaultValue instanceof PropertyValueGenerator)) {
public function setDefaultValue(
$defaultValue,
$defaultValueType = PropertyValueGenerator::TYPE_AUTO,
$defaultValueOutputMode = PropertyValueGenerator::OUTPUT_MULTIPLE_LINE
) {
if (! $defaultValue instanceof PropertyValueGenerator) {
$defaultValue = new PropertyValueGenerator($defaultValue, $defaultValueType, $defaultValueOutputMode);
}
@@ -204,23 +223,36 @@ class PropertyGenerator extends AbstractMemberGenerator
}
if ($this->isConst()) {
if ($defaultValue !== null && !$defaultValue->isValidConstantType()) {
if ($defaultValue !== null && ! $defaultValue->isValidConstantType()) {
throw new Exception\RuntimeException(sprintf(
'The property %s is said to be '
. 'constant but does not have a valid constant value.',
$this->name
));
}
$output .= $this->indentation . 'const ' . $name . ' = '
. (($defaultValue !== null) ? $defaultValue->generate() : 'null;');
} else {
$output .= $this->indentation
. $this->getVisibility()
. (($this->isStatic()) ? ' static' : '')
. ' $' . $name . ' = '
. (($defaultValue !== null) ? $defaultValue->generate() : 'null;');
$output .= $this->indentation . $this->getVisibility() . ' const ' . $name . ' = '
. ($defaultValue !== null ? $defaultValue->generate() : 'null;');
return $output;
}
return $output;
$output .= $this->indentation . $this->getVisibility() . ($this->isStatic() ? ' static' : '') . ' $' . $name;
if ($this->omitDefaultValue) {
return $output . ';';
}
return $output . ' = ' . ($defaultValue !== null ? $defaultValue->generate() : 'null;');
}
/**
* @param bool $omit
* @return PropertyGenerator
*/
public function omitDefaultValue(bool $omit = true)
{
$this->omitDefaultValue = $omit;
return $this;
}
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,6 +11,9 @@ namespace Zend\Code\Generator;
use Zend\Code\Reflection\ClassReflection;
use function str_replace;
use function strtolower;
class TraitGenerator extends ClassGenerator
{
const OBJECT_TYPE = 'trait';
@@ -38,7 +41,7 @@ class TraitGenerator extends ClassGenerator
$cg->setNamespaceName($classReflection->getNamespaceName());
}
$properties = array();
$properties = [];
foreach ($classReflection->getProperties() as $reflectionProperty) {
if ($reflectionProperty->getDeclaringClass()->getName() == $classReflection->getName()) {
$properties[] = PropertyGenerator::fromReflection($reflectionProperty);
@@ -46,9 +49,9 @@ class TraitGenerator extends ClassGenerator
}
$cg->addProperties($properties);
$methods = array();
$methods = [];
foreach ($classReflection->getMethods() as $reflectionMethod) {
$className = ($cg->getNamespaceName())
$className = $cg->getNamespaceName()
? $cg->getNamespaceName() . '\\' . $cg->getName()
: $cg->getName();
if ($reflectionMethod->getDeclaringClass()->getName() == $className) {
@@ -85,7 +88,7 @@ class TraitGenerator extends ClassGenerator
$cg = new static($array['name']);
foreach ($array as $name => $value) {
// normalize key
switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) {
switch (strtolower(str_replace(['.', '-', '_'], '', $name))) {
case 'containingfile':
$cg->setContainingFileGenerator($value);
break;
@@ -93,7 +96,7 @@ class TraitGenerator extends ClassGenerator
$cg->setNamespaceName($value);
break;
case 'docblock':
$docBlock = ($value instanceof DocBlockGenerator) ? $value : DocBlockGenerator::fromArray($value);
$docBlock = $value instanceof DocBlockGenerator ? $value : DocBlockGenerator::fromArray($value);
$cg->setDocBlock($docBlock);
break;
case 'properties':

View File

@@ -3,15 +3,29 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator;
use Reflection;
use ReflectionMethod;
class TraitUsageGenerator extends AbstractGenerator
use function array_key_exists;
use function array_search;
use function array_values;
use function count;
use function current;
use function explode;
use function implode;
use function in_array;
use function is_array;
use function is_string;
use function sprintf;
use function strpos;
class TraitUsageGenerator extends AbstractGenerator implements TraitUsageInterface
{
/**
* @var ClassGenerator
@@ -21,22 +35,22 @@ class TraitUsageGenerator extends AbstractGenerator
/**
* @var array Array of trait names
*/
protected $traits = array();
protected $traits = [];
/**
* @var array Array of trait aliases
*/
protected $traitAliases = array();
protected $traitAliases = [];
/**
* @var array Array of trait overrides
*/
protected $traitOverrides = array();
protected $traitOverrides = [];
/**
* @var array Array of string names
*/
protected $uses = array();
protected $uses = [];
public function __construct(ClassGenerator $classGenerator)
{
@@ -44,10 +58,12 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function addUse($use, $useAlias = null)
{
$this->removeUse($use);
if (! empty($useAlias)) {
$use .= ' as ' . $useAlias;
}
@@ -57,7 +73,7 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function getUses()
{
@@ -65,7 +81,105 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @param string $use
* @return bool
*/
public function hasUse($use)
{
foreach ($this->uses as $key => $value) {
$parts = explode(' ', $value);
if ($parts[0] === $use) {
return true;
}
}
return false;
}
/**
* @param string $use
* @return bool
*/
public function hasUseAlias($use)
{
foreach ($this->uses as $key => $value) {
$parts = explode(' as ', $value);
if ($parts[0] === $use && count($parts) == 2) {
return true;
}
}
return false;
}
/**
* Returns the alias of the provided FQCN
*
* @param string $use
* @return string|null
*/
public function getUseAlias(string $use): ?string
{
foreach ($this->uses as $key => $value) {
$parts = explode(' as ', $key);
if ($parts[0] === $use && count($parts) == 2) {
return $parts[1];
}
}
return null;
}
/**
* Returns true if the alias is defined in the use list
*
* @param string $alias
* @return bool
*/
public function isUseAlias(string $alias): bool
{
foreach ($this->uses as $key => $value) {
$parts = explode(' as ', $key);
if (count($parts) === 2 && $parts[1] === $alias) {
return true;
}
}
return false;
}
/**
* @param string $use
* @return TraitUsageGenerator
*/
public function removeUse($use)
{
foreach ($this->uses as $key => $value) {
$parts = explode(' ', $value);
if ($parts[0] === $use) {
unset($this->uses[$value]);
}
}
return $this;
}
/**
* @param string $use
* @return TraitUsageGenerator
*/
public function removeUseAlias($use)
{
foreach ($this->uses as $key => $value) {
$parts = explode(' as ', $value);
if ($parts[0] === $use && count($parts) == 2) {
unset($this->uses[$value]);
}
}
return $this;
}
/**
* @inheritDoc
*/
public function addTrait($trait)
{
@@ -97,7 +211,7 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function addTraits(array $traits)
{
@@ -109,7 +223,7 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function hasTrait($traitName)
{
@@ -117,7 +231,7 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function getTraits()
{
@@ -125,7 +239,7 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function removeTrait($traitName)
{
@@ -138,7 +252,7 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function addTraitAlias($method, $alias, $visibility = null)
{
@@ -156,7 +270,7 @@ class TraitUsageGenerator extends AbstractGenerator
}
// Validations
if (false === strpos($traitAndMethod, "::")) {
if (false === strpos($traitAndMethod, '::')) {
throw new Exception\InvalidArgumentException(
'Invalid Format: $method must be in the format of trait::method'
);
@@ -183,16 +297,16 @@ class TraitUsageGenerator extends AbstractGenerator
throw new Exception\InvalidArgumentException('Invalid trait: Trait does not exists on this class');
}
$this->traitAliases[$traitAndMethod] = array(
$this->traitAliases[$traitAndMethod] = [
'alias' => $alias,
'visibility' => $visibility
);
'visibility' => $visibility,
];
return $this;
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function getTraitAliases()
{
@@ -200,12 +314,12 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function addTraitOverride($method, $traitsToReplace)
{
if (false === is_array($traitsToReplace)) {
$traitsToReplace = array($traitsToReplace);
$traitsToReplace = [$traitsToReplace];
}
$traitAndMethod = $method;
@@ -222,19 +336,19 @@ class TraitUsageGenerator extends AbstractGenerator
}
// Validations
if (false === strpos($traitAndMethod, "::")) {
if (false === strpos($traitAndMethod, '::')) {
throw new Exception\InvalidArgumentException(
'Invalid Format: $method must be in the format of trait::method'
);
}
list($trait, $method) = explode("::", $traitAndMethod);
list($trait, $method) = explode('::', $traitAndMethod);
if (! $this->hasTrait($trait)) {
throw new Exception\InvalidArgumentException('Invalid trait: Trait does not exists on this class');
}
if (! array_key_exists($traitAndMethod, $this->traitOverrides)) {
$this->traitOverrides[$traitAndMethod] = array();
$this->traitOverrides[$traitAndMethod] = [];
}
foreach ($traitsToReplace as $traitToReplace) {
@@ -253,7 +367,7 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function removeTraitOverride($method, $overridesToRemove = null)
{
@@ -266,8 +380,8 @@ class TraitUsageGenerator extends AbstractGenerator
return $this;
}
$overridesToRemove = (! is_array($overridesToRemove))
? array($overridesToRemove)
$overridesToRemove = ! is_array($overridesToRemove)
? [$overridesToRemove]
: $overridesToRemove;
foreach ($overridesToRemove as $traitToRemove) {
$key = array_search($traitToRemove, $this->traitOverrides[$method]);
@@ -279,7 +393,7 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\TraitUsageInterface
* @inheritDoc
*/
public function getTraitOverrides()
{
@@ -287,7 +401,7 @@ class TraitUsageGenerator extends AbstractGenerator
}
/**
* @inherit Zend\Code\Generator\GeneratorInterface
* @inheritDoc
*/
public function generate()
{
@@ -304,13 +418,13 @@ class TraitUsageGenerator extends AbstractGenerator
$aliases = $this->getTraitAliases();
$overrides = $this->getTraitOverrides();
if (empty($aliases) && empty($overrides)) {
$output .= ";" . self::LINE_FEED . self::LINE_FEED;
$output .= ';' . self::LINE_FEED . self::LINE_FEED;
return $output;
}
$output .= ' {' . self::LINE_FEED;
foreach ($aliases as $method => $alias) {
$visibility = (null !== $alias['visibility'])
$visibility = null !== $alias['visibility']
? current(Reflection::getModifierNames($alias['visibility'])) . ' '
: '';

View File

@@ -3,9 +3,10 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator;
interface TraitUsageInterface
@@ -50,7 +51,7 @@ interface TraitUsageInterface
* Add multiple traits. Trait can be an array of trait names or array of trait
* configurations
*
* @param array $traitName Array of string names or configurations (@see addTrait)
* @param array $traits Array of string names or configurations (@see addTrait)
* @return self
*/
public function addTraits(array $traits);
@@ -58,7 +59,7 @@ interface TraitUsageInterface
/**
* Check to see if the class has a trait defined
*
* @param strint $traitName
* @param string $traitName
* @return bool
*/
public function hasTrait($traitName);
@@ -73,7 +74,7 @@ interface TraitUsageInterface
/**
* Remove a trait by its name
*
* @param $traitName
* @param string $traitName
*/
public function removeTrait($traitName);
@@ -91,11 +92,11 @@ interface TraitUsageInterface
* Alias is a string representing the new method name.
*
* $visibilty:
* ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PRIVATE| ReflectionMethod::IS_PROTECTED
* ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PRIVATE | ReflectionMethod::IS_PROTECTED
*
* @param mixed $method String or Array
* @param string $alias
* @param int $visiblity
* @param null|int $visibility
*/
public function addTraitAlias($method, $alias, $visibility = null);
@@ -123,7 +124,7 @@ interface TraitUsageInterface
* Option 2: Array of strings of traits to replace
* @param mixed $method
* @param mixed $traitToReplace
* @param mixed $traitsToReplace
*/
public function addTraitOverride($method, $traitsToReplace);
@@ -144,9 +145,9 @@ interface TraitUsageInterface
* Option 1: String of trait to replace
* Option 2: Array of strings of traits to replace
*
* @param $traitAndMethod
* @param null $overridesToRemove
* @return $this
* @param mixed $method
* @param mixed $overridesToRemove
* @return self
*/
public function removeTraitOverride($method, $overridesToRemove = null);

View File

@@ -0,0 +1,169 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator;
use Zend\Code\Generator\Exception\InvalidArgumentException;
use function in_array;
use function ltrim;
use function preg_match;
use function sprintf;
use function strpos;
use function strtolower;
use function substr;
final class TypeGenerator implements GeneratorInterface
{
/**
* @var bool
*/
private $isInternalPhpType;
/**
* @var string
*/
private $type;
/**
* @var bool
*/
private $nullable;
/**
* @var string[]
*
* @link http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
*/
private static $internalPhpTypes = [
'void',
'int',
'float',
'string',
'bool',
'array',
'callable',
'iterable',
'object'
];
/**
* @var string a regex pattern to match valid class names or types
*/
private static $validIdentifierMatcher = '/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*'
. '(\\\\[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)*$/';
/**
* @param string $type
*
* @return TypeGenerator
*
* @throws InvalidArgumentException
*/
public static function fromTypeString($type)
{
list($nullable, $trimmedNullable) = self::trimNullable($type);
list($wasTrimmed, $trimmedType) = self::trimType($trimmedNullable);
if (! preg_match(self::$validIdentifierMatcher, $trimmedType)) {
throw new InvalidArgumentException(sprintf(
'Provided type "%s" is invalid: must conform "%s"',
$type,
self::$validIdentifierMatcher
));
}
$isInternalPhpType = self::isInternalPhpType($trimmedType);
if ($wasTrimmed && $isInternalPhpType) {
throw new InvalidArgumentException(sprintf(
'Provided type "%s" is an internal PHP type, but was provided with a namespace separator prefix',
$type
));
}
if ($nullable && $isInternalPhpType && 'void' === strtolower($trimmedType)) {
throw new InvalidArgumentException(sprintf('Provided type "%s" cannot be nullable', $type));
}
$instance = new self();
$instance->type = $trimmedType;
$instance->nullable = $nullable;
$instance->isInternalPhpType = $isInternalPhpType;
return $instance;
}
private function __construct()
{
}
/**
* {@inheritDoc}
*/
public function generate()
{
$nullable = $this->nullable ? '?' : '';
if ($this->isInternalPhpType) {
return $nullable . strtolower($this->type);
}
return $nullable . '\\' . $this->type;
}
/**
* @return string the cleaned type string
*/
public function __toString()
{
return ltrim($this->generate(), '?\\');
}
/**
* @param string $type
*
* @return bool[]|string[] ordered tuple, first key represents whether the type is nullable, second is the
* trimmed string
*/
private static function trimNullable($type)
{
if (0 === strpos($type, '?')) {
return [true, substr($type, 1)];
}
return [false, $type];
}
/**
* @param string $type
*
* @return bool[]|string[] ordered tuple, first key represents whether the values was trimmed, second is the
* trimmed string
*/
private static function trimType($type)
{
if (0 === strpos($type, '\\')) {
return [true, substr($type, 1)];
}
return [false, $type];
}
/**
* @param string $type
*
* @return bool
*/
private static function isInternalPhpType($type)
{
return in_array(strtolower($type), self::$internalPhpTypes, true);
}
}

View File

@@ -3,33 +3,55 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Generator;
use Zend\Stdlib\ArrayObject;
use ArrayObject as SplArrayObject;
use Zend\Code\Exception\InvalidArgumentException;
use Zend\Stdlib\ArrayObject as StdlibArrayObject;
use function addcslashes;
use function array_keys;
use function array_merge;
use function array_search;
use function count;
use function get_class;
use function get_defined_constants;
use function gettype;
use function implode;
use function in_array;
use function is_array;
use function is_int;
use function is_object;
use function max;
use function sprintf;
use function str_repeat;
use function strpos;
class ValueGenerator extends AbstractGenerator
{
/**#@+
* Constant values
*/
const TYPE_AUTO = 'auto';
const TYPE_BOOLEAN = 'boolean';
const TYPE_BOOL = 'bool';
const TYPE_NUMBER = 'number';
const TYPE_INTEGER = 'integer';
const TYPE_INT = 'int';
const TYPE_FLOAT = 'float';
const TYPE_DOUBLE = 'double';
const TYPE_STRING = 'string';
const TYPE_ARRAY = 'array';
const TYPE_CONSTANT = 'constant';
const TYPE_NULL = 'null';
const TYPE_OBJECT = 'object';
const TYPE_OTHER = 'other';
const TYPE_AUTO = 'auto';
const TYPE_BOOLEAN = 'boolean';
const TYPE_BOOL = 'bool';
const TYPE_NUMBER = 'number';
const TYPE_INTEGER = 'integer';
const TYPE_INT = 'int';
const TYPE_FLOAT = 'float';
const TYPE_DOUBLE = 'double';
const TYPE_STRING = 'string';
const TYPE_ARRAY = 'array';
const TYPE_ARRAY_SHORT = 'array_short';
const TYPE_ARRAY_LONG = 'array_long';
const TYPE_CONSTANT = 'constant';
const TYPE_NULL = 'null';
const TYPE_OBJECT = 'object';
const TYPE_OTHER = 'other';
/**#@-*/
const OUTPUT_MULTIPLE_LINE = 'multipleLine';
@@ -38,7 +60,7 @@ class ValueGenerator extends AbstractGenerator
/**
* @var mixed
*/
protected $value = null;
protected $value;
/**
* @var string
@@ -58,21 +80,27 @@ class ValueGenerator extends AbstractGenerator
/**
* @var array
*/
protected $allowedTypes = null;
protected $allowedTypes;
/**
* Autodetectable constants
* @var ArrayObject
*
* @var SplArrayObject|StdlibArrayObject
*/
protected $constants = null;
protected $constants;
/**
* @param mixed $value
* @param string $type
* @param string $outputMode
* @param ArrayObject $constants
* @param null|SplArrayObject|StdlibArrayObject $constants
*/
public function __construct($value = null, $type = self::TYPE_AUTO, $outputMode = self::OUTPUT_MULTIPLE_LINE, ArrayObject $constants = null)
{
public function __construct(
$value = null,
$type = self::TYPE_AUTO,
$outputMode = self::OUTPUT_MULTIPLE_LINE,
$constants = null
) {
// strict check is important here if $type = AUTO
if ($value !== null) {
$this->setValue($value);
@@ -83,11 +111,14 @@ class ValueGenerator extends AbstractGenerator
if ($outputMode !== self::OUTPUT_MULTIPLE_LINE) {
$this->setOutputMode($outputMode);
}
if ($constants !== null) {
$this->constants = $constants;
} else {
$this->constants = new ArrayObject();
if ($constants === null) {
$constants = new SplArrayObject();
} elseif (! ($constants instanceof SplArrayObject || $constants instanceof StdlibArrayObject)) {
throw new InvalidArgumentException(
'$constants must be an instance of ArrayObject or Zend\Stdlib\ArrayObject'
);
}
$this->constants = $constants;
}
/**
@@ -95,7 +126,7 @@ class ValueGenerator extends AbstractGenerator
*/
public function initEnvironmentConstants()
{
$constants = array(
$constants = [
'__DIR__',
'__FILE__',
'__LINE__',
@@ -104,8 +135,8 @@ class ValueGenerator extends AbstractGenerator
'__METHOD__',
'__FUNCTION__',
'__NAMESPACE__',
'::'
);
'::',
];
$constants = array_merge($constants, array_keys(get_defined_constants()), $this->constants->getArrayCopy());
$this->constants->exchangeArray($constants);
}
@@ -143,7 +174,7 @@ class ValueGenerator extends AbstractGenerator
/**
* Return constant list
*
* @return ArrayObject
* @return SplArrayObject|StdlibArrayObject
*/
public function getConstants()
{
@@ -155,14 +186,16 @@ class ValueGenerator extends AbstractGenerator
*/
public function isValidConstantType()
{
if ($this->type == self::TYPE_AUTO) {
if ($this->type === self::TYPE_AUTO) {
$type = $this->getAutoDeterminedType($this->value);
} else {
$type = $this->type;
}
// valid types for constants
$scalarTypes = array(
$validConstantTypes = [
self::TYPE_ARRAY,
self::TYPE_ARRAY_LONG,
self::TYPE_ARRAY_SHORT,
self::TYPE_BOOLEAN,
self::TYPE_BOOL,
self::TYPE_NUMBER,
@@ -172,10 +205,10 @@ class ValueGenerator extends AbstractGenerator
self::TYPE_DOUBLE,
self::TYPE_STRING,
self::TYPE_CONSTANT,
self::TYPE_NULL
);
self::TYPE_NULL,
];
return in_array($type, $scalarTypes);
return in_array($type, $validConstantTypes);
}
/**
@@ -238,7 +271,7 @@ class ValueGenerator extends AbstractGenerator
*/
protected function getValidatedType($type)
{
$types = array(
$types = [
self::TYPE_AUTO,
self::TYPE_BOOLEAN,
self::TYPE_BOOL,
@@ -249,11 +282,13 @@ class ValueGenerator extends AbstractGenerator
self::TYPE_DOUBLE,
self::TYPE_STRING,
self::TYPE_ARRAY,
self::TYPE_ARRAY_SHORT,
self::TYPE_ARRAY_LONG,
self::TYPE_CONSTANT,
self::TYPE_NULL,
self::TYPE_OBJECT,
self::TYPE_OTHER
);
self::TYPE_OTHER,
];
if (in_array($type, $types)) {
return $type;
@@ -302,22 +337,32 @@ class ValueGenerator extends AbstractGenerator
{
$type = $this->type;
if ($type != self::TYPE_AUTO) {
if ($type !== self::TYPE_AUTO) {
$type = $this->getValidatedType($type);
}
$value = $this->value;
if ($type == self::TYPE_AUTO) {
if ($type === self::TYPE_AUTO) {
$type = $this->getAutoDeterminedType($value);
}
if ($type == self::TYPE_ARRAY) {
$isArrayType = in_array($type, [self::TYPE_ARRAY, self::TYPE_ARRAY_LONG, self::TYPE_ARRAY_SHORT]);
if ($isArrayType) {
foreach ($value as &$curValue) {
if ($curValue instanceof self) {
continue;
}
$curValue = new self($curValue, self::TYPE_AUTO, self::OUTPUT_MULTIPLE_LINE, $this->getConstants());
if (is_array($curValue)) {
$newType = $type;
} else {
$newType = self::TYPE_AUTO;
}
$curValue = new self($curValue, $newType, self::OUTPUT_MULTIPLE_LINE, $this->getConstants());
$curValue->setIndentation($this->indentation);
}
}
@@ -326,7 +371,7 @@ class ValueGenerator extends AbstractGenerator
switch ($type) {
case self::TYPE_BOOLEAN:
case self::TYPE_BOOL:
$output .= ($value ? 'true' : 'false');
$output .= $value ? 'true' : 'false';
break;
case self::TYPE_STRING:
$output .= self::escape($value);
@@ -343,11 +388,21 @@ class ValueGenerator extends AbstractGenerator
$output .= $value;
break;
case self::TYPE_ARRAY:
$output .= 'array(';
case self::TYPE_ARRAY_LONG:
case self::TYPE_ARRAY_SHORT:
if ($type === self::TYPE_ARRAY_LONG) {
$startArray = 'array(';
$endArray = ')';
} else {
$startArray = '[';
$endArray = ']';
}
$output .= $startArray;
if ($this->outputMode == self::OUTPUT_MULTIPLE_LINE) {
$output .= self::LINE_FEED . str_repeat($this->indentation, $this->arrayDepth + 1);
}
$outputParts = array();
$outputParts = [];
$noKeyIndex = 0;
foreach ($value as $n => $v) {
/* @var $v ValueGenerator */
@@ -369,7 +424,7 @@ class ValueGenerator extends AbstractGenerator
$outputParts[] = (is_int($n) ? $n : self::escape($n)) . ' => ' . $partV;
}
}
$padding = ($this->outputMode == self::OUTPUT_MULTIPLE_LINE)
$padding = $this->outputMode == self::OUTPUT_MULTIPLE_LINE
? self::LINE_FEED . str_repeat($this->indentation, $this->arrayDepth + 1)
: ' ';
$output .= implode(',' . $padding, $outputParts);
@@ -379,13 +434,14 @@ class ValueGenerator extends AbstractGenerator
}
$output .= self::LINE_FEED . str_repeat($this->indentation, $this->arrayDepth);
}
$output .= ')';
$output .= $endArray;
break;
case self::TYPE_OTHER:
default:
throw new Exception\RuntimeException(
sprintf('Type "%s" is unknown or cannot be used as property default value.', get_class($value))
);
throw new Exception\RuntimeException(sprintf(
'Type "%s" is unknown or cannot be used as property default value.',
is_object($value) ? get_class($value) : gettype($value)
));
}
return $output;

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,6 +11,8 @@ namespace Zend\Code\Generic\Prototype;
use Zend\Code\Reflection\Exception;
use function str_replace;
/**
* This is a factory for classes which are identified by name.
*
@@ -27,20 +29,20 @@ class PrototypeClassFactory
/**
* @var array
*/
protected $prototypes = array();
protected $prototypes = [];
/**
* @var PrototypeGenericInterface
*/
protected $genericPrototype = null;
protected $genericPrototype;
/**
* @param PrototypeInterface[] $prototypes
* @param PrototypeGenericInterface $genericPrototype
*/
public function __construct($prototypes = array(), PrototypeGenericInterface $genericPrototype = null)
public function __construct($prototypes = [], PrototypeGenericInterface $genericPrototype = null)
{
foreach ((array)$prototypes as $prototype) {
foreach ((array) $prototypes as $prototype) {
$this->addPrototype($prototype);
}
@@ -83,7 +85,7 @@ class PrototypeClassFactory
*/
protected function normalizeName($name)
{
return str_replace(array('-', '_'), '', $name);
return str_replace(['-', '_'], '', $name);
}
/**
@@ -105,11 +107,11 @@ class PrototypeClassFactory
{
$prototypeName = $this->normalizeName($prototypeName);
if (!$this->hasPrototype($prototypeName) && !isset($this->genericPrototype)) {
if (! $this->hasPrototype($prototypeName) && ! isset($this->genericPrototype)) {
throw new Exception\RuntimeException('This tag name is not supported by this tag manager');
}
if (!$this->hasPrototype($prototypeName)) {
if (! $this->hasPrototype($prototypeName)) {
$newPrototype = clone $this->genericPrototype;
$newPrototype->setName($prototypeName);
} else {

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,29 +3,42 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code;
use function array_key_exists;
use function array_search;
use function is_array;
use function is_int;
use function is_string;
use function ltrim;
use function strlen;
use function strpos;
use function strrpos;
use function substr;
use function substr_replace;
use function trim;
class NameInformation
{
/**
* @var string
*/
protected $namespace = null;
protected $namespace;
/**
* @var array
*/
protected $uses = array();
protected $uses = [];
/**
* @param string $namespace
* @param array $uses
*/
public function __construct($namespace = null, array $uses = array())
public function __construct($namespace = null, array $uses = [])
{
if ($namespace) {
$this->setNamespace($namespace);
@@ -58,7 +71,7 @@ class NameInformation
*/
public function hasNamespace()
{
return ($this->namespace !== null);
return $this->namespace !== null;
}
/**
@@ -67,7 +80,7 @@ class NameInformation
*/
public function setUses(array $uses)
{
$this->uses = array();
$this->uses = [];
$this->addUses($uses);
return $this;
@@ -128,11 +141,11 @@ class NameInformation
*/
public function resolveName($name)
{
if ($this->namespace && !$this->uses && strlen($name) > 0 && $name{0} != '\\') {
if ($this->namespace && ! $this->uses && strlen($name) > 0 && $name[0] != '\\') {
return $this->namespace . '\\' . $name;
}
if (!$this->uses || strlen($name) <= 0 || $name{0} == '\\') {
if (! $this->uses || strlen($name) <= 0 || $name[0] == '\\') {
return ltrim($name, '\\');
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -15,17 +15,25 @@ use Zend\Code\Annotation\AnnotationManager;
use Zend\Code\Scanner\AnnotationScanner;
use Zend\Code\Scanner\FileScanner;
use function array_shift;
use function array_slice;
use function array_unshift;
use function file;
use function file_exists;
use function implode;
use function strstr;
class ClassReflection extends ReflectionClass implements ReflectionInterface
{
/**
* @var AnnotationScanner
*/
protected $annotations = null;
protected $annotations;
/**
* @var DocBlockReflection
*/
protected $docBlock = null;
protected $docBlock;
/**
* Return the reflection file of the declaring file.
@@ -42,7 +50,7 @@ class ClassReflection extends ReflectionClass implements ReflectionInterface
/**
* Return the classes DocBlock reflection object
*
* @return DocBlockReflection
* @return DocBlockReflection|false
* @throws Exception\ExceptionInterface for missing DocBock or invalid reflection class
*/
public function getDocBlock()
@@ -62,7 +70,7 @@ class ClassReflection extends ReflectionClass implements ReflectionInterface
/**
* @param AnnotationManager $annotationManager
* @return AnnotationCollection
* @return AnnotationCollection|false
*/
public function getAnnotations(AnnotationManager $annotationManager)
{
@@ -79,7 +87,7 @@ class ClassReflection extends ReflectionClass implements ReflectionInterface
$fileScanner = $this->createFileScanner($this->getFileName());
$nameInformation = $fileScanner->getClassNameInformation($this->getName());
if (!$nameInformation) {
if (! $nameInformation) {
return false;
}
@@ -123,7 +131,7 @@ class ClassReflection extends ReflectionClass implements ReflectionInterface
// Ensure we get between the open and close braces
$lines = array_slice($filelines, $startnum, $endnum);
array_unshift($lines, $filelines[$startnum-1]);
array_unshift($lines, $filelines[$startnum - 1]);
return strstr(implode('', $lines), '{');
}
@@ -136,7 +144,7 @@ class ClassReflection extends ReflectionClass implements ReflectionInterface
public function getInterfaces()
{
$phpReflections = parent::getInterfaces();
$zendReflections = array();
$zendReflections = [];
while ($phpReflections && ($phpReflection = array_shift($phpReflections))) {
$instance = new ClassReflection($phpReflection->getName());
$zendReflections[] = $instance;
@@ -168,7 +176,7 @@ class ClassReflection extends ReflectionClass implements ReflectionInterface
*/
public function getMethods($filter = -1)
{
$methods = array();
$methods = [];
foreach (parent::getMethods($filter) as $method) {
$instance = new MethodReflection($this->getName(), $method->getName());
$methods[] = $instance;
@@ -180,11 +188,11 @@ class ClassReflection extends ReflectionClass implements ReflectionInterface
/**
* Returns an array of reflection classes of traits used by this class.
*
* @return array|null
* @return null|array
*/
public function getTraits()
{
$vals = array();
$vals = [];
$traits = parent::getTraits();
if ($traits === null) {
return;
@@ -239,7 +247,7 @@ class ClassReflection extends ReflectionClass implements ReflectionInterface
public function getProperties($filter = -1)
{
$phpReflections = parent::getProperties($filter);
$zendReflections = array();
$zendReflections = [];
while ($phpReflections && ($phpReflection = array_shift($phpReflections))) {
$instance = new PropertyReflection($this->getName(), $phpReflection->getName());
$zendReflections[] = $instance;
@@ -269,7 +277,7 @@ class ClassReflection extends ReflectionClass implements ReflectionInterface
/**
* Creates a new FileScanner instance.
*
* By having this as a seperate method it allows the method to be overridden
* By having this as a separate method it allows the method to be overridden
* if a different FileScanner is needed.
*
* @param string $filename

View File

@@ -3,23 +3,26 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Reflection\DocBlock\Tag;
use function preg_match;
use function rtrim;
class AuthorTag implements TagInterface
{
/**
* @var string
*/
protected $authorName = null;
protected $authorName;
/**
* @var string
*/
protected $authorEmail = null;
protected $authorEmail;
/**
* @return string
@@ -36,9 +39,9 @@ class AuthorTag implements TagInterface
*/
public function initialize($tagDocblockLine)
{
$match = array();
$match = [];
if (!preg_match('/^([^\<]*)(\<([^\>]*)\>)?(.*)$/u', $tagDocblockLine, $match)) {
if (! preg_match('/^([^\<]*)(\<([^\>]*)\>)?(.*)$/u', $tagDocblockLine, $match)) {
return;
}
@@ -69,6 +72,6 @@ class AuthorTag implements TagInterface
public function __toString()
{
return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . PHP_EOL;
return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . "\n";
}
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,27 +11,30 @@ namespace Zend\Code\Reflection\DocBlock\Tag;
use Zend\Code\Generic\Prototype\PrototypeGenericInterface;
use function explode;
use function trim;
class GenericTag implements TagInterface, PrototypeGenericInterface
{
/**
* @var string
*/
protected $name = null;
protected $name;
/**
* @var string
*/
protected $content = null;
protected $content;
/**
* @var null|string
*/
protected $contentSplitCharacter = null;
protected $contentSplitCharacter;
/**
* @var array
*/
protected $values = array();
protected $values = [];
/**
* @param string $contentSplitCharacter
@@ -95,7 +98,7 @@ class GenericTag implements TagInterface, PrototypeGenericInterface
*/
public function __toString()
{
return 'DocBlock Tag [ * @' . $this->name . ' ]' . PHP_EOL;
return 'DocBlock Tag [ * @' . $this->name . ' ]' . "\n";
}
/**

View File

@@ -3,23 +3,26 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Reflection\DocBlock\Tag;
use function preg_match;
use function trim;
class LicenseTag implements TagInterface
{
/**
* @var string
*/
protected $url = null;
protected $url;
/**
* @var string
*/
protected $licenseName = null;
protected $licenseName;
/**
* @return string
@@ -36,9 +39,9 @@ class LicenseTag implements TagInterface
*/
public function initialize($tagDocblockLine)
{
$match = array();
$match = [];
if (!preg_match('#^([\S]*)(?:\s+(.*))?$#m', $tagDocblockLine, $match)) {
if (! preg_match('#^([\S]*)(?:\s+(.*))?$#m', $tagDocblockLine, $match)) {
return;
}
@@ -69,6 +72,6 @@ class LicenseTag implements TagInterface
public function __toString()
{
return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . PHP_EOL;
return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . "\n";
}
}

View File

@@ -3,12 +3,16 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Reflection\DocBlock\Tag;
use function explode;
use function preg_match;
use function rtrim;
class MethodTag implements TagInterface, PhpDocTypedTagInterface
{
/**
@@ -16,17 +20,17 @@ class MethodTag implements TagInterface, PhpDocTypedTagInterface
*
* @var array
*/
protected $types = array();
protected $types = [];
/**
* @var string
*/
protected $methodName = null;
protected $methodName;
/**
* @var string
*/
protected $description = null;
protected $description;
/**
* Is static method
@@ -50,9 +54,9 @@ class MethodTag implements TagInterface, PhpDocTypedTagInterface
*/
public function initialize($tagDocblockLine)
{
$match = array();
$match = [];
if (!preg_match('#^(static[\s]+)?(.+[\s]+)?(.+\(\))[\s]*(.*)$#m', $tagDocblockLine, $match)) {
if (! preg_match('#^(static[\s]+)?(.+[\s]+)?(.+\(\))[\s]*(.*)$#m', $tagDocblockLine, $match)) {
return;
}
@@ -117,6 +121,6 @@ class MethodTag implements TagInterface, PhpDocTypedTagInterface
public function __toString()
{
return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . PHP_EOL;
return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . "\n";
}
}

View File

@@ -3,28 +3,33 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Reflection\DocBlock\Tag;
use function explode;
use function preg_match;
use function preg_replace;
use function trim;
class ParamTag implements TagInterface, PhpDocTypedTagInterface
{
/**
* @var array
*/
protected $types = array();
protected $types = [];
/**
* @var string
*/
protected $variableName = null;
protected $variableName;
/**
* @var string
*/
protected $description = null;
protected $description;
/**
* @return string
@@ -41,9 +46,9 @@ class ParamTag implements TagInterface, PhpDocTypedTagInterface
*/
public function initialize($tagDocBlockLine)
{
$matches = array();
$matches = [];
if (!preg_match('#((?:[\w|\\\]+(?:\[\])*\|?)+)(?:\s+(\$\S+))?(?:\s+(.*))?#s', $tagDocBlockLine, $matches)) {
if (! preg_match('#((?:[\w|\\\]+(?:\[\])*\|?)+)(?:\s+(\$\S+))?(?:\s+(.*))?#s', $tagDocBlockLine, $matches)) {
return;
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,28 +3,32 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Reflection\DocBlock\Tag;
use function explode;
use function preg_match;
use function rtrim;
class PropertyTag implements TagInterface, PhpDocTypedTagInterface
{
/**
* @var array
*/
protected $types = array();
protected $types = [];
/**
* @var string
*/
protected $propertyName = null;
protected $propertyName;
/**
* @var string
*/
protected $description = null;
protected $description;
/**
* @return string
@@ -41,8 +45,8 @@ class PropertyTag implements TagInterface, PhpDocTypedTagInterface
*/
public function initialize($tagDocblockLine)
{
$match = array();
if (!preg_match('#^(.+)?(\$[\S]+)[\s]*(.*)$#m', $tagDocblockLine, $match)) {
$match = [];
if (! preg_match('#^(.+)?(\$[\S]+)[\s]*(.*)$#m', $tagDocblockLine, $match)) {
return;
}
@@ -95,6 +99,6 @@ class PropertyTag implements TagInterface, PhpDocTypedTagInterface
public function __toString()
{
return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . PHP_EOL;
return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . "\n";
}
}

View File

@@ -3,23 +3,28 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Reflection\DocBlock\Tag;
use function explode;
use function preg_match;
use function preg_replace;
use function trim;
class ReturnTag implements TagInterface, PhpDocTypedTagInterface
{
/**
* @var array
*/
protected $types = array();
protected $types = [];
/**
* @var string
*/
protected $description = null;
protected $description;
/**
* @return string
@@ -35,8 +40,8 @@ class ReturnTag implements TagInterface, PhpDocTypedTagInterface
*/
public function initialize($tagDocBlockLine)
{
$matches = array();
if (!preg_match('#((?:[\w|\\\]+(?:\[\])*\|?)+)(?:\s+(.*))?#s', $tagDocBlockLine, $matches)) {
$matches = [];
if (! preg_match('#((?:[\w|\\\]+(?:\[\])*\|?)+)(?:\s+(.*))?#s', $tagDocBlockLine, $matches)) {
return;
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,23 +3,27 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Reflection\DocBlock\Tag;
use function explode;
use function implode;
use function preg_match;
class ThrowsTag implements TagInterface, PhpDocTypedTagInterface
{
/**
* @var array
*/
protected $types = array();
protected $types = [];
/**
* @var string
*/
protected $description = null;
protected $description;
/**
* @return string
@@ -35,7 +39,7 @@ class ThrowsTag implements TagInterface, PhpDocTypedTagInterface
*/
public function initialize($tagDocBlockLine)
{
$matches = array();
$matches = [];
preg_match('#([\w|\\\]+)(?:\s+(.*))?#', $tagDocBlockLine, $matches);
$this->types = explode('|', $matches[1]);

View File

@@ -0,0 +1,87 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Reflection\DocBlock\Tag;
class VarTag implements TagInterface, PhpDocTypedTagInterface
{
/**
* @var string[]
*/
private $types = [];
/**
* @var string|null
*/
private $variableName;
/**
* @var string|null
*/
private $description;
/**
* {@inheritDoc}
*/
public function getName() : string
{
return 'var';
}
/**
* {@inheritDoc}
*/
public function initialize($tagDocblockLine) : void
{
$match = [];
if (! preg_match(
'#^([^\$]\S+)?\s*(\$[\S]+)?\s*(.*)$#m',
$tagDocblockLine,
$match
)) {
return;
}
if ($match[1] !== '') {
$this->types = explode('|', rtrim($match[1]));
}
if ($match[2] !== '') {
$this->variableName = $match[2];
}
if ($match[3] !== '') {
$this->description = $match[3];
}
}
/**
* {@inheritDoc}
*/
public function getTypes() : array
{
return $this->types;
}
public function getVariableName() : ?string
{
return $this->variableName;
}
public function getDescription() : ?string
{
return $this->description;
}
public function __toString() : string
{
return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . PHP_EOL;
}
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -26,6 +26,7 @@ class TagManager extends PrototypeClassFactory
$this->addPrototype(new Tag\AuthorTag());
$this->addPrototype(new Tag\LicenseTag());
$this->addPrototype(new Tag\ThrowsTag());
$this->addPrototype(new Tag\VarTag());
$this->setGenericPrototype(new Tag\GenericTag());
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -14,49 +14,61 @@ use Zend\Code\Reflection\DocBlock\Tag\TagInterface as DocBlockTagInterface;
use Zend\Code\Reflection\DocBlock\TagManager as DocBlockTagManager;
use Zend\Code\Scanner\DocBlockScanner;
use function count;
use function get_class;
use function is_string;
use function ltrim;
use function method_exists;
use function preg_replace;
use function sprintf;
use function substr_count;
class DocBlockReflection implements ReflectionInterface
{
/**
* @var Reflector
*/
protected $reflector = null;
protected $reflector;
/**
* @var string
*/
protected $docComment = null;
protected $docComment;
/**
* @var DocBlockTagManager
*/
protected $tagManager = null;
protected $tagManager;
/**#@+
/**
* @var int
*/
protected $startLine = null;
protected $endLine = null;
/**#@-*/
protected $startLine;
/**
* @var int
*/
protected $endLine;
/**
* @var string
*/
protected $cleanDocComment = null;
protected $cleanDocComment;
/**
* @var string
*/
protected $longDescription = null;
protected $longDescription;
/**
* @var string
*/
protected $shortDescription = null;
protected $shortDescription;
/**
* @var array
*/
protected $tags = array();
protected $tags = [];
/**
* @var bool
@@ -79,11 +91,10 @@ class DocBlockReflection implements ReflectionInterface
* @param Reflector|string $commentOrReflector
* @param null|DocBlockTagManager $tagManager
* @throws Exception\InvalidArgumentException
* @return DocBlockReflection
*/
public function __construct($commentOrReflector, DocBlockTagManager $tagManager = null)
{
if (!$tagManager) {
if (! $tagManager) {
$tagManager = new DocBlockTagManager();
$tagManager->initializeDefaultTags();
}
@@ -91,7 +102,7 @@ class DocBlockReflection implements ReflectionInterface
if ($commentOrReflector instanceof Reflector) {
$this->reflector = $commentOrReflector;
if (!method_exists($commentOrReflector, 'getDocComment')) {
if (! method_exists($commentOrReflector, 'getDocComment')) {
throw new Exception\InvalidArgumentException('Reflector must contain method "getDocComment"');
}
/* @var MethodReflection $commentOrReflector */
@@ -222,11 +233,11 @@ class DocBlockReflection implements ReflectionInterface
public function getTags($filter = null)
{
$this->reflect();
if ($filter === null || !is_string($filter)) {
if ($filter === null || ! is_string($filter)) {
return $this->tags;
}
$returnTags = array();
$returnTags = [];
foreach ($this->tags as $tag) {
if ($tag->getName() == $filter) {
$returnTags[] = $tag;
@@ -251,7 +262,9 @@ class DocBlockReflection implements ReflectionInterface
// create a clean docComment
$this->cleanDocComment = preg_replace("#[ \t]*(?:/\*\*|\*/|\*)[ ]{0,1}(.*)?#", '$1', $docComment);
$this->cleanDocComment = ltrim($this->cleanDocComment, "\r\n"); // @todo should be changed to remove first and last empty line
// @todo should be changed to remove first and last empty line
$this->cleanDocComment = ltrim($this->cleanDocComment, "\r\n");
$scanner = new DocBlockScanner($docComment);
$this->shortDescription = ltrim($scanner->getShortDescription());
@@ -269,15 +282,15 @@ class DocBlockReflection implements ReflectionInterface
*/
public function toString()
{
$str = "DocBlock [ /* DocBlock */ ] {" . PHP_EOL . PHP_EOL;
$str .= " - Tags [" . count($this->tags) . "] {" . PHP_EOL;
$str = 'DocBlock [ /* DocBlock */ ] {' . "\n\n";
$str .= ' - Tags [' . count($this->tags) . '] {' . "\n";
foreach ($this->tags as $tag) {
$str .= " " . $tag;
$str .= ' ' . $tag;
}
$str .= " }" . PHP_EOL;
$str .= "}" . PHP_EOL;
$str .= ' }' . "\n";
$str .= '}' . "\n";
return $str;
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,17 +11,29 @@ namespace Zend\Code\Reflection;
use Zend\Code\Scanner\CachingFileScanner;
use function basename;
use function count;
use function current;
use function file_get_contents;
use function get_included_files;
use function in_array;
use function realpath;
use function reset;
use function sprintf;
use function stream_resolve_include_path;
use function substr_count;
class FileReflection implements ReflectionInterface
{
/**
* @var string
*/
protected $filePath = null;
protected $filePath;
/**
* @var string
*/
protected $docComment = null;
protected $docComment;
/**
* @var int
@@ -31,37 +43,37 @@ class FileReflection implements ReflectionInterface
/**
* @var int
*/
protected $endLine = null;
protected $endLine;
/**
* @var string[]
*/
protected $namespaces = array();
protected $namespaces = [];
/**
* @var string[]
*/
protected $uses = array();
protected $uses = [];
/**
* @var string[]
*/
protected $requiredFiles = array();
protected $requiredFiles = [];
/**
* @var ClassReflection[]
*/
protected $classes = array();
protected $classes = [];
/**
* @var FunctionReflection[]
*/
protected $functions = array();
protected $functions = [];
/**
* @var string
*/
protected $contents = null;
protected $contents;
/**
* @param string $filename
@@ -75,15 +87,15 @@ class FileReflection implements ReflectionInterface
$fileRealPath = stream_resolve_include_path($filename);
}
if (!$fileRealPath) {
if (! $fileRealPath) {
throw new Exception\InvalidArgumentException(sprintf(
'No file for %s was found.',
$filename
));
}
if (!in_array($fileRealPath, get_included_files())) {
if (!$includeIfNotAlreadyIncluded) {
if (! in_array($fileRealPath, get_included_files())) {
if (! $includeIfNotAlreadyIncluded) {
throw new Exception\RuntimeException(sprintf(
'File %s must be required before it can be reflected',
$filename
@@ -101,11 +113,10 @@ class FileReflection implements ReflectionInterface
* Required by the Reflector interface.
*
* @todo What should this do?
* @return null
* @return void
*/
public static function export()
{
return;
}
/**
@@ -147,11 +158,11 @@ class FileReflection implements ReflectionInterface
}
/**
* @return DocBlockReflection
* @return DocBlockReflection|false
*/
public function getDocBlock()
{
if (!($docComment = $this->getDocComment())) {
if (! ($docComment = $this->getDocComment())) {
return false;
}
@@ -169,7 +180,7 @@ class FileReflection implements ReflectionInterface
}
/**
* @return string
* @return null|string
*/
public function getNamespace()
{
@@ -195,7 +206,7 @@ class FileReflection implements ReflectionInterface
*/
public function getClasses()
{
$classes = array();
$classes = [];
foreach ($this->classes as $class) {
$classes[] = new ClassReflection($class);
}
@@ -210,7 +221,7 @@ class FileReflection implements ReflectionInterface
*/
public function getFunctions()
{
$functions = array();
$functions = [];
foreach ($this->functions as $function) {
$functions[] = new FunctionReflection($function);
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,6 +11,20 @@ namespace Zend\Code\Reflection;
use ReflectionFunction;
use function array_shift;
use function array_slice;
use function count;
use function file;
use function implode;
use function preg_match;
use function preg_quote;
use function preg_replace;
use function sprintf;
use function strlen;
use function strrpos;
use function substr;
use function var_export;
class FunctionReflection extends ReflectionFunction implements ReflectionInterface
{
/**
@@ -85,7 +99,7 @@ class FunctionReflection extends ReflectionFunction implements ReflectionInterfa
$lines = array_slice(
file($fileName, FILE_IGNORE_NEW_LINES),
$startLine - 1,
($endLine - ($startLine - 1)),
$endLine - ($startLine - 1),
true
);
@@ -98,8 +112,12 @@ class FunctionReflection extends ReflectionFunction implements ReflectionInterfa
$content = $matches[0];
}
} else {
$name = substr($this->getName(), strrpos($this->getName(), '\\')+1);
preg_match('#function\s+' . preg_quote($name) . '\s*\([^\)]*\)\s*{([^{}]+({[^}]+})*[^}]+)?}#', $functionLine, $matches);
$name = substr($this->getName(), strrpos($this->getName(), '\\') + 1);
preg_match(
'#function\s+' . preg_quote($name) . '\s*\([^\)]*\)\s*{([^{}]+({[^}]+})*[^}]+)?}#',
$functionLine,
$matches
);
if (isset($matches[0])) {
$content = $matches[0];
}
@@ -113,7 +131,8 @@ class FunctionReflection extends ReflectionFunction implements ReflectionInterfa
/**
* Get method prototype
*
* @return array
* @param string $format
* @return array|string
*/
public function getPrototype($format = FunctionReflection::PROTOTYPE_AS_ARRAY)
{
@@ -125,29 +144,31 @@ class FunctionReflection extends ReflectionFunction implements ReflectionInterfa
$returnType = count($returnTypes) > 1 ? implode('|', $returnTypes) : $returnTypes[0];
}
$prototype = array(
$prototype = [
'namespace' => $this->getNamespaceName(),
'name' => substr($this->getName(), strlen($this->getNamespaceName()) + 1),
'return' => $returnType,
'arguments' => array(),
);
'arguments' => [],
];
$parameters = $this->getParameters();
foreach ($parameters as $parameter) {
$prototype['arguments'][$parameter->getName()] = array(
'type' => $parameter->getType(),
'required' => !$parameter->isOptional(),
$prototype['arguments'][$parameter->getName()] = [
'type' => $parameter->detectType(),
'required' => ! $parameter->isOptional(),
'by_ref' => $parameter->isPassedByReference(),
'default' => $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null,
);
];
}
if ($format == FunctionReflection::PROTOTYPE_AS_STRING) {
$line = $prototype['return'] . ' ' . $prototype['name'] . '(';
$args = array();
$args = [];
foreach ($prototype['arguments'] as $name => $argument) {
$argsLine = ($argument['type'] ? $argument['type'] . ' ' : '') . ($argument['by_ref'] ? '&' : '') . '$' . $name;
if (!$argument['required']) {
$argsLine = ($argument['type']
? $argument['type'] . ' '
: '') . ($argument['by_ref'] ? '&' : '') . '$' . $name;
if (! $argument['required']) {
$argsLine .= ' = ' . var_export($argument['default'], true);
}
$args[] = $argsLine;
@@ -169,7 +190,7 @@ class FunctionReflection extends ReflectionFunction implements ReflectionInterfa
public function getParameters()
{
$phpReflections = parent::getParameters();
$zendReflections = array();
$zendReflections = [];
while ($phpReflections && ($phpReflection = array_shift($phpReflections))) {
$instance = new ParameterReflection($this->getName(), $phpReflection->getName());
$zendReflections[] = $instance;
@@ -189,7 +210,7 @@ class FunctionReflection extends ReflectionFunction implements ReflectionInterfa
public function getReturn()
{
$docBlock = $this->getDocBlock();
if (!$docBlock->hasTag('return')) {
if (! $docBlock->hasTag('return')) {
throw new Exception\InvalidArgumentException(
'Function does not specify an @return annotation tag; cannot determine return type'
);
@@ -226,7 +247,7 @@ class FunctionReflection extends ReflectionFunction implements ReflectionInterfa
$lines = array_slice(
file($fileName, FILE_IGNORE_NEW_LINES),
$startLine - 1,
($endLine - ($startLine - 1)),
$endLine - ($startLine - 1),
true
);
@@ -239,7 +260,7 @@ class FunctionReflection extends ReflectionFunction implements ReflectionInterfa
$body = $matches[2];
}
} else {
$name = substr($this->getName(), strrpos($this->getName(), '\\')+1);
$name = substr($this->getName(), strrpos($this->getName(), '\\') + 1);
preg_match('#function\s+' . $name . '\s*\([^\)]*\)\s*{([^{}]+({[^}]+})*[^}]+)}#', $functionLine, $matches);
if (isset($matches[1])) {
$body = $matches[1];

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -14,6 +14,21 @@ use Zend\Code\Annotation\AnnotationManager;
use Zend\Code\Scanner\AnnotationScanner;
use Zend\Code\Scanner\CachingFileScanner;
use function array_shift;
use function array_slice;
use function class_exists;
use function count;
use function file;
use function file_exists;
use function implode;
use function is_array;
use function rtrim;
use function strlen;
use function substr;
use function token_get_all;
use function token_name;
use function var_export;
class MethodReflection extends PhpReflectionMethod implements ReflectionInterface
{
/**
@@ -29,7 +44,7 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
/**
* @var AnnotationScanner
*/
protected $annotations = null;
protected $annotations;
/**
* Retrieve method DocBlock reflection
@@ -49,7 +64,7 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
/**
* @param AnnotationManager $annotationManager
* @return AnnotationScanner
* @return AnnotationScanner|false
*/
public function getAnnotations(AnnotationManager $annotationManager)
{
@@ -64,7 +79,7 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
$cachingFileScanner = $this->createFileScanner($this->getFileName());
$nameInformation = $cachingFileScanner->getClassNameInformation($this->getDeclaringClass()->getName());
if (!$nameInformation) {
if (! $nameInformation) {
return false;
}
@@ -107,7 +122,8 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
/**
* Get method prototype
*
* @return array
* @param string $format
* @return array|string
*/
public function getPrototype($format = MethodReflection::PROTOTYPE_AS_ARRAY)
{
@@ -120,31 +136,33 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
}
$declaringClass = $this->getDeclaringClass();
$prototype = array(
$prototype = [
'namespace' => $declaringClass->getNamespaceName(),
'class' => substr($declaringClass->getName(), strlen($declaringClass->getNamespaceName()) + 1),
'name' => $this->getName(),
'visibility' => ($this->isPublic() ? 'public' : ($this->isPrivate() ? 'private' : 'protected')),
'visibility' => $this->isPublic() ? 'public' : ($this->isPrivate() ? 'private' : 'protected'),
'return' => $returnType,
'arguments' => array(),
);
'arguments' => [],
];
$parameters = $this->getParameters();
foreach ($parameters as $parameter) {
$prototype['arguments'][$parameter->getName()] = array(
'type' => $parameter->getType(),
'required' => !$parameter->isOptional(),
$prototype['arguments'][$parameter->getName()] = [
'type' => $parameter->detectType(),
'required' => ! $parameter->isOptional(),
'by_ref' => $parameter->isPassedByReference(),
'default' => $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null,
);
];
}
if ($format == MethodReflection::PROTOTYPE_AS_STRING) {
$line = $prototype['visibility'] . ' ' . $prototype['return'] . ' ' . $prototype['name'] . '(';
$args = array();
$args = [];
foreach ($prototype['arguments'] as $name => $argument) {
$argsLine = ($argument['type'] ? $argument['type'] . ' ' : '') . ($argument['by_ref'] ? '&' : '') . '$' . $name;
if (!$argument['required']) {
$argsLine = ($argument['type'] ?
$argument['type'] . ' '
: '') . ($argument['by_ref'] ? '&' : '') . '$' . $name;
if (! $argument['required']) {
$argsLine .= ' = ' . var_export($argument['default'], true);
}
$args[] = $argsLine;
@@ -166,10 +184,10 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
public function getParameters()
{
$phpReflections = parent::getParameters();
$zendReflections = array();
$zendReflections = [];
while ($phpReflections && ($phpReflection = array_shift($phpReflections))) {
$instance = new ParameterReflection(
array($this->getDeclaringClass()->getName(), $this->getName()),
[$this->getDeclaringClass()->getName(), $this->getName()],
$phpReflection->getName()
);
$zendReflections[] = $instance;
@@ -189,7 +207,7 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
public function getContents($includeDocBlock = true)
{
$docComment = $this->getDocComment();
$content = ($includeDocBlock && !empty($docComment)) ? $docComment . "\n" : '';
$content = $includeDocBlock && ! empty($docComment) ? $docComment . "\n" : '';
$content .= $this->extractMethodContents();
return $content;
@@ -222,17 +240,17 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
$lines = array_slice(
file($fileName, FILE_IGNORE_NEW_LINES),
$this->getStartLine() - 1,
($this->getEndLine() - ($this->getStartLine() - 1)),
$this->getEndLine() - ($this->getStartLine() - 1),
true
);
$functionLine = implode("\n", $lines);
$tokens = token_get_all("<?php ". $functionLine);
$tokens = token_get_all('<?php ' . $functionLine);
//remove first entry which is php open tag
array_shift($tokens);
if (!count($tokens)) {
if (! count($tokens)) {
return '';
}
@@ -241,17 +259,17 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
$body = '';
foreach ($tokens as $key => $token) {
$tokenType = (is_array($token)) ? token_name($token[0]) : $token;
$tokenValue = (is_array($token)) ? $token[1] : $token;
$tokenType = is_array($token) ? token_name($token[0]) : $token;
$tokenValue = is_array($token) ? $token[1] : $token;
switch ($tokenType) {
case "T_FINAL":
case "T_ABSTRACT":
case "T_PUBLIC":
case "T_PROTECTED":
case "T_PRIVATE":
case "T_STATIC":
case "T_FUNCTION":
case 'T_FINAL':
case 'T_ABSTRACT':
case 'T_PUBLIC':
case 'T_PROTECTED':
case 'T_PRIVATE':
case 'T_STATIC':
case 'T_FUNCTION':
// check to see if we have a valid function
// then check if we are inside function and have a closure
if ($this->isValidFunction($tokens, $key, $this->getName())) {
@@ -267,33 +285,33 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
$capture = true;
} else {
//closure test
if ($firstBrace && $tokenType == "T_FUNCTION") {
if ($firstBrace && $tokenType == 'T_FUNCTION') {
$body .= $tokenValue;
continue;
break;
}
$capture = false;
continue;
break;
}
break;
case "{":
case '{':
if ($capture === false) {
continue;
break;
}
if ($firstBrace === false) {
$firstBrace = true;
if ($bodyOnly === true) {
continue;
break;
}
}
$body .= $tokenValue;
break;
case "}":
case '}':
if ($capture === false) {
continue;
break;
}
//check to see if this is the last brace
@@ -311,12 +329,12 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
default:
if ($capture === false) {
continue;
break;
}
// if returning body only wait for first brace before capturing
if ($bodyOnly === true && $firstBrace !== true) {
continue;
break;
}
$body .= $tokenValue;
@@ -339,16 +357,16 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
{
$content = '';
$count = count($haystack);
if ($position+1 == $count) {
if ($position + 1 == $count) {
return $content;
}
for ($i = $position-1;$i >= 0;$i--) {
$tokenType = (is_array($haystack[$i])) ? token_name($haystack[$i][0]) : $haystack[$i];
$tokenValue = (is_array($haystack[$i])) ? $haystack[$i][1] : $haystack[$i];
for ($i = $position - 1; $i >= 0; $i--) {
$tokenType = is_array($haystack[$i]) ? token_name($haystack[$i][0]) : $haystack[$i];
$tokenValue = is_array($haystack[$i]) ? $haystack[$i][1] : $haystack[$i];
//search only for whitespace
if ($tokenType == "T_WHITESPACE") {
if ($tokenType == 'T_WHITESPACE') {
$content .= $tokenValue;
} else {
break;
@@ -370,24 +388,24 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
$count = count($haystack);
//advance one position
$position = $position+1;
$position = $position + 1;
if ($position == $count) {
return true;
}
for ($i = $position;$i < $count; $i++) {
$tokenType = (is_array($haystack[$i])) ? token_name($haystack[$i][0]) : $haystack[$i];
for ($i = $position; $i < $count; $i++) {
$tokenType = is_array($haystack[$i]) ? token_name($haystack[$i][0]) : $haystack[$i];
switch ($tokenType) {
case "T_FINAL":
case "T_ABSTRACT":
case "T_PUBLIC":
case "T_PROTECTED":
case "T_PRIVATE":
case "T_STATIC":
case 'T_FINAL':
case 'T_ABSTRACT':
case 'T_PUBLIC':
case 'T_PROTECTED':
case 'T_PRIVATE':
case 'T_STATIC':
return true;
case "T_FUNCTION":
case 'T_FUNCTION':
// If a function is encountered and that function is not a closure
// then return true. otherwise the function is a closure, return false
if ($this->isValidFunction($haystack, $i)) {
@@ -395,32 +413,31 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
}
return false;
case "}":
case ";";
case "T_BREAK":
case "T_CATCH":
case "T_DO":
case "T_ECHO":
case "T_ELSE":
case "T_ELSEIF":
case "T_EVAL":
case "T_EXIT":
case "T_FINALLY":
case "T_FOR":
case "T_FOREACH":
case "T_GOTO":
case "T_IF":
case "T_INCLUDE":
case "T_INCLUDE_ONCE":
case "T_PRINT":
case "T_STRING":
case "T_STRING_VARNAME":
case "T_THROW":
case "T_USE":
case "T_VARIABLE":
case "T_WHILE":
case "T_YIELD":
case '}':
case ';':
case 'T_BREAK':
case 'T_CATCH':
case 'T_DO':
case 'T_ECHO':
case 'T_ELSE':
case 'T_ELSEIF':
case 'T_EVAL':
case 'T_EXIT':
case 'T_FINALLY':
case 'T_FOR':
case 'T_FOREACH':
case 'T_GOTO':
case 'T_IF':
case 'T_INCLUDE':
case 'T_INCLUDE_ONCE':
case 'T_PRINT':
case 'T_STRING':
case 'T_STRING_VARNAME':
case 'T_THROW':
case 'T_USE':
case 'T_VARIABLE':
case 'T_WHILE':
case 'T_YIELD':
return false;
}
}
@@ -439,12 +456,12 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
{
$isValid = false;
$count = count($haystack);
for ($i = $position+1; $i < $count; $i++) {
$tokenType = (is_array($haystack[$i])) ? token_name($haystack[$i][0]) : $haystack[$i];
$tokenValue = (is_array($haystack[$i])) ? $haystack[$i][1] : $haystack[$i];
for ($i = $position + 1; $i < $count; $i++) {
$tokenType = is_array($haystack[$i]) ? token_name($haystack[$i][0]) : $haystack[$i];
$tokenValue = is_array($haystack[$i]) ? $haystack[$i][1] : $haystack[$i];
//check for occurance of ( or
if ($tokenType == "T_STRING") {
//check for occurrence of ( or
if ($tokenType == 'T_STRING') {
//check to see if function name is passed, if so validate against that
if ($functionName !== null && $tokenValue != $functionName) {
$isValid = false;
@@ -453,7 +470,7 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
$isValid = true;
break;
} elseif ($tokenValue == "(") {
} elseif ($tokenValue == '(') {
break;
}
}
@@ -480,7 +497,7 @@ class MethodReflection extends PhpReflectionMethod implements ReflectionInterfac
/**
* Creates a new FileScanner instance.
*
* By having this as a seperate method it allows the method to be overridden
* By having this as a separate method it allows the method to be overridden
* if a different FileScanner is needed.
*
* @param string $filename

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,6 +11,8 @@ namespace Zend\Code\Reflection;
use ReflectionParameter;
use function method_exists;
class ParameterReflection extends ReflectionParameter implements ReflectionInterface
{
/**
@@ -35,13 +37,13 @@ class ParameterReflection extends ReflectionParameter implements ReflectionInter
/**
* Get class reflection object
*
* @return ClassReflection
* @return null|ClassReflection
*/
public function getClass()
{
$phpReflection = parent::getClass();
if ($phpReflection === null) {
return;
return null;
}
$zendReflection = new ClassReflection($phpReflection->getName());
@@ -71,13 +73,24 @@ class ParameterReflection extends ReflectionParameter implements ReflectionInter
/**
* Get parameter type
*
* @return string
* @return string|null
*/
public function getType()
public function detectType()
{
if (method_exists($this, 'getType')
&& ($type = $this->getType())
&& $type->isBuiltin()
) {
return $type->getName();
}
// can be dropped when dropping PHP7 support:
if ($this->isArray()) {
return 'array';
} elseif (method_exists($this, 'isCallable') && $this->isCallable()) {
}
// can be dropped when dropping PHP7 support:
if ($this->isCallable()) {
return 'callable';
}
@@ -86,16 +99,18 @@ class ParameterReflection extends ReflectionParameter implements ReflectionInter
}
$docBlock = $this->getDeclaringFunction()->getDocBlock();
if (!$docBlock instanceof DocBlockReflection) {
return;
if (! $docBlock instanceof DocBlockReflection) {
return null;
}
$params = $docBlock->getTags('param');
if (isset($params[$this->getPosition()])) {
return $params[$this->getPosition()]->getType();
}
return;
return null;
}
/**

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -53,7 +53,7 @@ class PropertyReflection extends PhpReflectionProperty implements ReflectionInte
*/
public function getDocBlock()
{
if (!($docComment = $this->getDocComment())) {
if (! ($docComment = $this->getDocComment())) {
return false;
}
@@ -64,7 +64,7 @@ class PropertyReflection extends PhpReflectionProperty implements ReflectionInte
/**
* @param AnnotationManager $annotationManager
* @return AnnotationScanner
* @return AnnotationScanner|false
*/
public function getAnnotations(AnnotationManager $annotationManager)
{
@@ -80,7 +80,7 @@ class PropertyReflection extends PhpReflectionProperty implements ReflectionInte
$cachingFileScanner = $this->createFileScanner($class->getFileName());
$nameInformation = $cachingFileScanner->getClassNameInformation($class->getName());
if (!$nameInformation) {
if (! $nameInformation) {
return false;
}
@@ -100,7 +100,7 @@ class PropertyReflection extends PhpReflectionProperty implements ReflectionInte
/**
* Creates a new FileScanner instance.
*
* By having this as a seperate method it allows the method to be overridden
* By having this as a separate method it allows the method to be overridden
* if a different FileScanner is needed.
*
* @param string $filename

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -27,18 +27,13 @@ class AggregateDirectoryScanner extends DirectoryScanner
// @todo
}
/*
public function getUses($returnScannerClass = false)
{}
*/
public function getIncludes($returnScannerClass = false)
{
}
public function getClasses($returnScannerClass = false, $returnDerivedScannerClass = false)
{
$classes = array();
$classes = [];
foreach ($this->directories as $scanner) {
$classes += $scanner->getClasses();
}
@@ -65,7 +60,7 @@ class AggregateDirectoryScanner extends DirectoryScanner
}
}
return (isset($scanner));
return isset($scanner);
}
/**
@@ -85,7 +80,7 @@ class AggregateDirectoryScanner extends DirectoryScanner
}
}
if (!isset($scanner)) {
if (! isset($scanner)) {
throw new Exception\RuntimeException('Class by that name was not found.');
}
@@ -101,8 +96,8 @@ class AggregateDirectoryScanner extends DirectoryScanner
{
$this->scan();
if (!$returnScannerClass) {
$functions = array();
if (! $returnScannerClass) {
$functions = [];
foreach ($this->infos as $info) {
if ($info['type'] == 'function') {
$functions[] = $info['name'];

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -13,6 +13,18 @@ use Zend\Code\Annotation\AnnotationCollection;
use Zend\Code\Annotation\AnnotationManager;
use Zend\Code\NameInformation;
use function array_pop;
use function current;
use function in_array;
use function is_string;
use function next;
use function preg_match;
use function reset;
use function strlen;
use function strpos;
use function substr;
use function substr_count;
class AnnotationScanner extends AnnotationCollection implements ScannerInterface
{
/**
@@ -23,22 +35,22 @@ class AnnotationScanner extends AnnotationCollection implements ScannerInterface
/**
* @var string
*/
protected $docComment = null;
protected $docComment;
/**
* @var NameInformation
*/
protected $nameInformation = null;
protected $nameInformation;
/**
* @var AnnotationManager
*/
protected $annotationManager = null;
protected $annotationManager;
/**
* @var array
*/
protected $annotations = array();
protected $annotations = [];
/**
* @param AnnotationManager $annotationManager
@@ -70,7 +82,7 @@ class AnnotationScanner extends AnnotationCollection implements ScannerInterface
*/
protected function scan(array $tokens)
{
$annotations = array();
$annotations = [];
$annotationIndex = -1;
$contentEnd = false;
@@ -80,28 +92,27 @@ class AnnotationScanner extends AnnotationCollection implements ScannerInterface
$token = current($tokens);
switch ($token[0]) {
case 'ANNOTATION_CLASS':
$contentEnd = false;
$annotationIndex++;
$class = substr($token[1], 1);
$class = $this->nameInformation->resolveName($class);
$annotations[$annotationIndex] = array($class, null);
$annotations[$annotationIndex] = [$class, null];
goto SCANNER_CONTINUE;
// goto no break needed
case 'ANNOTATION_CONTENT_START':
$annotations[$annotationIndex][1] = '';
//fall-through
// fall-through
case 'ANNOTATION_CONTENT_END':
case 'ANNOTATION_CONTENT':
case 'ANNOTATION_WHITESPACE':
case 'ANNOTATION_NEWLINE':
if (!$contentEnd && isset($annotations[$annotationIndex]) && is_string($annotations[$annotationIndex][1])) {
if (! $contentEnd
&& isset($annotations[$annotationIndex])
&& is_string($annotations[$annotationIndex][1])
) {
$annotations[$annotationIndex][1] .= $token[1];
}
@@ -110,6 +121,7 @@ class AnnotationScanner extends AnnotationCollection implements ScannerInterface
}
goto SCANNER_CONTINUE;
// goto no break needed
}
SCANNER_CONTINUE:
@@ -142,7 +154,7 @@ class AnnotationScanner extends AnnotationCollection implements ScannerInterface
$context = 0x00;
$stream = $this->docComment;
$streamIndex = null;
$tokens = array();
$tokens = [];
$tokenIndex = null;
$currentChar = null;
$currentWord = null;
@@ -150,21 +162,31 @@ class AnnotationScanner extends AnnotationCollection implements ScannerInterface
$annotationParentCount = 0;
$MACRO_STREAM_ADVANCE_CHAR = function ($positionsForward = 1) use (&$stream, &$streamIndex, &$currentChar, &$currentWord, &$currentLine) {
$positionsForward = ($positionsForward > 0) ? $positionsForward : 1;
$streamIndex = ($streamIndex === null) ? 0 : $streamIndex + $positionsForward;
if (!isset($stream[$streamIndex])) {
$MACRO_STREAM_ADVANCE_CHAR = function ($positionsForward = 1) use (
&$stream,
&$streamIndex,
&$currentChar,
&$currentWord,
&$currentLine
) {
$positionsForward = $positionsForward > 0 ? $positionsForward : 1;
$streamIndex = $streamIndex === null ? 0 : $streamIndex + $positionsForward;
if (! isset($stream[$streamIndex])) {
$currentChar = false;
return false;
}
$currentChar = $stream[$streamIndex];
$matches = array();
$currentLine = (preg_match('#(.*?)(?:\n|\r\n?)#', $stream, $matches, null, $streamIndex) === 1) ? $matches[1] : substr($stream, $streamIndex);
$matches = [];
$currentLine = preg_match('#(.*?)(?:\n|\r\n?)#', $stream, $matches, null, $streamIndex) === 1
? $matches[1]
: substr($stream, $streamIndex);
if ($currentChar === ' ') {
$currentWord = (preg_match('#( +)#', $currentLine, $matches) === 1) ? $matches[1] : $currentLine;
$currentWord = preg_match('#( +)#', $currentLine, $matches) === 1 ? $matches[1] : $currentLine;
} else {
$currentWord = (($matches = strpos($currentLine, ' ')) !== false) ? substr($currentLine, 0, $matches) : $currentLine;
$currentWord = ($matches = strpos($currentLine, ' ')) !== false
? substr($currentLine, 0, $matches)
: $currentLine;
}
return $currentChar;
@@ -176,8 +198,8 @@ class AnnotationScanner extends AnnotationCollection implements ScannerInterface
return $MACRO_STREAM_ADVANCE_CHAR(strlen($currentLine));
};
$MACRO_TOKEN_ADVANCE = function () use (&$tokenIndex, &$tokens) {
$tokenIndex = ($tokenIndex === null) ? 0 : $tokenIndex + 1;
$tokens[$tokenIndex] = array('ANNOTATION_UNKNOWN', '');
$tokenIndex = $tokenIndex === null ? 0 : $tokenIndex + 1;
$tokens[$tokenIndex] = ['ANNOTATION_UNKNOWN', ''];
};
$MACRO_TOKEN_SET_TYPE = function ($type) use (&$tokenIndex, &$tokens) {
$tokens[$tokenIndex][0] = $type;
@@ -192,7 +214,7 @@ class AnnotationScanner extends AnnotationCollection implements ScannerInterface
$tokens[$tokenIndex][1] .= $currentLine;
};
$MACRO_HAS_CONTEXT = function ($which) use (&$context) {
return (($context & $which) === $which);
return ($context & $which) === $which;
};
$MACRO_STREAM_ADVANCE_CHAR();
@@ -213,7 +235,7 @@ class AnnotationScanner extends AnnotationCollection implements ScannerInterface
}
if ($MACRO_HAS_CONTEXT($CONTEXT_CLASS)) {
if (in_array($currentChar, array(' ', '(', "\n", "\r"))) {
if (in_array($currentChar, [' ', '(', "\n", "\r"])) {
$context &= ~$CONTEXT_CLASS;
$MACRO_TOKEN_ADVANCE();
} else {
@@ -226,8 +248,8 @@ class AnnotationScanner extends AnnotationCollection implements ScannerInterface
}
// Since we don't know what line endings are used in the file, we check for all scenarios. If we find a
// cariage return (\r), we check the next character for a line feed (\n). If so we consume it and act as
// if the cariage return was a line feed.
// carriage return (\r), we check the next character for a line feed (\n). If so we consume it and act as
// if the carriage return was a line feed.
$lineEnded = $currentChar === "\n";
if ($currentChar === "\r") {
$lineEnded = true;
@@ -253,7 +275,11 @@ class AnnotationScanner extends AnnotationCollection implements ScannerInterface
}
if ($currentChar === ' ') {
$MACRO_TOKEN_SET_TYPE(($MACRO_HAS_CONTEXT($CONTEXT_ASTERISK)) ? 'ANNOTATION_WHITESPACE' : 'ANNOTATION_WHITESPACE_INDENT');
$MACRO_TOKEN_SET_TYPE(
$MACRO_HAS_CONTEXT($CONTEXT_ASTERISK)
? 'ANNOTATION_WHITESPACE'
: 'ANNOTATION_WHITESPACE_INDENT'
);
$MACRO_TOKEN_APPEND_WORD();
$MACRO_TOKEN_ADVANCE();
if ($MACRO_STREAM_ADVANCE_WORD() === false) {

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -13,17 +13,23 @@ use Zend\Code\Annotation\AnnotationManager;
use Zend\Code\Exception;
use Zend\Code\NameInformation;
use function file_exists;
use function md5;
use function realpath;
use function spl_object_hash;
use function sprintf;
class CachingFileScanner extends FileScanner
{
/**
* @var array
*/
protected static $cache = array();
protected static $cache = [];
/**
* @var null|FileScanner
*/
protected $fileScanner = null;
protected $fileScanner;
/**
* @param string $file
@@ -32,7 +38,7 @@ class CachingFileScanner extends FileScanner
*/
public function __construct($file, AnnotationManager $annotationManager = null)
{
if (!file_exists($file)) {
if (! file_exists($file)) {
throw new Exception\InvalidArgumentException(sprintf(
'File "%s" not found',
$file
@@ -41,7 +47,9 @@ class CachingFileScanner extends FileScanner
$file = realpath($file);
$cacheId = md5($file) . '/' . ((isset($annotationManager) ? spl_object_hash($annotationManager) : 'no-annotation'));
$cacheId = md5($file) . '/' . (isset($annotationManager)
? spl_object_hash($annotationManager)
: 'no-annotation');
if (isset(static::$cache[$cacheId])) {
$this->fileScanner = static::$cache[$cacheId];
@@ -56,7 +64,7 @@ class CachingFileScanner extends FileScanner
*/
public static function clearCache()
{
static::$cache = array();
static::$cache = [];
}
/**

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -14,6 +14,24 @@ use Zend\Code\Annotation;
use Zend\Code\Exception;
use Zend\Code\NameInformation;
use function array_key_exists;
use function array_merge;
use function array_search;
use function array_slice;
use function array_values;
use function define;
use function defined;
use function explode;
use function in_array;
use function is_array;
use function is_int;
use function is_object;
use function is_string;
use function ltrim;
use function sprintf;
use function substr_count;
use function trigger_error;
class ClassScanner implements ScannerInterface
{
/**
@@ -24,27 +42,27 @@ class ClassScanner implements ScannerInterface
/**
* @var string
*/
protected $docComment = null;
protected $docComment;
/**
* @var string
*/
protected $name = null;
protected $name;
/**
* @var string
*/
protected $shortName = null;
protected $shortName;
/**
* @var int
*/
protected $lineStart = null;
protected $lineStart;
/**
* @var int
*/
protected $lineEnd = null;
protected $lineEnd;
/**
* @var bool
@@ -69,47 +87,47 @@ class ClassScanner implements ScannerInterface
/**
* @var string
*/
protected $parentClass = null;
protected $parentClass;
/**
* @var string
*/
protected $shortParentClass = null;
protected $shortParentClass;
/**
* @var array
*/
protected $interfaces = array();
protected $interfaces = [];
/**
* @var array
*/
protected $shortInterfaces = array();
protected $shortInterfaces = [];
/**
* @var array
*/
protected $tokens = array();
protected $tokens = [];
/**
* @var NameInformation
*/
protected $nameInformation = null;
protected $nameInformation;
/**
* @var array
*/
protected $infos = array();
protected $infos = [];
/**
* @var array
*/
protected $traits = array();
protected $traits = [];
/**
* @var array
*/
protected $methods = array();
protected $methods = [];
/**
* @param array $classTokens
@@ -156,7 +174,7 @@ class ClassScanner implements ScannerInterface
*/
public function getDocBlock()
{
if (!$docComment = $this->getDocComment()) {
if (! $docComment = $this->getDocComment()) {
return false;
}
@@ -220,6 +238,7 @@ class ClassScanner implements ScannerInterface
/**
* Verify if class is a trait
*
* @return bool
*/
public function isTrait()
@@ -236,7 +255,7 @@ class ClassScanner implements ScannerInterface
public function isInstantiable()
{
$this->scan();
return (!$this->isAbstract && !$this->isInterface);
return ! $this->isAbstract && ! $this->isInterface && ! $this->isTrait;
}
/**
@@ -269,7 +288,7 @@ class ClassScanner implements ScannerInterface
public function hasParentClass()
{
$this->scan();
return ($this->parentClass !== null);
return $this->parentClass !== null;
}
/**
@@ -303,7 +322,7 @@ class ClassScanner implements ScannerInterface
{
$this->scan();
$return = array();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] != 'constant') {
continue;
@@ -330,7 +349,7 @@ class ClassScanner implements ScannerInterface
$this->scan();
$return = array();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] != 'constant') {
continue;
@@ -366,7 +385,7 @@ class ClassScanner implements ScannerInterface
break;
}
}
if (!$constantFound) {
if (! $constantFound) {
return false;
}
} else {
@@ -374,7 +393,7 @@ class ClassScanner implements ScannerInterface
'Invalid constant name of info index type. Must be of type int or string'
);
}
if (!isset($info)) {
if (! isset($info)) {
return false;
}
$p = new ConstantScanner(
@@ -414,7 +433,7 @@ class ClassScanner implements ScannerInterface
{
$this->scan();
$return = array();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] != 'property') {
continue;
@@ -435,7 +454,7 @@ class ClassScanner implements ScannerInterface
{
$this->scan();
$return = array();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] != 'property') {
continue;
@@ -471,7 +490,7 @@ class ClassScanner implements ScannerInterface
break;
}
}
if (!$propertyFound) {
if (! $propertyFound) {
return false;
}
} else {
@@ -479,7 +498,7 @@ class ClassScanner implements ScannerInterface
'Invalid property name of info index type. Must be of type int or string'
);
}
if (!isset($info)) {
if (! isset($info)) {
return false;
}
$p = new PropertyScanner(
@@ -547,7 +566,9 @@ class ClassScanner implements ScannerInterface
*/
public function getTraitNames()
{
$return = array();
$this->scan();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] !== 'use') {
continue;
@@ -562,7 +583,6 @@ class ClassScanner implements ScannerInterface
$return[] = $traitName;
}
}
break;
}
return $return;
@@ -575,7 +595,9 @@ class ClassScanner implements ScannerInterface
*/
public function getTraitAliases()
{
$return = array();
$this->scan();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] !== 'use') {
continue;
@@ -598,7 +620,6 @@ class ClassScanner implements ScannerInterface
$return[$alias['alias']] = $trait . '::' . $method;
}
}
break;
}
return $return;
@@ -612,6 +633,8 @@ class ClassScanner implements ScannerInterface
*/
protected function getVisibilityForAlias($aliasName)
{
$this->scan();
$return = null;
foreach ($this->infos as $info) {
if ($info['type'] !== 'use') {
@@ -632,7 +655,6 @@ class ClassScanner implements ScannerInterface
}
}
}
break;
}
return $return;
@@ -645,7 +667,9 @@ class ClassScanner implements ScannerInterface
*/
protected function getBlockedTraitMethods()
{
$return = array();
$this->scan();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] !== 'use') {
continue;
@@ -668,7 +692,6 @@ class ClassScanner implements ScannerInterface
$return[] = $trait . '::' . $method;
}
}
break;
}
return $return;
@@ -684,7 +707,7 @@ class ClassScanner implements ScannerInterface
$this->scan();
$methods = $this->getMethods();
$return = array();
$return = [];
foreach ($methods as $method) {
$return[] = $method->getName();
}
@@ -711,8 +734,8 @@ class ClassScanner implements ScannerInterface
}
// Merge in trait methods
if ($info['type'] === "use") {
$traitMethods = array();
if ($info['type'] === 'use') {
$traitMethods = [];
$traits = $this->getTraits();
$insteadof = $this->getBlockedTraitMethods();
$aliases = $this->getTraitAliases();
@@ -845,14 +868,13 @@ class ClassScanner implements ScannerInterface
return;
}
if (!$this->tokens) {
if (! $this->tokens) {
throw new Exception\RuntimeException('No tokens were provided');
}
/**
* Variables & Setup
*/
$tokens = &$this->tokens; // localize
$infos = &$this->infos; // localize
$tokenIndex = null;
@@ -876,8 +898,8 @@ class ClassScanner implements ScannerInterface
&$tokenLine
) {
static $lastTokenArray = null;
$tokenIndex = ($tokenIndex === null) ? 0 : $tokenIndex + 1;
if (!isset($tokens[$tokenIndex])) {
$tokenIndex = $tokenIndex === null ? 0 : $tokenIndex + 1;
if (! isset($tokens[$tokenIndex])) {
$token = false;
$tokenContent = false;
$tokenType = false;
@@ -890,13 +912,13 @@ class ClassScanner implements ScannerInterface
if (is_string($token)) {
$tokenType = null;
$tokenContent = $token;
$tokenLine = $tokenLine + substr_count(
$lastTokenArray[1],
$tokenLine += substr_count(
$lastTokenArray[1] ?? '',
"\n"
); // adjust token line by last known newline count
} else {
$lastTokenArray = $token;
list($tokenType, $tokenContent, $tokenLine) = $token;
[$tokenType, $tokenContent, $tokenLine] = $token;
}
return $tokenIndex;
@@ -912,16 +934,13 @@ class ClassScanner implements ScannerInterface
/**
* START FINITE STATE MACHINE FOR SCANNING TOKENS
*/
// Initialize token
$MACRO_TOKEN_ADVANCE();
SCANNER_TOP:
switch ($tokenType) {
case T_DOC_COMMENT:
$this->docComment = $tokenContent;
goto SCANNER_CONTINUE;
//goto no break needed
@@ -931,7 +950,6 @@ class ClassScanner implements ScannerInterface
case T_CLASS:
case T_INTERFACE:
case T_TRAIT:
// CLASS INFORMATION
$classContext = null;
@@ -946,7 +964,6 @@ class ClassScanner implements ScannerInterface
$this->lineStart = $tokenLine;
switch ($tokenType) {
case T_FINAL:
$this->isFinal = true;
goto SCANNER_CLASS_INFO_CONTINUE;
@@ -966,10 +983,11 @@ class ClassScanner implements ScannerInterface
$this->name = $this->shortName;
}
goto SCANNER_CLASS_INFO_CONTINUE;
// goto no break needed
case T_INTERFACE:
$this->isInterface = true;
//fall-through
// fall-through
case T_CLASS:
$this->shortName = $tokens[$tokenIndex + 2][1];
if ($this->nameInformation && $this->nameInformation->hasNamespace()) {
@@ -978,38 +996,43 @@ class ClassScanner implements ScannerInterface
$this->name = $this->shortName;
}
goto SCANNER_CLASS_INFO_CONTINUE;
//goto no break needed
// goto no break needed
case T_NS_SEPARATOR:
case T_STRING:
switch ($classContext) {
case T_EXTENDS:
$this->shortParentClass .= $tokenContent;
if ($this->isInterface) {
$this->shortInterfaces[$classInterfaceIndex] .= $tokenContent;
} else {
$this->shortParentClass .= $tokenContent;
}
break;
case T_IMPLEMENTS:
$this->shortInterfaces[$classInterfaceIndex] .= $tokenContent;
break;
}
goto SCANNER_CLASS_INFO_CONTINUE;
//goto no break needed
// goto no break needed
case T_EXTENDS:
case T_IMPLEMENTS:
$classContext = $tokenType;
if (($this->isInterface && $classContext === T_EXTENDS) || $classContext === T_IMPLEMENTS) {
$this->shortInterfaces[$classInterfaceIndex] = '';
} elseif (!$this->isInterface && $classContext === T_EXTENDS) {
} elseif (! $this->isInterface && $classContext === T_EXTENDS) {
$this->shortParentClass = '';
}
goto SCANNER_CLASS_INFO_CONTINUE;
//goto no break needed
// goto no break needed
case null:
if ($classContext == T_IMPLEMENTS && $tokenContent == ',') {
if (($classContext == T_IMPLEMENTS && $tokenContent == ',')
|| ($classContext == T_EXTENDS && $tokenContent == ',' && $this->isInterface)
) {
$classInterfaceIndex++;
$this->shortInterfaces[$classInterfaceIndex] = '';
}
}
SCANNER_CLASS_INFO_CONTINUE:
@@ -1022,7 +1045,6 @@ class ClassScanner implements ScannerInterface
SCANNER_CLASS_INFO_END:
goto SCANNER_CONTINUE;
}
if ($tokenType === null && $tokenContent === '{' && $braceCount === 0) {
@@ -1038,10 +1060,8 @@ class ClassScanner implements ScannerInterface
}
switch ($tokenType) {
case T_CONST:
$infos[$infoIndex] = array(
$infos[$infoIndex] = [
'type' => 'constant',
'tokenStart' => $tokenIndex,
'tokenEnd' => null,
@@ -1049,7 +1069,7 @@ class ClassScanner implements ScannerInterface
'lineEnd' => null,
'name' => null,
'value' => null,
);
];
SCANNER_CLASS_BODY_CONST_TOP:
@@ -1080,21 +1100,21 @@ class ClassScanner implements ScannerInterface
define('T_INSTEADOF', 24000);
}
$infos[$infoIndex] = array(
$infos[$infoIndex] = [
'type' => 'use',
'tokenStart' => $tokenIndex,
'tokenEnd' => null,
'lineStart' => $tokens[$tokenIndex][2],
'lineEnd' => null,
'name' => $namespace,
'use_statements' => array(0 => null),
'aliases' => array(0 => null),
);
'use_statements' => [0 => null],
'aliases' => [0 => null],
];
$isOriginalName = array(T_STRING, T_DOUBLE_COLON);
$isAlias = array(T_STRING);
$isVisibility = array(T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC);
$isAliasType = array(T_AS, T_INSTEADOF);
$isOriginalName = [T_STRING, T_DOUBLE_COLON];
$isAlias = [T_STRING];
$isVisibility = [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC];
$isAliasType = [T_AS, T_INSTEADOF];
$isValidAlias = array_merge($isOriginalName, $isAlias, $isVisibility, $isAliasType);
$useStatementIndex = 0;
@@ -1110,16 +1130,16 @@ class ClassScanner implements ScannerInterface
SCANNER_USE_TOP:
if ($tokenType === null) {
if ($tokenContent === "{") {
if ($tokenContent === '{') {
$useStatementIndex = 0;
$useAliasContext = true;
$infos[$infoIndex]['aliases'][$useStatementIndex] = array(
$infos[$infoIndex]['aliases'][$useStatementIndex] = [
'original' => null,
'alias' => null,
'visibility' => null,
'type' => 'as'
);
} elseif ($tokenContent === "}") {
'type' => 'as',
];
} elseif ($tokenContent === '}') {
$useAliasContext = false;
goto SCANNER_USE_END;
} elseif ($tokenContent === ';') {
@@ -1148,17 +1168,17 @@ class ClassScanner implements ScannerInterface
if (in_array($tokenType, $isValidAlias)
&& empty($infos[$infoIndex]['aliases'][$useStatementIndex])
) {
$infos[$infoIndex]['aliases'][$useStatementIndex] = array(
$infos[$infoIndex]['aliases'][$useStatementIndex] = [
'original' => null,
'visibility' => null,
'alias' => null,
'type' => null
);
'type' => null,
];
}
if ($tokenType == T_AS || $tokenType == T_INSTEADOF) {
$useAsContext = true;
$infos[$infoIndex]['aliases'][$useStatementIndex]['type'] = ($tokenType == T_INSTEADOF)
$infos[$infoIndex]['aliases'][$useStatementIndex]['type'] = $tokenType == T_INSTEADOF
? 'insteadof'
: 'as';
goto SCANNER_USE_CONTINUE;
@@ -1187,6 +1207,7 @@ class ClassScanner implements ScannerInterface
$MACRO_INFO_ADVANCE();
goto SCANNER_CLASS_BODY_CONTINUE;
// goto no break needed
case T_DOC_COMMENT:
case T_PUBLIC:
@@ -1196,15 +1217,14 @@ class ClassScanner implements ScannerInterface
case T_FINAL:
case T_VAR:
case T_FUNCTION:
$infos[$infoIndex] = array(
$infos[$infoIndex] = [
'type' => null,
'tokenStart' => $tokenIndex,
'tokenEnd' => null,
'lineStart' => $tokenLine,
'lineEnd' => null,
'name' => null,
);
];
$memberContext = null;
$methodBodyStarted = false;
@@ -1218,19 +1238,21 @@ class ClassScanner implements ScannerInterface
$braceCount++;
goto SCANNER_CLASS_BODY_MEMBER_CONTINUE;
// goto no break needed
case '}':
$braceCount--;
goto SCANNER_CLASS_BODY_MEMBER_CONTINUE;
// goto no break needed
case ';':
$infos[$infoIndex]['tokenEnd'] = $tokenIndex;
goto SCANNER_CLASS_BODY_MEMBER_CONTINUE;
// goto no break needed
}
}
if ($memberContext !== null) {
if (
($memberContext === 'property' && $tokenContent === ';')
if (($memberContext === 'property' && $tokenContent === ';')
|| ($memberContext === 'method' && $methodBodyStarted && $braceCount === 1)
|| ($memberContext === 'method' && $this->isInterface && $tokenContent === ';')
) {
@@ -1239,7 +1261,6 @@ class ClassScanner implements ScannerInterface
}
switch ($tokenType) {
case T_CONST:
$memberContext = 'constant';
$infos[$infoIndex]['type'] = 'constant';
@@ -1284,7 +1305,6 @@ class ClassScanner implements ScannerInterface
// goto no break needed
case null: // no type, is a string
switch ($tokenContent) {
case '{':
$braceCount++;
@@ -1294,6 +1314,7 @@ class ClassScanner implements ScannerInterface
case '}':
$braceCount--;
goto SCANNER_CLASS_BODY_CONTINUE;
// goto no break needed
}
}
@@ -1338,7 +1359,5 @@ class ClassScanner implements ScannerInterface
}
$this->isScanned = true;
return;
}
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -13,6 +13,15 @@ use Zend\Code\Annotation;
use Zend\Code\Exception;
use Zend\Code\NameInformation;
use function current;
use function is_string;
use function next;
use function reset;
use function strtolower;
use function substr;
use function strpos;
use function var_export;
class ConstantScanner implements ScannerInterface
{
/**
@@ -156,7 +165,7 @@ class ConstantScanner implements ScannerInterface
return;
}
if (!$this->tokens) {
if (! $this->tokens) {
throw new Exception\RuntimeException('No tokens were provided');
}
@@ -171,7 +180,7 @@ class ConstantScanner implements ScannerInterface
$token = current($tokens);
if (!is_string($token)) {
if (! is_string($token)) {
list($tokenType, $tokenContent, $tokenLine) = $token;
switch ($tokenType) {
@@ -183,7 +192,7 @@ class ConstantScanner implements ScannerInterface
// fall-through
case T_STRING:
$string = (is_string($token)) ? $token : $tokenContent;
$string = is_string($token) ? $token : $tokenContent;
if (null === $this->name) {
$this->name = $string;
@@ -207,9 +216,9 @@ class ConstantScanner implements ScannerInterface
case T_CONSTANT_ENCAPSED_STRING:
case T_DNUMBER:
case T_LNUMBER:
$string = (is_string($token)) ? $token : $tokenContent;
$string = is_string($token) ? $token : $tokenContent;
if (substr($string, 0, 1) === '"' || substr($string, 0, 1) === "'") {
if (0 === strpos($string, '"') || 0 === strpos($string, "'")) {
$this->value = substr($string, 1, -1); // Remove quotes
} else {
$this->value = $string;

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,27 +11,32 @@ namespace Zend\Code\Scanner;
use Zend\Code\Exception;
use function array_keys;
use function array_merge;
use function sprintf;
use function trigger_error;
class DerivedClassScanner extends ClassScanner
{
/**
* @var DirectoryScanner
*/
protected $directoryScanner = null;
protected $directoryScanner;
/**
* @var ClassScanner
*/
protected $classScanner = null;
protected $classScanner;
/**
* @var array
*/
protected $parentClassScanners = array();
protected $parentClassScanners = [];
/**
* @var array
*/
protected $interfaceClassScanners = array();
protected $interfaceClassScanners = [];
/**
* @param ClassScanner $classScanner
@@ -47,9 +52,9 @@ class DerivedClassScanner extends ClassScanner
while ($currentScannerClass && $currentScannerClass->hasParentClass()) {
$currentParentClassName = $currentScannerClass->getParentClass();
if ($directoryScanner->hasClass($currentParentClassName)) {
$currentParentClass = $directoryScanner->getClass($currentParentClassName);
$currentParentClass = $directoryScanner->getClass($currentParentClassName);
$this->parentClassScanners[$currentParentClassName] = $currentParentClass;
$currentScannerClass = $currentParentClass;
$currentScannerClass = $currentParentClass;
} else {
$currentScannerClass = false;
}
@@ -123,7 +128,7 @@ class DerivedClassScanner extends ClassScanner
*/
public function hasParentClass()
{
return ($this->classScanner->getParentClass() !== null);
return $this->classScanner->getParentClass() !== null;
}
/**

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -13,6 +13,15 @@ use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Zend\Code\Exception;
use function array_keys;
use function array_merge;
use function is_array;
use function is_dir;
use function is_string;
use function pathinfo;
use function realpath;
use function sprintf;
class DirectoryScanner implements ScannerInterface
{
/**
@@ -23,17 +32,17 @@ class DirectoryScanner implements ScannerInterface
/**
* @var string[]|DirectoryScanner[]
*/
protected $directories = array();
protected $directories = [];
/**
* @var FileScanner[]
*/
protected $fileScanners = array();
protected $fileScanners = [];
/**
* @var array
*/
protected $classToFileScanner = null;
protected $classToFileScanner;
/**
* @param null|string|array $directory
@@ -62,7 +71,7 @@ class DirectoryScanner implements ScannerInterface
$this->directories[] = $directory;
} elseif (is_string($directory)) {
$realDir = realpath($directory);
if (!$realDir || !is_dir($realDir)) {
if (! $realDir || ! is_dir($realDir)) {
throw new Exception\InvalidArgumentException(sprintf(
'Directory "%s" does not exist',
$realDir
@@ -139,9 +148,9 @@ class DirectoryScanner implements ScannerInterface
{
$this->scan();
$return = array();
$return = [];
foreach ($this->fileScanners as $fileScanner) {
$return[] = ($returnFileScanners) ? $fileScanner : $fileScanner->getFile();
$return[] = $returnFileScanners ? $fileScanner : $fileScanner->getFile();
}
return $return;
@@ -173,7 +182,7 @@ class DirectoryScanner implements ScannerInterface
$this->createClassToFileScannerCache();
}
$returnClasses = array();
$returnClasses = [];
foreach ($this->classToFileScanner as $className => $fsIndex) {
$classScanner = $this->fileScanners[$fsIndex]->getClass($className);
if ($returnDerivedScannerClass) {
@@ -197,7 +206,7 @@ class DirectoryScanner implements ScannerInterface
$this->createClassToFileScannerCache();
}
return (isset($this->classToFileScanner[$class]));
return isset($this->classToFileScanner[$class]);
}
/**
@@ -214,7 +223,7 @@ class DirectoryScanner implements ScannerInterface
$this->createClassToFileScannerCache();
}
if (!isset($this->classToFileScanner[$class])) {
if (! isset($this->classToFileScanner[$class])) {
throw new Exception\InvalidArgumentException('Class not found.');
}
@@ -222,7 +231,7 @@ class DirectoryScanner implements ScannerInterface
$fs = $this->fileScanners[$this->classToFileScanner[$class]];
$returnClass = $fs->getClass($class);
if (($returnClass instanceof ClassScanner) && $returnDerivedScannerClass) {
if ($returnClass instanceof ClassScanner && $returnDerivedScannerClass) {
return new DerivedClassScanner($returnClass, $this);
}
@@ -240,7 +249,8 @@ class DirectoryScanner implements ScannerInterface
return;
}
$this->classToFileScanner = array();
$this->classToFileScanner = [];
/** @var FileScanner $fileScanner */
foreach ($this->fileScanners as $fsIndex => $fileScanner) {
$fsClasses = $fileScanner->getClassNames();

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -12,6 +12,19 @@ namespace Zend\Code\Scanner;
use Zend\Code\Annotation\AnnotationManager;
use Zend\Code\NameInformation;
use function array_pop;
use function array_push;
use function current;
use function end;
use function key;
use function next;
use function preg_match;
use function reset;
use function strlen;
use function strpos;
use function substr;
use function trim;
class DocBlockScanner implements ScannerInterface
{
/**
@@ -22,22 +35,22 @@ class DocBlockScanner implements ScannerInterface
/**
* @var string
*/
protected $docComment = null;
protected $docComment;
/**
* @var NameInformation
*/
protected $nameInformation = null;
protected $nameInformation;
/**
* @var AnnotationManager
*/
protected $annotationManager = null;
protected $annotationManager;
/**
* @var string
*/
protected $shortDescription = null;
protected $shortDescription;
/**
* @var string
@@ -47,12 +60,12 @@ class DocBlockScanner implements ScannerInterface
/**
* @var array
*/
protected $tags = array();
protected $tags = [];
/**
* @var array
*/
protected $annotations = array();
protected $annotations = [];
/**
* @param string $docComment
@@ -135,7 +148,9 @@ class DocBlockScanner implements ScannerInterface
case 'DOCBLOCK_WHITESPACE':
case 'DOCBLOCK_TEXT':
if ($tagIndex !== null) {
$this->tags[$tagIndex]['value'] .= ($this->tags[$tagIndex]['value'] == '') ? $token[1] : ' ' . $token[1];
$this->tags[$tagIndex]['value'] .= $this->tags[$tagIndex]['value'] == ''
? $token[1]
: ' ' . $token[1];
goto SCANNER_CONTINUE;
} elseif ($mode <= 2) {
if ($mode == 1) {
@@ -147,8 +162,10 @@ class DocBlockScanner implements ScannerInterface
}
//gotos no break needed
case 'DOCBLOCK_TAG':
array_push($this->tags, array('name' => $token[1],
'value' => ''));
array_push($this->tags, [
'name' => $token[1],
'value' => '',
]);
end($this->tags);
$tagIndex = key($this->tags);
$mode = 3;
@@ -157,7 +174,6 @@ class DocBlockScanner implements ScannerInterface
case 'DOCBLOCK_COMMENTEND':
goto SCANNER_END;
}
SCANNER_CONTINUE:
@@ -184,27 +200,37 @@ class DocBlockScanner implements ScannerInterface
$context = 0x00;
$stream = $this->docComment;
$streamIndex = null;
$tokens = array();
$tokens = [];
$tokenIndex = null;
$currentChar = null;
$currentWord = null;
$currentLine = null;
$MACRO_STREAM_ADVANCE_CHAR = function ($positionsForward = 1) use (&$stream, &$streamIndex, &$currentChar, &$currentWord, &$currentLine) {
$positionsForward = ($positionsForward > 0) ? $positionsForward : 1;
$streamIndex = ($streamIndex === null) ? 0 : $streamIndex + $positionsForward;
if (!isset($stream[$streamIndex])) {
$MACRO_STREAM_ADVANCE_CHAR = function ($positionsForward = 1) use (
&$stream,
&$streamIndex,
&$currentChar,
&$currentWord,
&$currentLine
) {
$positionsForward = $positionsForward > 0 ? $positionsForward : 1;
$streamIndex = $streamIndex === null ? 0 : $streamIndex + $positionsForward;
if (! isset($stream[$streamIndex])) {
$currentChar = false;
return false;
}
$currentChar = $stream[$streamIndex];
$matches = array();
$currentLine = (preg_match('#(.*?)\r?\n#', $stream, $matches, null, $streamIndex) === 1) ? $matches[1] : substr($stream, $streamIndex);
$matches = [];
$currentLine = preg_match('#(.*?)\r?\n#', $stream, $matches, null, $streamIndex) === 1
? $matches[1]
: substr($stream, $streamIndex);
if ($currentChar === ' ') {
$currentWord = (preg_match('#( +)#', $currentLine, $matches) === 1) ? $matches[1] : $currentLine;
$currentWord = preg_match('#( +)#', $currentLine, $matches) === 1 ? $matches[1] : $currentLine;
} else {
$currentWord = (($matches = strpos($currentLine, ' ')) !== false) ? substr($currentLine, 0, $matches) : $currentLine;
$currentWord = ($matches = strpos($currentLine, ' ')) !== false
? substr($currentLine, 0, $matches)
: $currentLine;
}
return $currentChar;
@@ -216,8 +242,8 @@ class DocBlockScanner implements ScannerInterface
return $MACRO_STREAM_ADVANCE_CHAR(strlen($currentLine));
};
$MACRO_TOKEN_ADVANCE = function () use (&$tokenIndex, &$tokens) {
$tokenIndex = ($tokenIndex === null) ? 0 : $tokenIndex + 1;
$tokens[$tokenIndex] = array('DOCBLOCK_UNKNOWN', '');
$tokenIndex = $tokenIndex === null ? 0 : $tokenIndex + 1;
$tokens[$tokenIndex] = ['DOCBLOCK_UNKNOWN', ''];
};
$MACRO_TOKEN_SET_TYPE = function ($type) use (&$tokenIndex, &$tokens) {
$tokens[$tokenIndex][0] = $type;
@@ -264,7 +290,11 @@ class DocBlockScanner implements ScannerInterface
}
if ($currentChar === ' ' || $currentChar === "\t") {
$MACRO_TOKEN_SET_TYPE(($context & $CONTEXT_INSIDE_ASTERISK) ? 'DOCBLOCK_WHITESPACE' : 'DOCBLOCK_WHITESPACE_INDENT');
$MACRO_TOKEN_SET_TYPE(
$context & $CONTEXT_INSIDE_ASTERISK
? 'DOCBLOCK_WHITESPACE'
: 'DOCBLOCK_WHITESPACE_INDENT'
);
$MACRO_TOKEN_APPEND_WORD();
$MACRO_TOKEN_ADVANCE();
if ($MACRO_STREAM_ADVANCE_WORD() === false) {

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -12,12 +12,17 @@ namespace Zend\Code\Scanner;
use Zend\Code\Annotation\AnnotationManager;
use Zend\Code\Exception;
use function file_exists;
use function file_get_contents;
use function sprintf;
use function token_get_all;
class FileScanner extends TokenArrayScanner implements ScannerInterface
{
/**
* @var string
*/
protected $file = null;
protected $file;
/**
* @param string $file
@@ -27,7 +32,7 @@ class FileScanner extends TokenArrayScanner implements ScannerInterface
public function __construct($file, AnnotationManager $annotationManager = null)
{
$this->file = $file;
if (!file_exists($file)) {
if (! file_exists($file)) {
throw new Exception\InvalidArgumentException(sprintf(
'File "%s" not found',
$file

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -13,42 +13,51 @@ use Zend\Code\Annotation\AnnotationManager;
use Zend\Code\Exception;
use Zend\Code\NameInformation;
use function array_slice;
use function count;
use function is_int;
use function is_string;
use function ltrim;
use function strtolower;
use function substr_count;
use function var_export;
class MethodScanner implements ScannerInterface
{
/**
* @var bool
*/
protected $isScanned = false;
protected $isScanned = false;
/**
* @var string
*/
protected $docComment = null;
protected $docComment;
/**
* @var ClassScanner
*/
protected $scannerClass = null;
protected $scannerClass;
/**
* @var string
*/
protected $class = null;
protected $class;
/**
* @var string
*/
protected $name = null;
protected $name;
/**
* @var int
*/
protected $lineStart = null;
protected $lineStart;
/**
* @var int
*/
protected $lineEnd = null;
protected $lineEnd;
/**
* @var bool
@@ -88,17 +97,17 @@ class MethodScanner implements ScannerInterface
/**
* @var array
*/
protected $tokens = array();
protected $tokens = [];
/**
* @var NameInformation
*/
protected $nameInformation = null;
protected $nameInformation;
/**
* @var array
*/
protected $infos = array();
protected $infos = [];
/**
* @param array $methodTokens
@@ -131,7 +140,7 @@ class MethodScanner implements ScannerInterface
}
/**
* @return MethodScanner
* @return ClassScanner
*/
public function getClassScanner()
{
@@ -180,7 +189,7 @@ class MethodScanner implements ScannerInterface
/**
* @param AnnotationManager $annotationManager
* @return AnnotationScanner
* @return AnnotationScanner|false
*/
public function getAnnotations(AnnotationManager $annotationManager)
{
@@ -255,7 +264,7 @@ class MethodScanner implements ScannerInterface
* Override the given name for a method, this is necessary to
* support traits.
*
* @param $name
* @param string $name
* @return self
*/
public function setName($name)
@@ -268,13 +277,13 @@ class MethodScanner implements ScannerInterface
* Visibility must be of T_PUBLIC, T_PRIVATE or T_PROTECTED
* Needed to support traits
*
* @param $visibility T_PUBLIC | T_PRIVATE | T_PROTECTED
* @param int $visibility T_PUBLIC | T_PRIVATE | T_PROTECTED
* @return self
* @throws \Zend\Code\Exception
* @throws \Zend\Code\Exception\InvalidArgumentException
*/
public function setVisibility($visibility)
{
switch (strtolower($visibility)) {
switch ($visibility) {
case T_PUBLIC:
$this->isPublic = true;
$this->isPrivate = false;
@@ -294,7 +303,7 @@ class MethodScanner implements ScannerInterface
break;
default:
throw new Exception("Invalid visibility argument passed to setVisibility.");
throw new Exception\InvalidArgumentException('Invalid visibility argument passed to setVisibility.');
}
return $this;
@@ -316,14 +325,14 @@ class MethodScanner implements ScannerInterface
{
$this->scan();
$return = array();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] != 'parameter') {
continue;
}
if (!$returnScanner) {
if (! $returnScanner) {
$return[] = $info['name'];
} else {
$return[] = $this->getParameter($info['name']);
@@ -354,7 +363,7 @@ class MethodScanner implements ScannerInterface
}
unset($info);
}
if (!isset($info)) {
if (! isset($info)) {
throw new Exception\InvalidArgumentException('Index of info offset is not about a parameter');
}
}
@@ -400,14 +409,13 @@ class MethodScanner implements ScannerInterface
return;
}
if (!$this->tokens) {
if (! $this->tokens) {
throw new Exception\RuntimeException('No tokens were provided');
}
/**
* Variables & Setup
*/
$tokens = &$this->tokens; // localize
$infos = &$this->infos; // localize
$tokenIndex = null;
@@ -430,8 +438,8 @@ class MethodScanner implements ScannerInterface
&$tokenLine
) {
static $lastTokenArray = null;
$tokenIndex = ($tokenIndex === null) ? 0 : $tokenIndex + 1;
if (!isset($tokens[$tokenIndex])) {
$tokenIndex = $tokenIndex === null ? 0 : $tokenIndex + 1;
if (! isset($tokens[$tokenIndex])) {
$token = false;
$tokenContent = false;
$tokenType = false;
@@ -443,18 +451,19 @@ class MethodScanner implements ScannerInterface
if (is_string($token)) {
$tokenType = null;
$tokenContent = $token;
$tokenLine = $tokenLine + substr_count(
$lastTokenArray[1],
$tokenLine += substr_count(
$lastTokenArray[1] ?? '',
"\n"
); // adjust token line by last known newline count
} else {
list($tokenType, $tokenContent, $tokenLine) = $token;
$lastTokenArray = $token;
[$tokenType, $tokenContent, $tokenLine] = $token;
}
return $tokenIndex;
};
$MACRO_INFO_START = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) {
$infos[$infoIndex] = array(
$infos[$infoIndex] = [
'type' => 'parameter',
'tokenStart' => $tokenIndex,
'tokenEnd' => null,
@@ -462,7 +471,7 @@ class MethodScanner implements ScannerInterface
'lineEnd' => $tokenLine,
'name' => null,
'position' => $infoIndex + 1, // position is +1 of infoIndex
);
];
};
$MACRO_INFO_ADVANCE = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) {
$infos[$infoIndex]['tokenEnd'] = $tokenIndex;
@@ -475,13 +484,12 @@ class MethodScanner implements ScannerInterface
/**
* START FINITE STATE MACHINE FOR SCANNING TOKENS
*/
// Initialize token
$MACRO_TOKEN_ADVANCE();
SCANNER_TOP:
$this->lineStart = ($this->lineStart) ? : $tokenLine;
$this->lineStart = $this->lineStart ? : $tokenLine;
switch ($tokenType) {
case T_DOC_COMMENT:
@@ -490,47 +498,53 @@ class MethodScanner implements ScannerInterface
$this->docComment = $tokenContent;
}
goto SCANNER_CONTINUE_SIGNATURE;
//goto (no break needed);
// goto (no break needed);
case T_FINAL:
$this->isFinal = true;
goto SCANNER_CONTINUE_SIGNATURE;
//goto (no break needed);
// goto (no break needed);
case T_ABSTRACT:
$this->isAbstract = true;
goto SCANNER_CONTINUE_SIGNATURE;
//goto (no break needed);
// goto (no break needed);
case T_PUBLIC:
// use defaults
goto SCANNER_CONTINUE_SIGNATURE;
//goto (no break needed);
// goto (no break needed);
case T_PROTECTED:
$this->setVisibility(T_PROTECTED);
goto SCANNER_CONTINUE_SIGNATURE;
//goto (no break needed);
// goto (no break needed);
case T_PRIVATE:
$this->setVisibility(T_PRIVATE);
goto SCANNER_CONTINUE_SIGNATURE;
//goto (no break needed);
// goto (no break needed);
case T_STATIC:
$this->isStatic = true;
goto SCANNER_CONTINUE_SIGNATURE;
//goto (no break needed);
// goto (no break needed);
case T_NS_SEPARATOR:
if (! isset($infos[$infoIndex])) {
$MACRO_INFO_START();
}
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_VARIABLE:
case T_STRING:
if ($tokenType === T_STRING && $parentCount === 0) {
$this->name = $tokenContent;
}
if ($parentCount === 1) {
if (!isset($infos[$infoIndex])) {
if (! isset($infos[$infoIndex])) {
$MACRO_INFO_START();
}
if ($tokenType === T_VARIABLE) {
@@ -539,21 +553,20 @@ class MethodScanner implements ScannerInterface
}
goto SCANNER_CONTINUE_SIGNATURE;
//goto (no break needed);
// goto (no break needed);
case null:
switch ($tokenContent) {
case '&':
if (!isset($infos[$infoIndex])) {
if (! isset($infos[$infoIndex])) {
$MACRO_INFO_START();
}
goto SCANNER_CONTINUE_SIGNATURE;
//goto (no break needed);
// goto (no break needed);
case '(':
$parentCount++;
goto SCANNER_CONTINUE_SIGNATURE;
//goto (no break needed);
// goto (no break needed);
case ')':
$parentCount--;
if ($parentCount > 0) {
@@ -566,7 +579,7 @@ class MethodScanner implements ScannerInterface
$context = 'body';
}
goto SCANNER_CONTINUE_BODY;
//goto (no break needed);
// goto (no break needed);
case ',':
if ($parentCount === 1) {
$MACRO_INFO_ADVANCE();
@@ -601,7 +614,5 @@ class MethodScanner implements ScannerInterface
SCANNER_END:
$this->isScanned = true;
return;
}
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -11,6 +11,13 @@ namespace Zend\Code\Scanner;
use Zend\Code\NameInformation;
use function current;
use function is_string;
use function ltrim;
use function next;
use function reset;
use function trim;
class ParameterScanner
{
/**
@@ -21,42 +28,42 @@ class ParameterScanner
/**
* @var null|ClassScanner
*/
protected $declaringScannerClass = null;
protected $declaringScannerClass;
/**
* @var null|string
*/
protected $declaringClass = null;
protected $declaringClass;
/**
* @var null|MethodScanner
*/
protected $declaringScannerFunction = null;
protected $declaringScannerFunction;
/**
* @var null|string
*/
protected $declaringFunction = null;
protected $declaringFunction;
/**
* @var null|string
*/
protected $defaultValue = null;
protected $defaultValue;
/**
* @var null|string
*/
protected $class = null;
protected $class;
/**
* @var null|string
*/
protected $name = null;
protected $name;
/**
* @var null|int
*/
protected $position = null;
protected $position;
/**
* @var bool
@@ -81,12 +88,12 @@ class ParameterScanner
/**
* @var array|null
*/
protected $tokens = null;
protected $tokens;
/**
* @var null|NameInformation
*/
protected $nameInformation = null;
protected $nameInformation;
/**
* @param array $parameterTokens
@@ -195,7 +202,7 @@ class ParameterScanner
}
if ($this->name !== null) {
$this->defaultValue .= trim((is_string($token)) ? $token : $token[1]);
$this->defaultValue .= trim(is_string($token) ? $token : $token[1]);
}
SCANNER_CONTINUE:

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -13,13 +13,23 @@ use Zend\Code\Annotation;
use Zend\Code\Exception;
use Zend\Code\NameInformation;
use function is_array;
use function is_numeric;
use function is_string;
use function ltrim;
use function reset;
use function strpos;
use function substr;
use function trim;
use function var_export;
class PropertyScanner implements ScannerInterface
{
const T_BOOLEAN = "boolean";
const T_INTEGER = "int";
const T_STRING = "string";
const T_ARRAY = "array";
const T_UNKNOWN = "unknown";
const T_BOOLEAN = 'boolean';
const T_INTEGER = 'int';
const T_STRING = 'string';
const T_ARRAY = 'array';
const T_UNKNOWN = 'unknown';
/**
* @var bool
@@ -141,6 +151,7 @@ class PropertyScanner implements ScannerInterface
*/
public function getValueType()
{
$this->scan();
return $this->valueType;
}
@@ -200,7 +211,7 @@ class PropertyScanner implements ScannerInterface
/**
* @param Annotation\AnnotationManager $annotationManager
* @return AnnotationScanner
* @return AnnotationScanner|false
*/
public function getAnnotations(Annotation\AnnotationManager $annotationManager)
{
@@ -231,7 +242,7 @@ class PropertyScanner implements ScannerInterface
return;
}
if (!$this->tokens) {
if (! $this->tokens) {
throw new Exception\RuntimeException('No tokens were provided');
}
@@ -246,7 +257,7 @@ class PropertyScanner implements ScannerInterface
foreach ($tokens as $token) {
$tempValue = $token;
if (!is_string($token)) {
if (! is_string($token)) {
list($tokenType, $tokenContent, $tokenLine) = $token;
switch ($tokenType) {
@@ -284,7 +295,7 @@ class PropertyScanner implements ScannerInterface
}
//end value concatenation
if (!is_array($token) && trim($token) == ";") {
if (! is_array($token) && trim($token) == ';') {
$concatenateValue = false;
}
@@ -293,19 +304,19 @@ class PropertyScanner implements ScannerInterface
}
//start value concatenation
if (!is_array($token) && trim($token) == "=") {
if (! is_array($token) && trim($token) == '=') {
$concatenateValue = true;
}
}
$this->valueType = self::T_UNKNOWN;
if ($value == "false" || $value == "true") {
if ($value == 'false' || $value == 'true') {
$this->valueType = self::T_BOOLEAN;
} elseif (is_numeric($value)) {
$this->valueType = self::T_INTEGER;
} elseif (0 === strpos($value, 'array') || 0 === strpos($value, "[")) {
} elseif (0 === strpos($value, 'array') || 0 === strpos($value, '[')) {
$this->valueType = self::T_ARRAY;
} elseif (substr($value, 0, 1) === '"' || substr($value, 0, 1) === "'") {
} elseif (0 === strpos($value, '"') || 0 === strpos($value, "'")) {
$value = substr($value, 1, -1); // Remove quotes
$this->valueType = self::T_STRING;
}

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -13,6 +13,13 @@ use Zend\Code\Annotation\AnnotationManager;
use Zend\Code\Exception;
use Zend\Code\NameInformation;
use function array_shift;
use function array_slice;
use function in_array;
use function is_array;
use function is_int;
use function is_string;
class TokenArrayScanner implements ScannerInterface
{
/**
@@ -23,27 +30,27 @@ class TokenArrayScanner implements ScannerInterface
/**
* @var array
*/
protected $tokens = array();
protected $tokens = [];
/**
* @var null
*/
protected $docComment = null;
protected $docComment;
/**
* @var NameInformation
*/
protected $nameInformation = null;
protected $nameInformation;
/**
* @var array
*/
protected $infos = array();
protected $infos = [];
/**
* @var AnnotationManager
*/
protected $annotationManager = null;
protected $annotationManager;
/**
* @param null|array $tokens
@@ -69,7 +76,7 @@ class TokenArrayScanner implements ScannerInterface
* @todo Assignment of $this->docComment should probably be done in scan()
* and then $this->getDocComment() just retrieves it.
*
* @return string
* @return string|null
*/
public function getDocComment()
{
@@ -96,7 +103,7 @@ class TokenArrayScanner implements ScannerInterface
{
$this->scan();
$namespaces = array();
$namespaces = [];
foreach ($this->infos as $info) {
if ($info['type'] == 'namespace') {
$namespaces[] = $info['namespace'];
@@ -118,7 +125,7 @@ class TokenArrayScanner implements ScannerInterface
}
/**
* @return array
* @return void
*/
public function getIncludes()
{
@@ -133,7 +140,7 @@ class TokenArrayScanner implements ScannerInterface
{
$this->scan();
$return = array();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] != 'class') {
continue;
@@ -152,7 +159,7 @@ class TokenArrayScanner implements ScannerInterface
{
$this->scan();
$return = array();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] != 'class') {
continue;
@@ -169,7 +176,7 @@ class TokenArrayScanner implements ScannerInterface
*
* @param string|int $name
* @throws Exception\InvalidArgumentException
* @return ClassScanner
* @return ClassScanner|false
*/
public function getClass($name)
{
@@ -189,7 +196,7 @@ class TokenArrayScanner implements ScannerInterface
}
}
if (!$classFound) {
if (! $classFound) {
return false;
}
}
@@ -198,7 +205,7 @@ class TokenArrayScanner implements ScannerInterface
array_slice(
$this->tokens,
$info['tokenStart'],
($info['tokenEnd'] - $info['tokenStart'] + 1)
$info['tokenEnd'] - $info['tokenStart'] + 1
), // zero indexed array
new NameInformation($info['namespace'], $info['uses'])
);
@@ -220,11 +227,11 @@ class TokenArrayScanner implements ScannerInterface
}
}
if (!$classFound) {
if (! $classFound) {
return false;
}
if (!isset($info)) {
if (! isset($info)) {
return;
}
@@ -237,7 +244,7 @@ class TokenArrayScanner implements ScannerInterface
public function getFunctionNames()
{
$this->scan();
$functionNames = array();
$functionNames = [];
foreach ($this->infos as $info) {
if ($info['type'] == 'function') {
$functionNames[] = $info['name'];
@@ -254,12 +261,12 @@ class TokenArrayScanner implements ScannerInterface
{
$this->scan();
$functions = array();
foreach ($this->infos as $info) {
if ($info['type'] == 'function') {
// @todo $functions[] = new FunctionScanner($info['name']);
}
}
$functions = [];
// foreach ($this->infos as $info) {
// if ($info['type'] == 'function') {
// // @todo $functions[] = new FunctionScanner($info['name']);
// }
// }
return $functions;
}
@@ -267,7 +274,7 @@ class TokenArrayScanner implements ScannerInterface
/**
* Export
*
* @param $tokens
* @param mixed $tokens
*/
public static function export($tokens)
{
@@ -294,21 +301,13 @@ class TokenArrayScanner implements ScannerInterface
return;
}
if (!$this->tokens) {
if (! $this->tokens) {
throw new Exception\RuntimeException('No tokens were provided');
}
/**
* Define PHP 5.4 'trait' token constant.
*/
if (!defined('T_TRAIT')) {
define('T_TRAIT', 42001);
}
/**
* Variables & Setup
*/
$tokens = &$this->tokens; // localize
$infos = &$this->infos; // localize
$tokenIndex = null;
@@ -323,9 +322,16 @@ class TokenArrayScanner implements ScannerInterface
/*
* MACRO creation
*/
$MACRO_TOKEN_ADVANCE = function () use (&$tokens, &$tokenIndex, &$token, &$tokenType, &$tokenContent, &$tokenLine) {
$tokenIndex = ($tokenIndex === null) ? 0 : $tokenIndex + 1;
if (!isset($tokens[$tokenIndex])) {
$MACRO_TOKEN_ADVANCE = function () use (
&$tokens,
&$tokenIndex,
&$token,
&$tokenType,
&$tokenContent,
&$tokenLine
) {
$tokenIndex = $tokenIndex === null ? 0 : $tokenIndex + 1;
if (! isset($tokens[$tokenIndex])) {
$token = false;
$tokenContent = false;
$tokenType = false;
@@ -336,7 +342,7 @@ class TokenArrayScanner implements ScannerInterface
if (is_string($tokens[$tokenIndex]) && $tokens[$tokenIndex] === '"') {
do {
$tokenIndex++;
} while (!(is_string($tokens[$tokenIndex]) && $tokens[$tokenIndex] === '"'));
} while (! (is_string($tokens[$tokenIndex]) && $tokens[$tokenIndex] === '"'));
}
$token = $tokens[$tokenIndex];
if (is_array($token)) {
@@ -349,7 +355,7 @@ class TokenArrayScanner implements ScannerInterface
return $tokenIndex;
};
$MACRO_TOKEN_LOGICAL_START_INDEX = function () use (&$tokenIndex, &$docCommentIndex) {
return ($docCommentIndex === false) ? $tokenIndex : $docCommentIndex;
return $docCommentIndex === false ? $tokenIndex : $docCommentIndex;
};
$MACRO_DOC_COMMENT_START = function () use (&$tokenIndex, &$docCommentIndex) {
$docCommentIndex = $tokenIndex;
@@ -359,9 +365,9 @@ class TokenArrayScanner implements ScannerInterface
$MACRO_DOC_COMMENT_VALIDATE = function () use (&$tokenType, &$docCommentIndex) {
static $validTrailingTokens = null;
if ($validTrailingTokens === null) {
$validTrailingTokens = array(T_WHITESPACE, T_FINAL, T_ABSTRACT, T_INTERFACE, T_CLASS, T_FUNCTION);
$validTrailingTokens = [T_WHITESPACE, T_FINAL, T_ABSTRACT, T_INTERFACE, T_CLASS, T_FUNCTION];
}
if ($docCommentIndex !== false && !in_array($tokenType, $validTrailingTokens)) {
if ($docCommentIndex !== false && ! in_array($tokenType, $validTrailingTokens)) {
$docCommentIndex = false;
}
@@ -378,7 +384,6 @@ class TokenArrayScanner implements ScannerInterface
/**
* START FINITE STATE MACHINE FOR SCANNING TOKENS
*/
// Initialize token
$MACRO_TOKEN_ADVANCE();
@@ -392,23 +397,20 @@ class TokenArrayScanner implements ScannerInterface
$MACRO_DOC_COMMENT_VALIDATE();
switch ($tokenType) {
case T_DOC_COMMENT:
$MACRO_DOC_COMMENT_START();
goto SCANNER_CONTINUE;
//goto no break needed
// goto no break needed
case T_NAMESPACE:
$infos[$infoIndex] = array(
$infos[$infoIndex] = [
'type' => 'namespace',
'tokenStart' => $MACRO_TOKEN_LOGICAL_START_INDEX(),
'tokenEnd' => null,
'lineStart' => $token[2],
'lineEnd' => null,
'namespace' => null,
);
];
// start processing with next token
if ($MACRO_TOKEN_ADVANCE() === false) {
@@ -417,7 +419,7 @@ class TokenArrayScanner implements ScannerInterface
SCANNER_NAMESPACE_TOP:
if ($tokenType === null && $tokenContent === ';' || $tokenContent === '{') {
if (($tokenType === null && $tokenContent === ';') || $tokenContent === '{') {
goto SCANNER_NAMESPACE_END;
}
@@ -442,20 +444,23 @@ class TokenArrayScanner implements ScannerInterface
$MACRO_INFO_ADVANCE();
goto SCANNER_CONTINUE;
//goto no break needed
// goto no break needed
case T_USE:
$infos[$infoIndex] = array(
$infos[$infoIndex] = [
'type' => 'use',
'tokenStart' => $MACRO_TOKEN_LOGICAL_START_INDEX(),
'tokenEnd' => null,
'lineStart' => $tokens[$tokenIndex][2],
'lineEnd' => null,
'namespace' => $namespace,
'statements' => array(0 => array('use' => null,
'as' => null)),
);
'statements' => [
0 => [
'use' => null,
'as' => null,
],
],
];
$useStatementIndex = 0;
$useAsContext = false;
@@ -473,8 +478,10 @@ class TokenArrayScanner implements ScannerInterface
} elseif ($tokenContent === ',') {
$useAsContext = false;
$useStatementIndex++;
$infos[$infoIndex]['statements'][$useStatementIndex] = array('use' => null,
'as' => null);
$infos[$infoIndex]['statements'][$useStatementIndex] = [
'use' => null,
'as' => null,
];
}
}
@@ -505,22 +512,21 @@ class TokenArrayScanner implements ScannerInterface
$MACRO_INFO_ADVANCE();
goto SCANNER_CONTINUE;
//goto no break needed
// goto no break needed
case T_INCLUDE:
case T_INCLUDE_ONCE:
case T_REQUIRE:
case T_REQUIRE_ONCE:
// Static for performance
static $includeTypes = array(
static $includeTypes = [
T_INCLUDE => 'include',
T_INCLUDE_ONCE => 'include_once',
T_REQUIRE => 'require',
T_REQUIRE_ONCE => 'require_once'
);
T_REQUIRE_ONCE => 'require_once',
];
$infos[$infoIndex] = array(
$infos[$infoIndex] = [
'type' => 'include',
'tokenStart' => $MACRO_TOKEN_LOGICAL_START_INDEX(),
'tokenEnd' => null,
@@ -528,7 +534,7 @@ class TokenArrayScanner implements ScannerInterface
'lineEnd' => null,
'includeType' => $includeTypes[$tokens[$tokenIndex][0]],
'path' => '',
);
];
// start processing with next token
if ($MACRO_TOKEN_ADVANCE() === false) {
@@ -554,7 +560,7 @@ class TokenArrayScanner implements ScannerInterface
$MACRO_INFO_ADVANCE();
goto SCANNER_CONTINUE;
//goto no break needed
// goto no break needed
case T_FUNCTION:
case T_FINAL:
@@ -562,9 +568,8 @@ class TokenArrayScanner implements ScannerInterface
case T_CLASS:
case T_INTERFACE:
case T_TRAIT:
$infos[$infoIndex] = array(
'type' => ($tokenType === T_FUNCTION) ? 'function' : 'class',
$infos[$infoIndex] = [
'type' => $tokenType === T_FUNCTION ? 'function' : 'class',
'tokenStart' => $MACRO_TOKEN_LOGICAL_START_INDEX(),
'tokenEnd' => null,
'lineStart' => $tokens[$tokenIndex][2],
@@ -573,7 +578,7 @@ class TokenArrayScanner implements ScannerInterface
'uses' => $this->getUsesNoScan($namespace),
'name' => null,
'shortName' => null,
);
];
$classBraceCount = 0;
@@ -583,11 +588,18 @@ class TokenArrayScanner implements ScannerInterface
// process the name
if ($infos[$infoIndex]['shortName'] == ''
&& (($tokenType === T_CLASS || $tokenType === T_INTERFACE || $tokenType === T_TRAIT) && $infos[$infoIndex]['type'] === 'class'
&& (($tokenType === T_CLASS
|| $tokenType === T_INTERFACE
|| $tokenType === T_TRAIT)
&& $infos[$infoIndex]['type'] === 'class'
|| ($tokenType === T_FUNCTION && $infos[$infoIndex]['type'] === 'function'))
) {
$infos[$infoIndex]['shortName'] = $tokens[$tokenIndex + 2][1];
$infos[$infoIndex]['name'] = (($namespace !== null) ? $namespace . '\\' : '') . $infos[$infoIndex]['shortName'];
$infos[$infoIndex]['shortName'] = is_array($tokens[$tokenIndex + 2])
? $tokens[$tokenIndex + 2][1]
: $tokens[$tokenIndex + 2];
$infos[$infoIndex]['name'] = ($namespace !== null
? $namespace . '\\'
: '') . $infos[$infoIndex]['shortName'];
}
if ($tokenType === null) {
@@ -613,7 +625,7 @@ class TokenArrayScanner implements ScannerInterface
$MACRO_INFO_ADVANCE();
goto SCANNER_CONTINUE;
// goto no break needed
}
SCANNER_CONTINUE:
@@ -628,7 +640,6 @@ class TokenArrayScanner implements ScannerInterface
/**
* END FINITE STATE MACHINE FOR SCANNING TOKENS
*/
$this->isScanned = true;
}
@@ -657,7 +668,7 @@ class TokenArrayScanner implements ScannerInterface
*/
protected function getUsesNoScan($namespace)
{
$namespaces = array();
$namespaces = [];
foreach ($this->infos as $info) {
if ($info['type'] == 'namespace') {
$namespaces[] = $info['namespace'];
@@ -666,13 +677,13 @@ class TokenArrayScanner implements ScannerInterface
if ($namespace === null) {
$namespace = array_shift($namespaces);
} elseif (!is_string($namespace)) {
} elseif (! is_string($namespace)) {
throw new Exception\InvalidArgumentException('Invalid namespace provided');
} elseif (!in_array($namespace, $namespaces)) {
} elseif (! in_array($namespace, $namespaces)) {
return;
}
$uses = array();
$uses = [];
foreach ($this->infos as $info) {
if ($info['type'] !== 'use') {
continue;

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
@@ -12,6 +12,16 @@ namespace Zend\Code\Scanner;
use stdClass;
use Zend\Code\Exception;
use function array_key_exists;
use function is_object;
use function ltrim;
use function property_exists;
use function sprintf;
use function strlen;
use function strpos;
use function substr;
use function substr_replace;
/**
* Shared utility methods used by scanners
*/
@@ -28,9 +38,9 @@ class Util
*/
public static function resolveImports(&$value, $key = null, stdClass $data = null)
{
if (!is_object($data)
|| !property_exists($data, 'uses')
|| !property_exists($data, 'namespace')
if (! is_object($data)
|| ! property_exists($data, 'uses')
|| ! property_exists($data, 'namespace')
) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects a data object containing "uses" and "namespace" properties; on or both missing',
@@ -38,13 +48,13 @@ class Util
));
}
if ($data->namespace && !$data->uses && strlen($value) > 0 && $value{0} != '\\') {
if ($data->namespace && ! $data->uses && strlen($value) > 0 && $value[0] != '\\') {
$value = $data->namespace . '\\' . $value;
return;
}
if (!$data->uses || strlen($value) <= 0 || $value{0} == '\\') {
if (! $data->uses || strlen($value) <= 0 || $value[0] == '\\') {
$value = ltrim($value, '\\');
return;

View File

@@ -3,7 +3,7 @@
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

View File

@@ -0,0 +1,279 @@
# Changelog
All notable changes to this project will be documented in this file, in reverse chronological order by release.
## 3.2.1 - 2018-04-25
### Added
- [#66](https://github.com/zendframework/zend-eventmanager/pull/66) adds support for PHP 7.2.
### Changed
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 3.2.0 - 2017-07-11
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- [#47](https://github.com/zendframework/zend-eventmanager/pull/47) removes
support for PHP 5.5 and HHVM.
### Fixed
- Nothing.
## 3.1.0 - 2016-12-19
### Added
- [#26](https://github.com/zendframework/zend-eventmanager/pull/26) publishes
the documentation to https://zendframework.github.io/zend-eventmanager/
### Changes
- [#17](https://github.com/zendframework/zend-eventmanager/pull/17) makes a
number of internal changes to how listeners are stored in order to improve
performance, by as much as 10% in the scenario used in the MVC layer.
Additionally, it optimizes when the target and event arguments are injected
into an event, eliminating that step entirely when either is unavailable.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 3.0.1 - 2016-02-18
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#24](https://github.com/zendframework/zend-eventmanager/pull/24) updates the
zend-stdlib dependency to `^2.7.3 || ^3.0`, allowing either major version.
## 3.0.0 - 2016-01-12
### Added
- [Migration documentation](doc/book/migration/) was added.
- [Automated benchmarks](benchmarks/) were added.
- `EventManager::__construct()` now accepts an optional
`SharedEventManagerInterface` instance as the first argument, and an optional
array of identifiers as the second. As identifiers have no meaning without a
shared manager present, they are secondary to providing the shared manager.
- `EventManagerInterface::trigger()` changes its signature to
`trigger($eventName, $target = null, $argv = [])`; each argument has exactly
one possible meaning; the `$eventName` can only be a string event name. The
fourth `$callback` argument is removed.
- `EventManagerInterface::triggerUntil()` changes its signature to
`triggerUntil(callable $callback, $eventName, $target = null, $argv = null)`.
Each argument has exactly one meaning.
- `EventManagerInterface` adds two new methods for triggering provided
`EventInterface` arguments: `triggerEvent(EventInterface $event)` and
`triggerEventUntil(callable $callback, EventInterface $event)`.
- `EventManagerInterface::attach()` and `detach()` change their signatures to
`attach($eventName, callable $listener, $priority = 1)` and `detach(callable
$listener, $eventName = null)`, respectively. Note that `$eventName` can now
only be a string event name, not an array or `Traversable`.
- `EventManagerInterface::setIdentifiers()` and `addIdentifiers()` change their
signatures to each only accept an *array* of identifiers.
- `SharedEventManagerInterface::getListeners()` changes signature to
`getListeners(array $identifiers, $eventName)` and now guarantees return of an
array. Note that the second argument is now *required*.
- `SharedEventManagerInterface::attach()` changes signature to
`attach($identifier, $eventName, callable $listener, $priority = 1)`. The
`$identifier` and `$eventName` **must** be strings.
- `SharedEventManagerInterface::detach()` changes signature to `detach(callable
$listener, $identifier = null, $eventName = null)`; `$identifier` and
`$eventName` **must** be strings if passed.
- `ListenerAggregateInterface::attach()` adds an optional `$priority = 1`
argument. This was used already in v2, but not dictated by the interface.
- `FilterInterface::attach()` and `detach()` have changed signature to
`attach(callable $callback)` and `detach(callable $ilter)`, respectively.
- `LazyListener` allows wrapping:
- fetching a listener service from a container-interop container, and
- invoking a designated listener method with the provided event.
- `LazyEventListener` extends `LazyListener`, and provides metadata for
discovering the intended event name and priority at which to attach the lazy
listener; these are consumed by:
- `LazyListenerAggregate`, which, provided a list of `LazyEventListeners` and/or
definitions to use to create them, acts as an aggregate for attaching a number
of such listeners at once.
- [#20](https://github.com/zendframework/zend-eventmanager/pull/20) updates the
trait `Zend\EventManager\Test\EventListenerIntrospectionTrait` so that the
implementation will work with the v3 changes; the tests written for v2
continue to pass, allowing this trait to be used to provide compatibility
testing between v2 and v3.
### Deprecated
- Nothing.
### Removed
- `GlobalEventManager` and `StaticEventManager` are removed (with prejudice!).
- `ProvidesEvents`, which was previously deprecated, is removed.
- `EventManagerInterface::setSharedManager()` is removed. Shared managers are
now expected to be injected during instantiation.
- `EventManagerInterface::getEvents()` and `getListeners()` are removed; they
had now purpose within the implementation.
- `EventManagerInterface::setEventClass()` was renamed to `setEventPrototype()`,
which now expects an `EventInterface` instance. That instance will be cloned
whenever a new event is created.
- `EventManagerInterface::attachAggregate()` and `detachAggregate()` are
removed. Users should use the `attach()` and `detach()` methods of the
aggregates themselves.
- `SharedEventAggregateAwareInterface` and `SharedListenerAggregateInterface`
are removed. This was an undocumented and largely unused feature.
- `SharedEventManagerAwareInterface` is removed. A new interface,
`SharedEventsCapableInterface` defines the `getSharedManager()` method from
the interface, and `EventManagerInterface` extends that new interface.
- `SharedEventManagerInterface::getEvents()` is removed, as it had no purpose in
the implementation.
- `ResponseCollection::setStopped()` no longer implements a fluent interface.
### Fixed
- `FilterIterator::insert()` has been modified to raise an exception if the value provided is not a callable.
## 2.6.2 - 2016-01-12
### Added
- [#19](https://github.com/zendframework/zend-eventmanager/pull/19) adds a new
trait, `Zend\EventManager\Test\EventListenerIntrospectionTrait`, intended for
composition in unit tests. It provides a number of methods that can be used
to retrieve listeners with or without associated priority, and the assertion
`assertListenerAtPriority(callable $listener, $priority, $event, EventManager $events, $message = '')`,
which can be used for testing that a listener was registered at the specified
priority with the specified event.
The features in this patch are intended to facilitate testing against both
version 2 and version 3 of zend-eventmanager, as it provides a consistent API
for retrieving lists of events and listeners between the two versions.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 2.6.0 - 2015-09-29
### Added
- Added `Zend\EventManager\SharedEventsCapableInterface`. This interface will
largely replace `Zend\EventManager\SharedEventManagerAwareInterface` in
version 3, and the latter was updated to extend it.
- Added `EventManager::triggerEvent(EventInterface $event)` as a
forwards-compatibility feature.
- Add `EventManager::triggerEventUntil(callable $callback, EventIterface $event)`
as a forwards-compatibility feature.
- Adds [Athletic](https://github.com/polyfractal/athletic) benchmarks to aid in
gauging performanc impact of changes; these are a development change only.
### Deprecated
- Marked `GlobalEventManager` as deprecated; this class will be removed in
version 3.
- Marked `StaticEventManager` as deprecated; this class will be removed in
version 3.
- Marked `SharedListenerAggregateInterface` as deprecated; this interface will
be removed in version 3.
- Marked `SharedEventAggregateAwareInterface` as deprecated; this interface will
be removed in version 3.
- Marked `SharedEventManagerAwareInterface` as deprecated; this interface will
be removed in version 3.
- Marked `EventManager::setSharedManager()` as deprecated; this method will be
removed in version 3.
- Marked `EventManager::unsetSharedManager()` as deprecated; this method will be
removed in version 3.
- Marked `EventManagerInterface::` and `EventManager::getEvents()` as
deprecated; this method will be removed in version 3.
- Marked `EventManagerInterface::` and `EventManager::getListeners()` as
deprecated; this method will be removed in version 3.
- Marked `EventManagerInterface::` and `Eventmanager::setEventClass()` as
deprecated; this method is renamed to `setEventPrototype(EventInterface $event)`
in version 3.
- Marked `EventManagerInterface::` and `EventManager::attachAggregate()` as
deprecated; this method will be removed in version 3.
- Marked `EventManagerInterface::` and `EventManager::detachAggregate()` as
deprecated; this method will be removed in version 3.
- Marked `SharedEventManagerInterface::` and `SharedEventManager::getEvents()`
as deprecated; this method will be removed in version 3.
### Removed
- Nothing.
### Fixed
- Nothing.
## 2.5.2 - 2015-07-16
### Added
- [#5](https://github.com/zendframework/zend-eventmanager/pull/5) adds a number
of unit tests to improve test coverage, and thus maintainability and
stability.
### Deprecated
- Nothing.
### Removed
- [#3](https://github.com/zendframework/zend-eventmanager/pull/3) removes some
PHP 5.3- and 5.4-isms (such as marking Traits as requiring 5.4, and closing
over a copy of `$this`) from the test suite.
### Fixed
- [#5](https://github.com/zendframework/zend-eventmanager/pull/5) fixes a bug in
`FilterIterator` that occurs when attempting to extract from an empty heap.

View File

@@ -0,0 +1,43 @@
# Contributor Code of Conduct
The Zend Framework project adheres to [The Code Manifesto](http://codemanifesto.com)
as its guidelines for contributor interactions.
## The Code Manifesto
We want to work in an ecosystem that empowers developers to reach their
potential — one that encourages growth and effective collaboration. A space that
is safe for all.
A space such as this benefits everyone that participates in it. It encourages
new developers to enter our field. It is through discussion and collaboration
that we grow, and through growth that we improve.
In the effort to create such a place, we hold to these values:
1. **Discrimination limits us.** This includes discrimination on the basis of
race, gender, sexual orientation, gender identity, age, nationality, technology
and any other arbitrary exclusion of a group of people.
2. **Boundaries honor us.** Your comfort levels are not everyones comfort
levels. Remember that, and if brought to your attention, heed it.
3. **We are our biggest assets.** None of us were born masters of our trade.
Each of us has been helped along the way. Return that favor, when and where
you can.
4. **We are resources for the future.** As an extension of #3, share what you
know. Make yourself a resource to help those that come after you.
5. **Respect defines us.** Treat others as you wish to be treated. Make your
discussions, criticisms and debates from a position of respectfulness. Ask
yourself, is it true? Is it necessary? Is it constructive? Anything less is
unacceptable.
6. **Reactions require grace.** Angry responses are valid, but abusive language
and vindictive actions are toxic. When something happens that offends you,
handle it assertively, but be respectful. Escalate reasonably, and try to
allow the offender an opportunity to explain themselves, and possibly correct
the issue.
7. **Opinions are just that: opinions.** Each and every one of us, due to our
background and upbringing, have varying opinions. The fact of the matter, is
that is perfectly acceptable. Remember this: if you respect your own
opinions, you should respect the opinions of others.
8. **To err is human.** You might not intend it, but mistakes do happen and
contribute to build experience. Tolerate honest mistakes, and don't hesitate
to apologize if you make one yourself.

View File

@@ -1,36 +1,58 @@
{
"name": "zendframework/zend-eventmanager",
"description": " ",
"description": "Trigger and listen to events within a PHP application",
"license": "BSD-3-Clause",
"keywords": [
"zf2",
"event",
"events",
"eventmanager"
],
"homepage": "https://github.com/zendframework/zend-eventmanager",
"minimum-stability": "dev",
"prefer-stable": true,
"extra": {
"branch-alias": {
"dev-master": "3.2-dev",
"dev-develop": "3.3-dev"
}
},
"autoload": {
"psr-4": {
"Zend\\EventManager\\": "src/"
}
},
"require": {
"php": ">=5.3.23",
"zendframework/zend-stdlib": "~2.5"
},
"minimum-stability": "dev",
"prefer-stable": true,
"extra": {
"branch-alias": {
"dev-master": "2.5-dev",
"dev-develop": "2.6-dev"
}
},
"autoload-dev": {
"psr-4": {
"ZendTest\\EventManager\\": "test/"
}
"ZendTest\\EventManager\\": "test/",
"ZendBench\\EventManager\\": "benchmarks/"
},
"files": [
"test/_autoload.php"
]
},
"require": {
"php": "^5.6 || ^7.0"
},
"require-dev": {
"fabpot/php-cs-fixer": "1.7.*",
"phpunit/PHPUnit": "~4.0"
"phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2",
"athletic/athletic": "^0.1",
"zendframework/zend-stdlib": "^2.7.3 || ^3.0",
"container-interop/container-interop": "^1.1.0",
"zendframework/zend-coding-standard": "~1.0.0"
},
"suggest": {
"container-interop/container-interop": "^1.1.0, to use the lazy listeners feature",
"zendframework/zend-stdlib": "^2.7.3 || ^3.0, to use the FilterChain feature"
},
"scripts": {
"check": [
"@cs-check",
"@test"
],
"cs-check": "phpcs",
"cs-fix": "phpcbf",
"test": "phpunit --colors=always",
"test-coverage": "phpunit --colors=always --coverage-clover clover.xml"
}
}

1937
vendor/zendframework/zend-eventmanager/composer.lock generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -2,9 +2,9 @@
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @link http://github.com/zendframework/zend-eventmanager for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @license https://github.com/zendframework/zend-eventmanager/blob/master/LICENSE.md
*/
namespace Zend\EventManager;
@@ -15,9 +15,9 @@ namespace Zend\EventManager;
abstract class AbstractListenerAggregate implements ListenerAggregateInterface
{
/**
* @var \Zend\Stdlib\CallbackHandler[]
* @var callable[]
*/
protected $listeners = array();
protected $listeners = [];
/**
* {@inheritDoc}
@@ -25,9 +25,8 @@ abstract class AbstractListenerAggregate implements ListenerAggregateInterface
public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $index => $callback) {
if ($events->detach($callback)) {
unset($this->listeners[$index]);
}
$events->detach($callback);
unset($this->listeners[$index]);
}
}
}

View File

@@ -2,9 +2,9 @@
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @link http://github.com/zendframework/zend-eventmanager for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @license https://github.com/zendframework/zend-eventmanager/blob/master/LICENSE.md
*/
namespace Zend\EventManager;
@@ -32,7 +32,7 @@ class Event implements EventInterface
/**
* @var array|ArrayAccess|object The event parameters
*/
protected $params = array();
protected $params = [];
/**
* @var bool Whether or not to stop propagation
@@ -91,19 +91,17 @@ class Event implements EventInterface
* Overwrites parameters
*
* @param array|ArrayAccess|object $params
* @return Event
* @throws Exception\InvalidArgumentException
*/
public function setParams($params)
{
if (!is_array($params) && !is_object($params)) {
if (! is_array($params) && ! is_object($params)) {
throw new Exception\InvalidArgumentException(
sprintf('Event parameters must be an array or object; received "%s"', gettype($params))
);
}
$this->params = $params;
return $this;
}
/**
@@ -129,7 +127,7 @@ class Event implements EventInterface
{
// Check in params that are arrays or implement array access
if (is_array($this->params) || $this->params instanceof ArrayAccess) {
if (!isset($this->params[$name])) {
if (! isset($this->params[$name])) {
return $default;
}
@@ -137,7 +135,7 @@ class Event implements EventInterface
}
// Check in normal objects
if (!isset($this->params->{$name})) {
if (! isset($this->params->{$name})) {
return $default;
}
return $this->params->{$name};
@@ -147,24 +145,20 @@ class Event implements EventInterface
* Set the event name
*
* @param string $name
* @return Event
*/
public function setName($name)
{
$this->name = (string) $name;
return $this;
}
/**
* Set the event target/context
*
* @param null|string|object $target
* @return Event
*/
public function setTarget($target)
{
$this->target = $target;
return $this;
}
/**
@@ -172,25 +166,23 @@ class Event implements EventInterface
*
* @param string|int $name
* @param mixed $value
* @return Event
*/
public function setParam($name, $value)
{
if (is_array($this->params) || $this->params instanceof ArrayAccess) {
// Arrays or objects implementing array access
$this->params[$name] = $value;
} else {
// Objects
$this->params->{$name} = $value;
return;
}
return $this;
// Objects
$this->params->{$name} = $value;
}
/**
* Stop further event propagation
*
* @param bool $flag
* @return void
*/
public function stopPropagation($flag = true)
{

View File

@@ -2,9 +2,9 @@
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @link http://github.com/zendframework/zend-eventmanager for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @license https://github.com/zendframework/zend-eventmanager/blob/master/LICENSE.md
*/
namespace Zend\EventManager;
@@ -65,7 +65,7 @@ interface EventInterface
/**
* Set event parameters
*
* @param string $params
* @param array|ArrayAccess $params
* @return void
*/
public function setParams($params);

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