Subiendo proyecto completo sin restricciones de git ignore

This commit is contained in:
Jose Sanchez
2023-08-17 11:44:02 -04:00
parent a0d4f5ba3b
commit 20f1c60600
19921 changed files with 2509159 additions and 45 deletions

View File

@@ -0,0 +1,7 @@
version: 2
updates:
- package-ecosystem: composer
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10

View File

@@ -0,0 +1,223 @@
on:
push:
branches:
- 2.x
pull_request:
name: Qa workflow
jobs:
setup:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Restore/cache vendor folder
uses: actions/cache@v1
with:
path: vendor
key: all-build-${{ hashFiles('**/composer.lock') }}
restore-keys: |
all-build-${{ hashFiles('**/composer.lock') }}
all-build-
- name: Restore/cache tools folder
uses: actions/cache@v1
with:
path: tools
key: all-tools-${{ github.sha }}
restore-keys: |
all-tools-${{ github.sha }}-
all-tools-
- name: composer
uses: docker://composer
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
args: install --no-interaction --prefer-dist --optimize-autoloader
- name: Install phive
run: make install-phive
- name: Install PHAR dependencies
run: tools/phive.phar --no-progress install --copy --trust-gpg-keys 4AA394086372C20A,8A03EA3B385DBAA1 --force-accept-unsigned
phpunit-with-coverage:
runs-on: ubuntu-latest
name: Unit tests
needs: setup
steps:
- uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 7.2
ini-values: memory_limit=2G, display_errors=On, error_reporting=-1
coverage: pcov
- name: Restore/cache tools folder
uses: actions/cache@v1
with:
path: tools
key: all-tools-${{ github.sha }}
restore-keys: |
all-tools-${{ github.sha }}-
all-tools-
- name: Get composer cache directory
id: composer-cache
run: echo "::set-output name=dir::$(composer config cache-files-dir)"
- name: Cache composer dependencies
uses: actions/cache@v1
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ubuntu-latest-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ubuntu-latest-composer-
- name: Install Composer dependencies
run: |
composer install --no-progress --no-suggest --prefer-dist --optimize-autoloader
- name: Run PHPUnit
run: php tools/phpunit
phpunit:
runs-on: ${{ matrix.operating-system }}
strategy:
matrix:
operating-system:
- ubuntu-latest
- windows-latest
- macOS-latest
php-versions: ['7.2', '7.3', '7.4', '8.0']
name: Unit tests for PHP version ${{ matrix.php-versions }} on ${{ matrix.operating-system }}
needs:
- setup
- phpunit-with-coverage
steps:
- uses: actions/checkout@v2
- name: Restore/cache tools folder
uses: actions/cache@v1
with:
path: tools
key: all-tools-${{ github.sha }}
restore-keys: |
all-tools-${{ github.sha }}-
all-tools-
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
ini-values: memory_limit=2G, display_errors=On, error_reporting=-1
coverage: none
- name: Get composer cache directory
id: composer-cache
run: echo "::set-output name=dir::$(composer config cache-files-dir)"
- name: Cache composer dependencies
uses: actions/cache@v1
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-
- name: Install Composer dependencies
run: |
composer install --no-progress --no-suggest --prefer-dist --optimize-autoloader
- name: Run PHPUnit
continue-on-error: true
run: php tools/phpunit
codestyle:
runs-on: ubuntu-latest
needs: [setup, phpunit]
steps:
- uses: actions/checkout@v2
- name: Restore/cache vendor folder
uses: actions/cache@v1
with:
path: vendor
key: all-build-${{ hashFiles('**/composer.lock') }}
restore-keys: |
all-build-${{ hashFiles('**/composer.lock') }}
all-build-
- name: Code style check
uses: phpDocumentor/coding-standard@latest
with:
args: -s
phpstan:
runs-on: ubuntu-latest
needs: [setup, phpunit]
steps:
- uses: actions/checkout@v2
- name: Restore/cache vendor folder
uses: actions/cache@v1
with:
path: vendor
key: all-build-${{ hashFiles('**/composer.lock') }}
restore-keys: |
all-build-${{ hashFiles('**/composer.lock') }}
all-build-
- name: PHPStan
uses: phpDocumentor/phpstan-ga@latest
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
args: analyse src --configuration phpstan.neon
psalm:
runs-on: ubuntu-latest
needs: [setup, phpunit]
steps:
- uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 7.2
ini-values: memory_limit=2G, display_errors=On, error_reporting=-1
tools: psalm
coverage: none
- name: Get composer cache directory
id: composer-cache
run: echo "::set-output name=dir::$(composer config cache-files-dir)"
- name: Cache composer dependencies
uses: actions/cache@v1
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-
- name: Install Composer dependencies
run: |
composer install --no-progress --no-suggest --prefer-dist --optimize-autoloader
- name: Psalm
run: psalm --output-format=github
bc_check:
name: BC Check
runs-on: ubuntu-latest
needs: [setup, phpunit]
steps:
- uses: actions/checkout@v2
- name: fetch tags
run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
- name: Restore/cache vendor folder
uses: actions/cache@v1
with:
path: vendor
key: all-build-${{ hashFiles('**/composer.lock') }}
restore-keys: |
all-build-${{ hashFiles('**/composer.lock') }}
all-build-
- name: Roave BC Check
uses: docker://nyholm/roave-bc-check-ga

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 phpDocumentor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,11 @@
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
![Qa workflow](https://github.com/phpDocumentor/ReflectionCommon/workflows/Qa%20workflow/badge.svg)
[![Coveralls Coverage](https://img.shields.io/coveralls/github/phpDocumentor/ReflectionCommon.svg)](https://coveralls.io/github/phpDocumentor/ReflectionCommon?branch=master)
[![Scrutinizer Code Coverage](https://img.shields.io/scrutinizer/coverage/g/phpDocumentor/ReflectionCommon.svg)](https://scrutinizer-ci.com/g/phpDocumentor/ReflectionCommon/?branch=master)
[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/phpDocumentor/ReflectionCommon.svg)](https://scrutinizer-ci.com/g/phpDocumentor/ReflectionCommon/?branch=master)
[![Stable Version](https://img.shields.io/packagist/v/phpDocumentor/Reflection-Common.svg)](https://packagist.org/packages/phpDocumentor/Reflection-Common)
[![Unstable Version](https://img.shields.io/packagist/vpre/phpDocumentor/Reflection-Common.svg)](https://packagist.org/packages/phpDocumentor/Reflection-Common)
ReflectionCommon
================

View File

@@ -0,0 +1,28 @@
{
"name": "phpdocumentor/reflection-common",
"keywords": ["phpdoc", "phpDocumentor", "reflection", "static analysis", "FQSEN"],
"homepage": "http://www.phpdoc.org",
"description": "Common reflection classes used by phpdocumentor to reflect the code structure",
"license": "MIT",
"authors": [
{
"name": "Jaap van Otterdijk",
"email": "opensource@ijaap.nl"
}
],
"require": {
"php": "^7.2 || ^8.0"
},
"autoload" : {
"psr-4" : {
"phpDocumentor\\Reflection\\": "src/"
}
},
"require-dev": {
},
"extra": {
"branch-alias": {
"dev-2.x": "2.x-dev"
}
}
}

View File

@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
/**
* phpDocumentor
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection;
/**
* Interface for Api Elements
*/
interface Element
{
/**
* Returns the Fqsen of the element.
*/
public function getFqsen() : Fqsen;
/**
* Returns the name of the element.
*/
public function getName() : string;
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection;
/**
* Interface for files processed by the ProjectFactory
*/
interface File
{
/**
* Returns the content of the file as a string.
*/
public function getContents() : string;
/**
* Returns md5 hash of the file.
*/
public function md5() : string;
/**
* Returns an relative path to the file.
*/
public function path() : string;
}

View File

@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
/**
* phpDocumentor
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection;
use InvalidArgumentException;
use function assert;
use function end;
use function explode;
use function is_string;
use function preg_match;
use function sprintf;
use function trim;
/**
* Value Object for Fqsen.
*
* @link https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc-meta.md
*
* @psalm-immutable
*/
final class Fqsen
{
/** @var string full quallified class name */
private $fqsen;
/** @var string name of the element without path. */
private $name;
/**
* Initializes the object.
*
* @throws InvalidArgumentException when $fqsen is not matching the format.
*/
public function __construct(string $fqsen)
{
$matches = [];
$result = preg_match(
//phpcs:ignore Generic.Files.LineLength.TooLong
'/^\\\\([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff\\\\]*)?(?:[:]{2}\\$?([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*))?(?:\\(\\))?$/',
$fqsen,
$matches
);
if ($result === 0) {
throw new InvalidArgumentException(
sprintf('"%s" is not a valid Fqsen.', $fqsen)
);
}
$this->fqsen = $fqsen;
if (isset($matches[2])) {
$this->name = $matches[2];
} else {
$matches = explode('\\', $fqsen);
$name = end($matches);
assert(is_string($name));
$this->name = trim($name, '()');
}
}
/**
* converts this class to string.
*/
public function __toString() : string
{
return $this->fqsen;
}
/**
* Returns the name of the element without path.
*/
public function getName() : string
{
return $this->name;
}
}

View File

@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection;
/**
* The location where an element occurs within a file.
*
* @psalm-immutable
*/
final class Location
{
/** @var int */
private $lineNumber = 0;
/** @var int */
private $columnNumber = 0;
/**
* Initializes the location for an element using its line number in the file and optionally the column number.
*/
public function __construct(int $lineNumber, int $columnNumber = 0)
{
$this->lineNumber = $lineNumber;
$this->columnNumber = $columnNumber;
}
/**
* Returns the line number that is covered by this location.
*/
public function getLineNumber() : int
{
return $this->lineNumber;
}
/**
* Returns the column number (character position on a line) for this location object.
*/
public function getColumnNumber() : int
{
return $this->columnNumber;
}
}

View File

@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
/**
* phpDocumentor
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection;
/**
* Interface for project. Since the definition of a project can be different per factory this interface will be small.
*/
interface Project
{
/**
* Returns the name of the project.
*/
public function getName() : string;
}

View File

@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
/**
* phpDocumentor
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection;
/**
* Interface for project factories. A project factory shall convert a set of files
* into an object implementing the Project interface.
*/
interface ProjectFactory
{
/**
* Creates a project from the set of files.
*
* @param File[] $files
*/
public function create(string $name, array $files) : Project;
}

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2010 Mike van Riel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,177 @@
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
![](https://github.com/phpdocumentor/typeresolver/workflows/Qa%20workflow/badge.svg?branch=1.x)
[![Coveralls Coverage](https://img.shields.io/coveralls/github/phpDocumentor/TypeResolver.svg)](https://coveralls.io/github/phpDocumentor/TypeResolver?branch=1.x)
[![Scrutinizer Code Coverage](https://img.shields.io/scrutinizer/coverage/g/phpDocumentor/TypeResolver.svg)](https://scrutinizer-ci.com/g/phpDocumentor/TypeResolver/?branch=1.x)
[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/phpDocumentor/TypeResolver.svg)](https://scrutinizer-ci.com/g/phpDocumentor/TypeResolver/?branch=1.x)
![Packagist Version](https://img.shields.io/packagist/v/phpdocumentor/type-resolver?label=Packagist%20stable)
![Packagist Version](https://img.shields.io/packagist/vpre/phpdocumentor/type-resolver?label=Packagist%20unstable)
TypeResolver and FqsenResolver
==============================
The specification on types in DocBlocks (PSR-5) describes various keywords and special constructs
but also how to statically resolve the partial name of a Class into a Fully Qualified Class Name (FQCN).
PSR-5 also introduces an additional way to describe deeper elements than Classes, Interfaces and Traits
called the Fully Qualified Structural Element Name (FQSEN). Using this it is possible to refer to methods,
properties and class constants but also functions and global constants.
This package provides two Resolvers that are capable of
1. Returning a series of Value Object for given expression while resolving any partial class names, and
2. Returning an FQSEN object after resolving any partial Structural Element Names into Fully Qualified Structural
Element names.
## Installing
The easiest way to install this library is with [Composer](https://getcomposer.org) using the following command:
$ composer require phpdocumentor/type-resolver
## Examples
Ready to dive in and don't want to read through all that text below? Just consult the [examples](examples) folder and check which type of action that your want to accomplish.
## On Types and Element Names
This component can be used in one of two ways
1. To resolve a Type or
2. To resolve a Fully Qualified Structural Element Name
The big difference between these two is in the number of things it can resolve.
The TypeResolver can resolve:
- a php primitive or pseudo-primitive such as a string or void (`@var string` or `@return void`).
- a composite such as an array of string (`@var string[]`).
- a compound such as a string or integer (`@var string|integer`).
- an array expression (`@var (string|TypeResolver)[]`)
- an object or interface such as the TypeResolver class (`@var TypeResolver`
or `@var \phpDocumentor\Reflection\TypeResolver`)
> please note that if you want to pass partial class names that additional steps are necessary, see the
> chapter `Resolving partial classes and FQSENs` for more information.
Where the FqsenResolver can resolve:
- Constant expressions (i.e. `@see \MyNamespace\MY_CONSTANT`)
- Function expressions (i.e. `@see \MyNamespace\myFunction()`)
- Class expressions (i.e. `@see \MyNamespace\MyClass`)
- Interface expressions (i.e. `@see \MyNamespace\MyInterface`)
- Trait expressions (i.e. `@see \MyNamespace\MyTrait`)
- Class constant expressions (i.e. `@see \MyNamespace\MyClass::MY_CONSTANT`)
- Property expressions (i.e. `@see \MyNamespace\MyClass::$myProperty`)
- Method expressions (i.e. `@see \MyNamespace\MyClass::myMethod()`)
## Resolving a type
In order to resolve a type you will have to instantiate the class `\phpDocumentor\Reflection\TypeResolver` and call its `resolve` method like this:
```php
$typeResolver = new \phpDocumentor\Reflection\TypeResolver();
$type = $typeResolver->resolve('string|integer');
```
In this example you will receive a Value Object of class `\phpDocumentor\Reflection\Types\Compound` that has two
elements, one of type `\phpDocumentor\Reflection\Types\String_` and one of type
`\phpDocumentor\Reflection\Types\Integer`.
The real power of this resolver is in its capability to expand partial class names into fully qualified class names; but in order to do that we need an additional `\phpDocumentor\Reflection\Types\Context` class that will inform the resolver in which namespace the given expression occurs and which namespace aliases (or imports) apply.
### Resolving nullable types
Php 7.1 introduced nullable types e.g. `?string`. Type resolver will resolve the original type without the nullable notation `?`
just like it would do without the `?`. After that the type is wrapped in a `\phpDocumentor\Reflection\Types\Nullable` object.
The `Nullable` type has a method to fetch the actual type.
## Resolving an FQSEN
A Fully Qualified Structural Element Name is a reference to another element in your code bases and can be resolved using the `\phpDocumentor\Reflection\FqsenResolver` class' `resolve` method, like this:
```php
$fqsenResolver = new \phpDocumentor\Reflection\FqsenResolver();
$fqsen = $fqsenResolver->resolve('\phpDocumentor\Reflection\FqsenResolver::resolve()');
```
In this example we resolve a Fully Qualified Structural Element Name (meaning that it includes the full namespace, class name and element name) and receive a Value Object of type `\phpDocumentor\Reflection\Fqsen`.
The real power of this resolver is in its capability to expand partial element names into Fully Qualified Structural Element Names; but in order to do that we need an additional `\phpDocumentor\Reflection\Types\Context` class that will inform the resolver in which namespace the given expression occurs and which namespace aliases (or imports) apply.
## Resolving partial Classes and Structural Element Names
Perhaps the best feature of this library is that it knows how to resolve partial class names into fully qualified class names.
For example, you have this file:
```php
namespace My\Example;
use phpDocumentor\Reflection\Types;
class Classy
{
/**
* @var Types\Context
* @see Classy::otherFunction()
*/
public function __construct($context) {}
public function otherFunction(){}
}
```
Suppose that you would want to resolve (and expand) the type in the `@var` tag and the element name in the `@see` tag.
For the resolvers to know how to expand partial names you have to provide a bit of _Context_ for them by instantiating a new class named `\phpDocumentor\Reflection\Types\Context` with the name of the namespace and the aliases that are in play.
### Creating a Context
You can do this by manually creating a Context like this:
```php
$context = new \phpDocumentor\Reflection\Types\Context(
'\My\Example',
[ 'Types' => '\phpDocumentor\Reflection\Types']
);
```
Or by using the `\phpDocumentor\Reflection\Types\ContextFactory` to instantiate a new context based on a Reflector object or by providing the namespace that you'd like to extract and the source code of the file in which the given type expression occurs.
```php
$contextFactory = new \phpDocumentor\Reflection\Types\ContextFactory();
$context = $contextFactory->createFromReflector(new ReflectionMethod('\My\Example\Classy', '__construct'));
```
or
```php
$contextFactory = new \phpDocumentor\Reflection\Types\ContextFactory();
$context = $contextFactory->createForNamespace('\My\Example', file_get_contents('My/Example/Classy.php'));
```
### Using the Context
After you have obtained a Context it is just a matter of passing it along with the `resolve` method of either Resolver class as second argument and the Resolvers will take this into account when resolving partial names.
To obtain the resolved class name for the `@var` tag in the example above you can do:
```php
$typeResolver = new \phpDocumentor\Reflection\TypeResolver();
$type = $typeResolver->resolve('Types\Context', $context);
```
When you do this you will receive an object of class `\phpDocumentor\Reflection\Types\Object_` for which you can call the `getFqsen` method to receive a Value Object that represents the complete FQSEN. So that would be `phpDocumentor\Reflection\Types\Context`.
> Why is the FQSEN wrapped in another object `Object_`?
>
> The resolve method of the TypeResolver only returns object with the interface `Type` and the FQSEN is a common type that does not represent a Type. Also: in some cases a type can represent an "Untyped Object", meaning that it is an object (signified by the `object` keyword) but does not refer to a specific element using an FQSEN.
Another example is on how to resolve the FQSEN of a method as can be seen with the `@see` tag in the example above. To resolve that you can do the following:
```php
$fqsenResolver = new \phpDocumentor\Reflection\FqsenResolver();
$type = $fqsenResolver->resolve('Classy::otherFunction()', $context);
```
Because Classy is a Class in the current namespace its FQSEN will have the `My\Example` namespace and by calling the `resolve` method of the FQSEN Resolver you will receive an `Fqsen` object that refers to `\My\Example\Classy::otherFunction()`.

View File

@@ -0,0 +1,51 @@
{
"name": "phpdocumentor/type-resolver",
"description": "A PSR-5 based resolver of Class names, Types and Structural Element Names",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Mike van Riel",
"email": "me@mikevanriel.com"
}
],
"require": {
"php": "^7.4 || ^8.0",
"phpdocumentor/reflection-common": "^2.0",
"phpstan/phpdoc-parser": "^1.13",
"doctrine/deprecations": "^1.0"
},
"require-dev": {
"ext-tokenizer": "*",
"phpunit/phpunit": "^9.5",
"phpstan/phpstan": "^1.8",
"phpstan/phpstan-phpunit": "^1.1",
"phpstan/extension-installer": "^1.1",
"vimeo/psalm": "^4.25",
"rector/rector": "^0.13.9",
"phpbench/phpbench": "^1.2"
},
"autoload": {
"psr-4": {
"phpDocumentor\\Reflection\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"phpDocumentor\\Reflection\\": ["tests/unit", "tests/benchmark"]
}
},
"extra": {
"branch-alias": {
"dev-1.x": "1.x-dev"
}
},
"config": {
"platform": {
"php": "7.4.0"
},
"allow-plugins": {
"phpstan/extension-installer": true
}
}
}

View File

@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection;
use InvalidArgumentException;
use phpDocumentor\Reflection\Types\Context;
use function explode;
use function implode;
use function strpos;
/**
* Resolver for Fqsen using Context information
*
* @psalm-immutable
*/
class FqsenResolver
{
/** @var string Definition of the NAMESPACE operator in PHP */
private const OPERATOR_NAMESPACE = '\\';
public function resolve(string $fqsen, ?Context $context = null): Fqsen
{
if ($context === null) {
$context = new Context('');
}
if ($this->isFqsen($fqsen)) {
return new Fqsen($fqsen);
}
return $this->resolvePartialStructuralElementName($fqsen, $context);
}
/**
* Tests whether the given type is a Fully Qualified Structural Element Name.
*/
private function isFqsen(string $type): bool
{
return strpos($type, self::OPERATOR_NAMESPACE) === 0;
}
/**
* Resolves a partial Structural Element Name (i.e. `Reflection\DocBlock`) to its FQSEN representation
* (i.e. `\phpDocumentor\Reflection\DocBlock`) based on the Namespace and aliases mentioned in the Context.
*
* @throws InvalidArgumentException When type is not a valid FQSEN.
*/
private function resolvePartialStructuralElementName(string $type, Context $context): Fqsen
{
$typeParts = explode(self::OPERATOR_NAMESPACE, $type, 2);
$namespaceAliases = $context->getNamespaceAliases();
// if the first segment is not an alias; prepend namespace name and return
if (!isset($namespaceAliases[$typeParts[0]])) {
$namespace = $context->getNamespace();
if ($namespace !== '') {
$namespace .= self::OPERATOR_NAMESPACE;
}
return new Fqsen(self::OPERATOR_NAMESPACE . $namespace . $type);
}
$typeParts[0] = $namespaceAliases[$typeParts[0]];
return new Fqsen(self::OPERATOR_NAMESPACE . implode(self::OPERATOR_NAMESPACE, $typeParts));
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection;
interface PseudoType extends Type
{
public function underlyingType(): Type;
}

View File

@@ -0,0 +1,44 @@
<?php
/*
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*
*/
declare(strict_types=1);
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Array_;
use phpDocumentor\Reflection\Types\ArrayKey;
use phpDocumentor\Reflection\Types\Mixed_;
use function implode;
/** @psalm-immutable */
class ArrayShape implements PseudoType
{
/** @var ArrayShapeItem[] */
private array $items;
public function __construct(ArrayShapeItem ...$items)
{
$this->items = $items;
}
public function underlyingType(): Type
{
return new Array_(new Mixed_(), new ArrayKey());
}
public function __toString(): string
{
return 'array{' . implode(', ', $this->items) . '}';
}
}

View File

@@ -0,0 +1,62 @@
<?php
/*
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*
*/
declare(strict_types=1);
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Mixed_;
use function sprintf;
final class ArrayShapeItem
{
private ?string $key;
private Type $value;
private bool $optional;
public function __construct(?string $key, ?Type $value, bool $optional)
{
$this->key = $key;
$this->value = $value ?? new Mixed_();
$this->optional = $optional;
}
public function getKey(): ?string
{
return $this->key;
}
public function getValue(): Type
{
return $this->value;
}
public function isOptional(): bool
{
return $this->optional;
}
public function __toString(): string
{
if ($this->key !== null) {
return sprintf(
'%s%s: %s',
$this->key,
$this->optional ? '?' : '',
(string) $this->value
);
}
return (string) $this->value;
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\String_;
/**
* Value Object representing the type 'string'.
*
* @psalm-immutable
*/
final class CallableString extends String_ implements PseudoType
{
public function underlyingType(): Type
{
return new String_();
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'callable-string';
}
}

View File

@@ -0,0 +1,53 @@
<?php
/*
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*
*/
declare(strict_types=1);
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Mixed_;
use function sprintf;
/** @psalm-immutable */
final class ConstExpression implements PseudoType
{
private Type $owner;
private string $expression;
public function __construct(Type $owner, string $expression)
{
$this->owner = $owner;
$this->expression = $expression;
}
public function getOwner(): Type
{
return $this->owner;
}
public function getExpression(): string
{
return $this->expression;
}
public function underlyingType(): Type
{
return new Mixed_();
}
public function __toString(): string
{
return sprintf('%s::%s', (string) $this->owner, $this->expression);
}
}

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link https://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Boolean;
use function class_alias;
/**
* Value Object representing the PseudoType 'False', which is a Boolean type.
*
* @psalm-immutable
*/
final class False_ extends Boolean implements PseudoType
{
public function underlyingType(): Type
{
return new Boolean();
}
public function __toString(): string
{
return 'false';
}
}
class_alias(False_::class, 'phpDocumentor\Reflection\Types\False_', false);

View File

@@ -0,0 +1,44 @@
<?php
/*
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*
*/
declare(strict_types=1);
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Float_;
/** @psalm-immutable */
class FloatValue implements PseudoType
{
private float $value;
public function __construct(float $value)
{
$this->value = $value;
}
public function getValue(): float
{
return $this->value;
}
public function underlyingType(): Type
{
return new Float_();
}
public function __toString(): string
{
return (string) $this->value;
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\String_;
/**
* Value Object representing the type 'string'.
*
* @psalm-immutable
*/
final class HtmlEscapedString extends String_ implements PseudoType
{
public function underlyingType(): Type
{
return new String_();
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'html-escaped-string';
}
}

View File

@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Integer;
/**
* Value Object representing the type 'int'.
*
* @psalm-immutable
*/
final class IntegerRange extends Integer implements PseudoType
{
private string $minValue;
private string $maxValue;
public function __construct(string $minValue, string $maxValue)
{
$this->minValue = $minValue;
$this->maxValue = $maxValue;
}
public function underlyingType(): Type
{
return new Integer();
}
public function getMinValue(): string
{
return $this->minValue;
}
public function getMaxValue(): string
{
return $this->maxValue;
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'int<' . $this->minValue . ', ' . $this->maxValue . '>';
}
}

View File

@@ -0,0 +1,44 @@
<?php
/*
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*
*/
declare(strict_types=1);
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Integer;
/** @psalm-immutable */
final class IntegerValue implements PseudoType
{
private int $value;
public function __construct(int $value)
{
$this->value = $value;
}
public function getValue(): int
{
return $this->value;
}
public function underlyingType(): Type
{
return new Integer();
}
public function __toString(): string
{
return (string) $this->value;
}
}

View File

@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Array_;
use phpDocumentor\Reflection\Types\Integer;
use phpDocumentor\Reflection\Types\Mixed_;
/**
* Value Object representing the type 'list'.
*
* @psalm-immutable
*/
final class List_ extends Array_ implements PseudoType
{
public function underlyingType(): Type
{
return new Array_();
}
public function __construct(?Type $valueType = null)
{
parent::__construct($valueType, new Integer());
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
if ($this->valueType instanceof Mixed_) {
return 'list';
}
return 'list<' . $this->valueType . '>';
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\String_;
/**
* Value Object representing the type 'string'.
*
* @psalm-immutable
*/
final class LiteralString extends String_ implements PseudoType
{
public function underlyingType(): Type
{
return new String_();
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'literal-string';
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\String_;
/**
* Value Object representing the type 'string'.
*
* @psalm-immutable
*/
final class LowercaseString extends String_ implements PseudoType
{
public function underlyingType(): Type
{
return new String_();
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'lowercase-string';
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Integer;
/**
* Value Object representing the type 'int'.
*
* @psalm-immutable
*/
final class NegativeInteger extends Integer implements PseudoType
{
public function underlyingType(): Type
{
return new Integer();
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'negative-int';
}
}

View File

@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Array_;
use phpDocumentor\Reflection\Types\Integer;
use phpDocumentor\Reflection\Types\Mixed_;
/**
* Value Object representing the type 'non-empty-list'.
*
* @psalm-immutable
*/
final class NonEmptyList extends Array_ implements PseudoType
{
public function underlyingType(): Type
{
return new Array_();
}
public function __construct(?Type $valueType = null)
{
parent::__construct($valueType, new Integer());
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
if ($this->valueType instanceof Mixed_) {
return 'non-empty-list';
}
return 'non-empty-list<' . $this->valueType . '>';
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\String_;
/**
* Value Object representing the type 'string'.
*
* @psalm-immutable
*/
final class NonEmptyLowercaseString extends String_ implements PseudoType
{
public function underlyingType(): Type
{
return new String_();
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'non-empty-lowercase-string';
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\String_;
/**
* Value Object representing the type 'string'.
*
* @psalm-immutable
*/
final class NonEmptyString extends String_ implements PseudoType
{
public function underlyingType(): Type
{
return new String_();
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'non-empty-string';
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\String_;
/**
* Value Object representing the type 'string'.
*
* @psalm-immutable
*/
final class NumericString extends String_ implements PseudoType
{
public function underlyingType(): Type
{
return new String_();
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'numeric-string';
}
}

View File

@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\AggregatedType;
use phpDocumentor\Reflection\Types\Compound;
use phpDocumentor\Reflection\Types\Float_;
use phpDocumentor\Reflection\Types\Integer;
/**
* Value Object representing the 'numeric' pseudo-type, which is either a numeric-string, integer or float.
*
* @psalm-immutable
*/
final class Numeric_ extends AggregatedType implements PseudoType
{
public function __construct()
{
AggregatedType::__construct([new NumericString(), new Integer(), new Float_()], '|');
}
public function underlyingType(): Type
{
return new Compound([new NumericString(), new Integer(), new Float_()]);
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'numeric';
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Integer;
/**
* Value Object representing the type 'int'.
*
* @psalm-immutable
*/
final class PositiveInteger extends Integer implements PseudoType
{
public function underlyingType(): Type
{
return new Integer();
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'positive-int';
}
}

View File

@@ -0,0 +1,46 @@
<?php
/*
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*
*/
declare(strict_types=1);
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\String_;
use function sprintf;
/** @psalm-immutable */
class StringValue implements PseudoType
{
private string $value;
public function __construct(string $value)
{
$this->value = $value;
}
public function getValue(): string
{
return $this->value;
}
public function underlyingType(): Type
{
return new String_();
}
public function __toString(): string
{
return sprintf('"%s"', $this->value);
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\String_;
/**
* Value Object representing the type 'string'.
*
* @psalm-immutable
*/
final class TraitString extends String_ implements PseudoType
{
public function underlyingType(): Type
{
return new String_();
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'trait-string';
}
}

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link https://phpdoc.org
*/
namespace phpDocumentor\Reflection\PseudoTypes;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Boolean;
use function class_alias;
/**
* Value Object representing the PseudoType 'False', which is a Boolean type.
*
* @psalm-immutable
*/
final class True_ extends Boolean implements PseudoType
{
public function underlyingType(): Type
{
return new Boolean();
}
public function __toString(): string
{
return 'true';
}
}
class_alias(True_::class, 'phpDocumentor\Reflection\Types\True_', false);

View File

@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection;
/**
* @psalm-immutable
*/
interface Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string;
}

View File

@@ -0,0 +1,623 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection;
use Doctrine\Deprecations\Deprecation;
use InvalidArgumentException;
use phpDocumentor\Reflection\PseudoTypes\ArrayShape;
use phpDocumentor\Reflection\PseudoTypes\ArrayShapeItem;
use phpDocumentor\Reflection\PseudoTypes\CallableString;
use phpDocumentor\Reflection\PseudoTypes\ConstExpression;
use phpDocumentor\Reflection\PseudoTypes\False_;
use phpDocumentor\Reflection\PseudoTypes\FloatValue;
use phpDocumentor\Reflection\PseudoTypes\HtmlEscapedString;
use phpDocumentor\Reflection\PseudoTypes\IntegerRange;
use phpDocumentor\Reflection\PseudoTypes\IntegerValue;
use phpDocumentor\Reflection\PseudoTypes\List_;
use phpDocumentor\Reflection\PseudoTypes\LiteralString;
use phpDocumentor\Reflection\PseudoTypes\LowercaseString;
use phpDocumentor\Reflection\PseudoTypes\NegativeInteger;
use phpDocumentor\Reflection\PseudoTypes\NonEmptyList;
use phpDocumentor\Reflection\PseudoTypes\NonEmptyLowercaseString;
use phpDocumentor\Reflection\PseudoTypes\NonEmptyString;
use phpDocumentor\Reflection\PseudoTypes\Numeric_;
use phpDocumentor\Reflection\PseudoTypes\NumericString;
use phpDocumentor\Reflection\PseudoTypes\PositiveInteger;
use phpDocumentor\Reflection\PseudoTypes\StringValue;
use phpDocumentor\Reflection\PseudoTypes\TraitString;
use phpDocumentor\Reflection\PseudoTypes\True_;
use phpDocumentor\Reflection\Types\AggregatedType;
use phpDocumentor\Reflection\Types\Array_;
use phpDocumentor\Reflection\Types\ArrayKey;
use phpDocumentor\Reflection\Types\Boolean;
use phpDocumentor\Reflection\Types\Callable_;
use phpDocumentor\Reflection\Types\CallableParameter;
use phpDocumentor\Reflection\Types\ClassString;
use phpDocumentor\Reflection\Types\Collection;
use phpDocumentor\Reflection\Types\Compound;
use phpDocumentor\Reflection\Types\Context;
use phpDocumentor\Reflection\Types\Expression;
use phpDocumentor\Reflection\Types\Float_;
use phpDocumentor\Reflection\Types\Integer;
use phpDocumentor\Reflection\Types\InterfaceString;
use phpDocumentor\Reflection\Types\Intersection;
use phpDocumentor\Reflection\Types\Iterable_;
use phpDocumentor\Reflection\Types\Mixed_;
use phpDocumentor\Reflection\Types\Never_;
use phpDocumentor\Reflection\Types\Null_;
use phpDocumentor\Reflection\Types\Nullable;
use phpDocumentor\Reflection\Types\Object_;
use phpDocumentor\Reflection\Types\Parent_;
use phpDocumentor\Reflection\Types\Resource_;
use phpDocumentor\Reflection\Types\Scalar;
use phpDocumentor\Reflection\Types\Self_;
use phpDocumentor\Reflection\Types\Static_;
use phpDocumentor\Reflection\Types\String_;
use phpDocumentor\Reflection\Types\This;
use phpDocumentor\Reflection\Types\Void_;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
use PHPStan\PhpDocParser\Ast\Type\CallableTypeParameterNode;
use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode;
use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode;
use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode;
use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\ConstExprParser;
use PHPStan\PhpDocParser\Parser\ParserException;
use PHPStan\PhpDocParser\Parser\TokenIterator;
use PHPStan\PhpDocParser\Parser\TypeParser;
use RuntimeException;
use function array_filter;
use function array_key_exists;
use function array_map;
use function array_reverse;
use function class_exists;
use function class_implements;
use function get_class;
use function in_array;
use function sprintf;
use function strpos;
use function strtolower;
use function trim;
final class TypeResolver
{
/** @var string Definition of the NAMESPACE operator in PHP */
private const OPERATOR_NAMESPACE = '\\';
/**
* @var array<string, string> List of recognized keywords and unto which Value Object they map
* @psalm-var array<string, class-string<Type>>
*/
private array $keywords = [
'string' => String_::class,
'class-string' => ClassString::class,
'interface-string' => InterfaceString::class,
'html-escaped-string' => HtmlEscapedString::class,
'lowercase-string' => LowercaseString::class,
'non-empty-lowercase-string' => NonEmptyLowercaseString::class,
'non-empty-string' => NonEmptyString::class,
'numeric-string' => NumericString::class,
'numeric' => Numeric_::class,
'trait-string' => TraitString::class,
'int' => Integer::class,
'integer' => Integer::class,
'positive-int' => PositiveInteger::class,
'negative-int' => NegativeInteger::class,
'bool' => Boolean::class,
'boolean' => Boolean::class,
'real' => Float_::class,
'float' => Float_::class,
'double' => Float_::class,
'object' => Object_::class,
'mixed' => Mixed_::class,
'array' => Array_::class,
'array-key' => ArrayKey::class,
'resource' => Resource_::class,
'void' => Void_::class,
'null' => Null_::class,
'scalar' => Scalar::class,
'callback' => Callable_::class,
'callable' => Callable_::class,
'callable-string' => CallableString::class,
'false' => False_::class,
'true' => True_::class,
'literal-string' => LiteralString::class,
'self' => Self_::class,
'$this' => This::class,
'static' => Static_::class,
'parent' => Parent_::class,
'iterable' => Iterable_::class,
'never' => Never_::class,
'list' => List_::class,
'non-empty-list' => NonEmptyList::class,
];
/** @psalm-readonly */
private FqsenResolver $fqsenResolver;
/** @psalm-readonly */
private TypeParser $typeParser;
/** @psalm-readonly */
private Lexer $lexer;
/**
* Initializes this TypeResolver with the means to create and resolve Fqsen objects.
*/
public function __construct(?FqsenResolver $fqsenResolver = null)
{
$this->fqsenResolver = $fqsenResolver ?: new FqsenResolver();
$this->typeParser = new TypeParser(new ConstExprParser());
$this->lexer = new Lexer();
}
/**
* Analyzes the given type and returns the FQCN variant.
*
* When a type is provided this method checks whether it is not a keyword or
* Fully Qualified Class Name. If so it will use the given namespace and
* aliases to expand the type to a FQCN representation.
*
* This method only works as expected if the namespace and aliases are set;
* no dynamic reflection is being performed here.
*
* @uses Context::getNamespace() to determine with what to prefix the type name.
* @uses Context::getNamespaceAliases() to check whether the first part of the relative type name should not be
* replaced with another namespace.
*
* @param string $type The relative or absolute type.
*/
public function resolve(string $type, ?Context $context = null): Type
{
$type = trim($type);
if (!$type) {
throw new InvalidArgumentException('Attempted to resolve "' . $type . '" but it appears to be empty');
}
if ($context === null) {
$context = new Context('');
}
$tokens = $this->lexer->tokenize($type);
$tokenIterator = new TokenIterator($tokens);
$ast = $this->parse($tokenIterator);
$type = $this->createType($ast, $context);
return $this->tryParseRemainingCompoundTypes($tokenIterator, $context, $type);
}
public function createType(?TypeNode $type, Context $context): Type
{
if ($type === null) {
return new Mixed_();
}
switch (get_class($type)) {
case ArrayTypeNode::class:
return new Array_(
$this->createType($type->type, $context)
);
case ArrayShapeNode::class:
return new ArrayShape(
...array_map(
fn (ArrayShapeItemNode $item) => new ArrayShapeItem(
(string) $item->keyName,
$this->createType($item->valueType, $context),
$item->optional
),
$type->items
)
);
case CallableTypeNode::class:
return $this->createFromCallable($type, $context);
case ConstTypeNode::class:
return $this->createFromConst($type, $context);
case GenericTypeNode::class:
return $this->createFromGeneric($type, $context);
case IdentifierTypeNode::class:
return $this->resolveSingleType($type->name, $context);
case IntersectionTypeNode::class:
return new Intersection(
array_filter(
array_map(
function (TypeNode $nestedType) use ($context) {
$type = $this->createType($nestedType, $context);
if ($type instanceof AggregatedType) {
return new Expression($type);
}
return $type;
},
$type->types
)
)
);
case NullableTypeNode::class:
$nestedType = $this->createType($type->type, $context);
return new Nullable($nestedType);
case UnionTypeNode::class:
return new Compound(
array_filter(
array_map(
function (TypeNode $nestedType) use ($context) {
$type = $this->createType($nestedType, $context);
if ($type instanceof AggregatedType) {
return new Expression($type);
}
return $type;
},
$type->types
)
)
);
case ThisTypeNode::class:
return new This();
case ConditionalTypeNode::class:
case ConditionalTypeForParameterNode::class:
case OffsetAccessTypeNode::class:
default:
return new Mixed_();
}
}
private function createFromGeneric(GenericTypeNode $type, Context $context): Type
{
switch (strtolower($type->type->name)) {
case 'array':
return $this->createArray($type->genericTypes, $context);
case 'class-string':
$subType = $this->createType($type->genericTypes[0], $context);
if (!$subType instanceof Object_ || $subType->getFqsen() === null) {
throw new RuntimeException(
$subType . ' is not a class string'
);
}
return new ClassString(
$subType->getFqsen()
);
case 'interface-string':
$subType = $this->createType($type->genericTypes[0], $context);
if (!$subType instanceof Object_ || $subType->getFqsen() === null) {
throw new RuntimeException(
$subType . ' is not a class string'
);
}
return new InterfaceString(
$subType->getFqsen()
);
case 'list':
return new List_(
$this->createType($type->genericTypes[0], $context)
);
case 'non-empty-list':
return new NonEmptyList(
$this->createType($type->genericTypes[0], $context)
);
case 'int':
if (isset($type->genericTypes[1]) === false) {
throw new RuntimeException('int<min,max> has not the correct format');
}
return new IntegerRange(
(string) $type->genericTypes[0],
(string) $type->genericTypes[1],
);
case 'iterable':
return new Iterable_(
...array_reverse(
array_map(
fn (TypeNode $genericType) => $this->createType($genericType, $context),
$type->genericTypes
)
)
);
default:
$collectionType = $this->createType($type->type, $context);
if ($collectionType instanceof Object_ === false) {
throw new RuntimeException(sprintf('%s is not a collection', (string) $collectionType));
}
return new Collection(
$collectionType->getFqsen(),
...array_reverse(
array_map(
fn (TypeNode $genericType) => $this->createType($genericType, $context),
$type->genericTypes
)
)
);
}
}
private function createFromCallable(CallableTypeNode $type, Context $context): Callable_
{
return new Callable_(
array_map(
function (CallableTypeParameterNode $param) use ($context) {
return new CallableParameter(
$this->createType($param->type, $context),
$param->parameterName !== '' ? trim($param->parameterName, '$') : null,
$param->isReference,
$param->isVariadic,
$param->isOptional
);
},
$type->parameters
),
$this->createType($type->returnType, $context),
);
}
private function createFromConst(ConstTypeNode $type, Context $context): Type
{
switch (true) {
case $type->constExpr instanceof ConstExprIntegerNode:
return new IntegerValue((int) $type->constExpr->value);
case $type->constExpr instanceof ConstExprFloatNode:
return new FloatValue((float) $type->constExpr->value);
case $type->constExpr instanceof ConstExprStringNode:
return new StringValue($type->constExpr->value);
case $type->constExpr instanceof ConstFetchNode:
return new ConstExpression(
$this->resolve($type->constExpr->className, $context),
$type->constExpr->name
);
default:
throw new RuntimeException(sprintf('Unsupported constant type %s', get_class($type)));
}
}
/**
* resolve the given type into a type object
*
* @param string $type the type string, representing a single type
*
* @return Type|Array_|Object_
*
* @psalm-mutation-free
*/
private function resolveSingleType(string $type, Context $context): object
{
switch (true) {
case $this->isKeyword($type):
return $this->resolveKeyword($type);
case $this->isFqsen($type):
return $this->resolveTypedObject($type);
case $this->isPartialStructuralElementName($type):
return $this->resolveTypedObject($type, $context);
// @codeCoverageIgnoreStart
default:
// I haven't got the foggiest how the logic would come here but added this as a defense.
throw new RuntimeException(
'Unable to resolve type "' . $type . '", there is no known method to resolve it'
);
}
// @codeCoverageIgnoreEnd
}
/**
* Adds a keyword to the list of Keywords and associates it with a specific Value Object.
*
* @psalm-param class-string<Type> $typeClassName
*/
public function addKeyword(string $keyword, string $typeClassName): void
{
if (!class_exists($typeClassName)) {
throw new InvalidArgumentException(
'The Value Object that needs to be created with a keyword "' . $keyword . '" must be an existing class'
. ' but we could not find the class ' . $typeClassName
);
}
$interfaces = class_implements($typeClassName);
if ($interfaces === false) {
throw new InvalidArgumentException(
'The Value Object that needs to be created with a keyword "' . $keyword . '" must be an existing class'
. ' but we could not find the class ' . $typeClassName
);
}
if (!in_array(Type::class, $interfaces, true)) {
throw new InvalidArgumentException(
'The class "' . $typeClassName . '" must implement the interface "phpDocumentor\Reflection\Type"'
);
}
$this->keywords[$keyword] = $typeClassName;
}
/**
* Detects whether the given type represents a PHPDoc keyword.
*
* @param string $type A relative or absolute type as defined in the phpDocumentor documentation.
*
* @psalm-mutation-free
*/
private function isKeyword(string $type): bool
{
return array_key_exists(strtolower($type), $this->keywords);
}
/**
* Detects whether the given type represents a relative structural element name.
*
* @param string $type A relative or absolute type as defined in the phpDocumentor documentation.
*
* @psalm-mutation-free
*/
private function isPartialStructuralElementName(string $type): bool
{
return (isset($type[0]) && $type[0] !== self::OPERATOR_NAMESPACE) && !$this->isKeyword($type);
}
/**
* Tests whether the given type is a Fully Qualified Structural Element Name.
*
* @psalm-mutation-free
*/
private function isFqsen(string $type): bool
{
return strpos($type, self::OPERATOR_NAMESPACE) === 0;
}
/**
* Resolves the given keyword (such as `string`) into a Type object representing that keyword.
*
* @psalm-mutation-free
*/
private function resolveKeyword(string $type): Type
{
$className = $this->keywords[strtolower($type)];
return new $className();
}
/**
* Resolves the given FQSEN string into an FQSEN object.
*
* @psalm-mutation-free
*/
private function resolveTypedObject(string $type, ?Context $context = null): Object_
{
return new Object_($this->fqsenResolver->resolve($type, $context));
}
/** @param TypeNode[] $typeNodes */
private function createArray(array $typeNodes, Context $context): Array_
{
$types = array_reverse(
array_map(
fn (TypeNode $node) => $this->createType($node, $context),
$typeNodes
)
);
if (isset($types[1]) === false) {
return new Array_(...$types);
}
if ($this->validArrayKeyType($types[1]) || $types[1] instanceof ArrayKey) {
return new Array_(...$types);
}
if ($types[1] instanceof Compound && $types[1]->getIterator()->count() === 2) {
if ($this->validArrayKeyType($types[1]->get(0)) && $this->validArrayKeyType($types[1]->get(1))) {
return new Array_(...$types);
}
}
throw new RuntimeException('An array can have only integers or strings as keys');
}
private function validArrayKeyType(?Type $type): bool
{
return $type instanceof String_ || $type instanceof Integer;
}
private function parse(TokenIterator $tokenIterator): TypeNode
{
try {
$ast = $this->typeParser->parse($tokenIterator);
} catch (ParserException $e) {
throw new RuntimeException($e->getMessage(), 0, $e);
}
return $ast;
}
/**
* Will try to parse unsupported type notations by phpstan
*
* The phpstan parser doesn't support the illegal nullable combinations like this library does.
* This method will warn the user about those notations but for bc purposes we will still have it here.
*/
private function tryParseRemainingCompoundTypes(TokenIterator $tokenIterator, Context $context, Type $type): Type
{
if (
$tokenIterator->isCurrentTokenType(Lexer::TOKEN_UNION) ||
$tokenIterator->isCurrentTokenType(Lexer::TOKEN_INTERSECTION)
) {
Deprecation::trigger(
'phpdocumentor/type-resolver',
'https://github.com/phpDocumentor/TypeResolver/issues/184',
'Legacy nullable type detected, please update your code as
you are using nullable types in a docblock. support will be removed in v2.0.0',
);
}
$continue = true;
while ($continue) {
$continue = false;
while ($tokenIterator->tryConsumeTokenType(Lexer::TOKEN_UNION)) {
$ast = $this->parse($tokenIterator);
$type2 = $this->createType($ast, $context);
$type = new Compound([$type, $type2]);
$continue = true;
}
while ($tokenIterator->tryConsumeTokenType(Lexer::TOKEN_INTERSECTION)) {
$ast = $this->typeParser->parse($tokenIterator);
$type2 = $this->createType($ast, $context);
$type = new Intersection([$type, $type2]);
$continue = true;
}
}
return $type;
}
}

View File

@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Represents a list of values. This is an abstract class for Array_ and Collection.
*
* @psalm-immutable
*/
abstract class AbstractList implements Type
{
/** @var Type */
protected $valueType;
/** @var Type|null */
protected $keyType;
/** @var Type */
protected $defaultKeyType;
/**
* Initializes this representation of an array with the given Type.
*/
public function __construct(?Type $valueType = null, ?Type $keyType = null)
{
if ($valueType === null) {
$valueType = new Mixed_();
}
$this->valueType = $valueType;
$this->defaultKeyType = new Compound([new String_(), new Integer()]);
$this->keyType = $keyType;
}
/**
* Returns the type for the keys of this array.
*/
public function getKeyType(): Type
{
return $this->keyType ?? $this->defaultKeyType;
}
/**
* Returns the type for the values of this array.
*/
public function getValueType(): Type
{
return $this->valueType;
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
if ($this->keyType) {
return 'array<' . $this->keyType . ',' . $this->valueType . '>';
}
if ($this->valueType instanceof Mixed_) {
return 'array';
}
if ($this->valueType instanceof Compound) {
return '(' . $this->valueType . ')[]';
}
return $this->valueType . '[]';
}
}

View File

@@ -0,0 +1,124 @@
<?php
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
declare(strict_types=1);
namespace phpDocumentor\Reflection\Types;
use ArrayIterator;
use IteratorAggregate;
use phpDocumentor\Reflection\Type;
use function array_key_exists;
use function implode;
/**
* Base class for aggregated types like Compound and Intersection
*
* A Aggregated Type is not so much a special keyword or object reference but is a series of Types that are separated
* using separator.
*
* @psalm-immutable
* @template-implements IteratorAggregate<int, Type>
*/
abstract class AggregatedType implements Type, IteratorAggregate
{
/**
* @psalm-allow-private-mutation
* @var array<int, Type>
*/
private array $types = [];
private string $token;
/**
* @param array<Type> $types
*/
public function __construct(array $types, string $token)
{
foreach ($types as $type) {
$this->add($type);
}
$this->token = $token;
}
/**
* Returns the type at the given index.
*/
public function get(int $index): ?Type
{
if (!$this->has($index)) {
return null;
}
return $this->types[$index];
}
/**
* Tests if this compound type has a type with the given index.
*/
public function has(int $index): bool
{
return array_key_exists($index, $this->types);
}
/**
* Tests if this compound type contains the given type.
*/
public function contains(Type $type): bool
{
foreach ($this->types as $typePart) {
// if the type is duplicate; do not add it
if ((string) $typePart === (string) $type) {
return true;
}
}
return false;
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return implode($this->token, $this->types);
}
/**
* @return ArrayIterator<int, Type>
*/
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->types);
}
/**
* @psalm-suppress ImpureMethodCall
*/
private function add(Type $type): void
{
if ($type instanceof static) {
foreach ($type->getIterator() as $subType) {
$this->add($subType);
}
return;
}
// if the type is duplicate; do not add it
if ($this->contains($type)) {
return;
}
$this->types[] = $type;
}
}

View File

@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing a array-key Type.
*
* A array-key Type is the supertype (but not a union) of int and string.
*
* @psalm-immutable
*/
final class ArrayKey extends AggregatedType implements PseudoType
{
public function __construct()
{
parent::__construct([new String_(), new Integer()], '|');
}
public function underlyingType(): Type
{
return new Compound([new String_(), new Integer()]);
}
public function __toString(): string
{
return 'array-key';
}
}

View File

@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
/**
* Represents an array type as described in the PSR-5, the PHPDoc Standard.
*
* An array can be represented in two forms:
*
* 1. Untyped (`array`), where the key and value type is unknown and hence classified as 'Mixed_'.
* 2. Types (`string[]`), where the value type is provided by preceding an opening and closing square bracket with a
* type name.
*
* @psalm-immutable
*/
class Array_ extends AbstractList
{
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing a Boolean type.
*
* @psalm-immutable
*/
class Boolean implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'bool';
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
declare(strict_types=1);
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing a Callable parameters.
*
* @psalm-immutable
*/
final class CallableParameter
{
private Type $type;
private bool $isReference;
private bool $isVariadic;
private bool $isOptional;
private ?string $name;
public function __construct(
Type $type,
?string $name = null,
bool $isReference = false,
bool $isVariadic = false,
bool $isOptional = false
) {
$this->type = $type;
$this->isReference = $isReference;
$this->isVariadic = $isVariadic;
$this->isOptional = $isOptional;
$this->name = $name;
}
public function getName(): ?string
{
return $this->name;
}
public function getType(): Type
{
return $this->type;
}
public function isReference(): bool
{
return $this->isReference;
}
public function isVariadic(): bool
{
return $this->isVariadic;
}
public function isOptional(): bool
{
return $this->isOptional;
}
}

View File

@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing a Callable type.
*
* @psalm-immutable
*/
final class Callable_ implements Type
{
private ?Type $returnType;
/** @var CallableParameter[] */
private array $parameters;
/**
* @param CallableParameter[] $parameters
*/
public function __construct(array $parameters = [], ?Type $returnType = null)
{
$this->parameters = $parameters;
$this->returnType = $returnType;
}
/** @return CallableParameter[] */
public function getParameters(): array
{
return $this->parameters;
}
public function getReturnType(): ?Type
{
return $this->returnType;
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'callable';
}
}

View File

@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Fqsen;
use phpDocumentor\Reflection\PseudoType;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing the type 'string'.
*
* @psalm-immutable
*/
final class ClassString extends String_ implements PseudoType
{
private ?Fqsen $fqsen;
/**
* Initializes this representation of a class string with the given Fqsen.
*/
public function __construct(?Fqsen $fqsen = null)
{
$this->fqsen = $fqsen;
}
public function underlyingType(): Type
{
return new String_();
}
/**
* Returns the FQSEN associated with this object.
*/
public function getFqsen(): ?Fqsen
{
return $this->fqsen;
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
if ($this->fqsen === null) {
return 'class-string';
}
return 'class-string<' . (string) $this->fqsen . '>';
}
}

View File

@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Fqsen;
use phpDocumentor\Reflection\Type;
/**
* Represents a collection type as described in the PSR-5, the PHPDoc Standard.
*
* A collection can be represented in two forms:
*
* 1. `ACollectionObject<aValueType>`
* 2. `ACollectionObject<aValueType,aKeyType>`
*
* - ACollectionObject can be 'array' or an object that can act as an array
* - aValueType and aKeyType can be any type expression
*
* @psalm-immutable
*/
final class Collection extends AbstractList
{
private ?Fqsen $fqsen;
/**
* Initializes this representation of an array with the given Type or Fqsen.
*/
public function __construct(?Fqsen $fqsen, Type $valueType, ?Type $keyType = null)
{
parent::__construct($valueType, $keyType);
$this->fqsen = $fqsen;
}
/**
* Returns the FQSEN associated with this object.
*/
public function getFqsen(): ?Fqsen
{
return $this->fqsen;
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
$objectType = (string) ($this->fqsen ?? 'object');
if ($this->keyType === null) {
return $objectType . '<' . $this->valueType . '>';
}
return $objectType . '<' . $this->keyType . ',' . $this->valueType . '>';
}
}

View File

@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing a Compound Type.
*
* A Compound Type is not so much a special keyword or object reference but is a series of Types that are separated
* using an OR operator (`|`). This combination of types signifies that whatever is associated with this compound type
* may contain a value with any of the given types.
*
* @psalm-immutable
*/
final class Compound extends AggregatedType
{
/**
* Initializes a compound type (i.e. `string|int`) and tests if the provided types all implement the Type interface.
*
* @param array<Type> $types
*/
public function __construct(array $types)
{
parent::__construct($types, '|');
}
}

View File

@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use function strlen;
use function substr;
use function trim;
/**
* Provides information about the Context in which the DocBlock occurs that receives this context.
*
* A DocBlock does not know of its own accord in which namespace it occurs and which namespace aliases are applicable
* for the block of code in which it is in. This information is however necessary to resolve Class names in tags since
* you can provide a short form or make use of namespace aliases.
*
* The phpDocumentor Reflection component knows how to create this class but if you use the DocBlock parser from your
* own application it is possible to generate a Context class using the ContextFactory; this will analyze the file in
* which an associated class resides for its namespace and imports.
*
* @see ContextFactory::createFromClassReflector()
* @see ContextFactory::createForNamespace()
*
* @psalm-immutable
*/
final class Context
{
/** @var string The current namespace. */
private string $namespace;
/**
* @var string[] List of namespace aliases => Fully Qualified Namespace.
* @psalm-var array<string, string>
*/
private array $namespaceAliases;
/**
* Initializes the new context and normalizes all passed namespaces to be in Qualified Namespace Name (QNN)
* format (without a preceding `\`).
*
* @param string $namespace The namespace where this DocBlock resides in.
* @param string[] $namespaceAliases List of namespace aliases => Fully Qualified Namespace.
* @psalm-param array<string, string> $namespaceAliases
*/
public function __construct(string $namespace, array $namespaceAliases = [])
{
$this->namespace = $namespace !== 'global' && $namespace !== 'default'
? trim($namespace, '\\')
: '';
foreach ($namespaceAliases as $alias => $fqnn) {
if ($fqnn[0] === '\\') {
$fqnn = substr($fqnn, 1);
}
if ($fqnn[strlen($fqnn) - 1] === '\\') {
$fqnn = substr($fqnn, 0, -1);
}
$namespaceAliases[$alias] = $fqnn;
}
$this->namespaceAliases = $namespaceAliases;
}
/**
* Returns the Qualified Namespace Name (thus without `\` in front) where the associated element is in.
*/
public function getNamespace(): string
{
return $this->namespace;
}
/**
* Returns a list of Qualified Namespace Names (thus without `\` in front) that are imported, the keys represent
* the alias for the imported Namespace.
*
* @return string[]
* @psalm-return array<string, string>
*/
public function getNamespaceAliases(): array
{
return $this->namespaceAliases;
}
}

View File

@@ -0,0 +1,420 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use ArrayIterator;
use InvalidArgumentException;
use ReflectionClass;
use ReflectionClassConstant;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionProperty;
use Reflector;
use RuntimeException;
use UnexpectedValueException;
use function define;
use function defined;
use function file_exists;
use function file_get_contents;
use function get_class;
use function in_array;
use function is_string;
use function strrpos;
use function substr;
use function token_get_all;
use function trim;
use const T_AS;
use const T_CLASS;
use const T_CURLY_OPEN;
use const T_DOLLAR_OPEN_CURLY_BRACES;
use const T_NAME_FULLY_QUALIFIED;
use const T_NAME_QUALIFIED;
use const T_NAMESPACE;
use const T_NS_SEPARATOR;
use const T_STRING;
use const T_USE;
if (!defined('T_NAME_QUALIFIED')) {
define('T_NAME_QUALIFIED', 'T_NAME_QUALIFIED');
}
if (!defined('T_NAME_FULLY_QUALIFIED')) {
define('T_NAME_FULLY_QUALIFIED', 'T_NAME_FULLY_QUALIFIED');
}
/**
* Convenience class to create a Context for DocBlocks when not using the Reflection Component of phpDocumentor.
*
* For a DocBlock to be able to resolve types that use partial namespace names or rely on namespace imports we need to
* provide a bit of context so that the DocBlock can read that and based on it decide how to resolve the types to
* Fully Qualified names.
*
* @see Context for more information.
*/
final class ContextFactory
{
/** The literal used at the end of a use statement. */
private const T_LITERAL_END_OF_USE = ';';
/** The literal used between sets of use statements */
private const T_LITERAL_USE_SEPARATOR = ',';
/**
* Build a Context given a Class Reflection.
*
* @see Context for more information on Contexts.
*/
public function createFromReflector(Reflector $reflector): Context
{
if ($reflector instanceof ReflectionClass) {
//phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.MissingVariable
/** @var ReflectionClass<object> $reflector */
return $this->createFromReflectionClass($reflector);
}
if ($reflector instanceof ReflectionParameter) {
return $this->createFromReflectionParameter($reflector);
}
if ($reflector instanceof ReflectionMethod) {
return $this->createFromReflectionMethod($reflector);
}
if ($reflector instanceof ReflectionProperty) {
return $this->createFromReflectionProperty($reflector);
}
if ($reflector instanceof ReflectionClassConstant) {
return $this->createFromReflectionClassConstant($reflector);
}
throw new UnexpectedValueException('Unhandled \Reflector instance given: ' . get_class($reflector));
}
private function createFromReflectionParameter(ReflectionParameter $parameter): Context
{
$class = $parameter->getDeclaringClass();
if (!$class) {
throw new InvalidArgumentException('Unable to get class of ' . $parameter->getName());
}
return $this->createFromReflectionClass($class);
}
private function createFromReflectionMethod(ReflectionMethod $method): Context
{
$class = $method->getDeclaringClass();
return $this->createFromReflectionClass($class);
}
private function createFromReflectionProperty(ReflectionProperty $property): Context
{
$class = $property->getDeclaringClass();
return $this->createFromReflectionClass($class);
}
private function createFromReflectionClassConstant(ReflectionClassConstant $constant): Context
{
//phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.MissingVariable
/** @phpstan-var ReflectionClass<object> $class */
$class = $constant->getDeclaringClass();
return $this->createFromReflectionClass($class);
}
/**
* @phpstan-param ReflectionClass<object> $class
*/
private function createFromReflectionClass(ReflectionClass $class): Context
{
$fileName = $class->getFileName();
$namespace = $class->getNamespaceName();
if (is_string($fileName) && file_exists($fileName)) {
$contents = file_get_contents($fileName);
if ($contents === false) {
throw new RuntimeException('Unable to read file "' . $fileName . '"');
}
return $this->createForNamespace($namespace, $contents);
}
return new Context($namespace, []);
}
/**
* Build a Context for a namespace in the provided file contents.
*
* @see Context for more information on Contexts.
*
* @param string $namespace It does not matter if a `\` precedes the namespace name,
* this method first normalizes.
* @param string $fileContents The file's contents to retrieve the aliases from with the given namespace.
*/
public function createForNamespace(string $namespace, string $fileContents): Context
{
$namespace = trim($namespace, '\\');
$useStatements = [];
$currentNamespace = '';
$tokens = new ArrayIterator(token_get_all($fileContents));
while ($tokens->valid()) {
$currentToken = $tokens->current();
switch ($currentToken[0]) {
case T_NAMESPACE:
$currentNamespace = $this->parseNamespace($tokens);
break;
case T_CLASS:
// Fast-forward the iterator through the class so that any
// T_USE tokens found within are skipped - these are not
// valid namespace use statements so should be ignored.
$braceLevel = 0;
$firstBraceFound = false;
while ($tokens->valid() && ($braceLevel > 0 || !$firstBraceFound)) {
$currentToken = $tokens->current();
if (
$currentToken === '{'
|| in_array($currentToken[0], [T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true)
) {
if (!$firstBraceFound) {
$firstBraceFound = true;
}
++$braceLevel;
}
if ($currentToken === '}') {
--$braceLevel;
}
$tokens->next();
}
break;
case T_USE:
if ($currentNamespace === $namespace) {
$useStatements += $this->parseUseStatement($tokens);
}
break;
}
$tokens->next();
}
return new Context($namespace, $useStatements);
}
/**
* Deduce the name from tokens when we are at the T_NAMESPACE token.
*
* @param ArrayIterator<int, string|array{0:int,1:string,2:int}> $tokens
*/
private function parseNamespace(ArrayIterator $tokens): string
{
// skip to the first string or namespace separator
$this->skipToNextStringOrNamespaceSeparator($tokens);
$name = '';
$acceptedTokens = [T_STRING, T_NS_SEPARATOR, T_NAME_QUALIFIED];
while ($tokens->valid() && in_array($tokens->current()[0], $acceptedTokens, true)) {
$name .= $tokens->current()[1];
$tokens->next();
}
return $name;
}
/**
* Deduce the names of all imports when we are at the T_USE token.
*
* @param ArrayIterator<int, string|array{0:int,1:string,2:int}> $tokens
*
* @return string[]
* @psalm-return array<string, string>
*/
private function parseUseStatement(ArrayIterator $tokens): array
{
$uses = [];
while ($tokens->valid()) {
$this->skipToNextStringOrNamespaceSeparator($tokens);
$uses += $this->extractUseStatements($tokens);
$currentToken = $tokens->current();
if ($currentToken[0] === self::T_LITERAL_END_OF_USE) {
return $uses;
}
}
return $uses;
}
/**
* Fast-forwards the iterator as longs as we don't encounter a T_STRING or T_NS_SEPARATOR token.
*
* @param ArrayIterator<int, string|array{0:int,1:string,2:int}> $tokens
*/
private function skipToNextStringOrNamespaceSeparator(ArrayIterator $tokens): void
{
while ($tokens->valid()) {
$currentToken = $tokens->current();
if (in_array($currentToken[0], [T_STRING, T_NS_SEPARATOR], true)) {
break;
}
if ($currentToken[0] === T_NAME_QUALIFIED) {
break;
}
if (defined('T_NAME_FULLY_QUALIFIED') && $currentToken[0] === T_NAME_FULLY_QUALIFIED) {
break;
}
$tokens->next();
}
}
/**
* Deduce the namespace name and alias of an import when we are at the T_USE token or have not reached the end of
* a USE statement yet. This will return a key/value array of the alias => namespace.
*
* @param ArrayIterator<int, string|array{0:int,1:string,2:int}> $tokens
*
* @return string[]
* @psalm-return array<string, string>
*
* @psalm-suppress TypeDoesNotContainType
*/
private function extractUseStatements(ArrayIterator $tokens): array
{
$extractedUseStatements = [];
$groupedNs = '';
$currentNs = '';
$currentAlias = '';
$state = 'start';
while ($tokens->valid()) {
$currentToken = $tokens->current();
$tokenId = is_string($currentToken) ? $currentToken : $currentToken[0];
$tokenValue = is_string($currentToken) ? null : $currentToken[1];
switch ($state) {
case 'start':
switch ($tokenId) {
case T_STRING:
case T_NS_SEPARATOR:
$currentNs .= (string) $tokenValue;
$currentAlias = $tokenValue;
break;
case T_NAME_QUALIFIED:
case T_NAME_FULLY_QUALIFIED:
$currentNs .= (string) $tokenValue;
$currentAlias = substr(
(string) $tokenValue,
(int) (strrpos((string) $tokenValue, '\\')) + 1
);
break;
case T_CURLY_OPEN:
case '{':
$state = 'grouped';
$groupedNs = $currentNs;
break;
case T_AS:
$state = 'start-alias';
break;
case self::T_LITERAL_USE_SEPARATOR:
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
break;
case 'start-alias':
switch ($tokenId) {
case T_STRING:
$currentAlias = $tokenValue;
break;
case self::T_LITERAL_USE_SEPARATOR:
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
break;
case 'grouped':
switch ($tokenId) {
case T_STRING:
case T_NS_SEPARATOR:
$currentNs .= (string) $tokenValue;
$currentAlias = $tokenValue;
break;
case T_AS:
$state = 'grouped-alias';
break;
case self::T_LITERAL_USE_SEPARATOR:
$state = 'grouped';
$extractedUseStatements[(string) $currentAlias] = $currentNs;
$currentNs = $groupedNs;
$currentAlias = '';
break;
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
break;
case 'grouped-alias':
switch ($tokenId) {
case T_STRING:
$currentAlias = $tokenValue;
break;
case self::T_LITERAL_USE_SEPARATOR:
$state = 'grouped';
$extractedUseStatements[(string) $currentAlias] = $currentNs;
$currentNs = $groupedNs;
$currentAlias = '';
break;
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
}
if ($state === 'end') {
break;
}
$tokens->next();
}
if ($groupedNs !== $currentNs) {
$extractedUseStatements[(string) $currentAlias] = $currentNs;
}
return $extractedUseStatements;
}
}

View File

@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Represents an expression type as described in the PSR-5, the PHPDoc Standard.
*
* @psalm-immutable
*/
final class Expression implements Type
{
protected Type $valueType;
/**
* Initializes this representation of an array with the given Type.
*/
public function __construct(Type $valueType)
{
$this->valueType = $valueType;
}
/**
* Returns the value for the keys of this array.
*/
public function getValueType(): Type
{
return $this->valueType;
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return '(' . $this->valueType . ')';
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing a Float.
*
* @psalm-immutable
*/
final class Float_ implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'float';
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value object representing Integer type
*
* @psalm-immutable
*/
class Integer implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'int';
}
}

View File

@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Fqsen;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing the type 'string'.
*
* @psalm-immutable
*/
final class InterfaceString implements Type
{
private ?Fqsen $fqsen;
/**
* Initializes this representation of a class string with the given Fqsen.
*/
public function __construct(?Fqsen $fqsen = null)
{
$this->fqsen = $fqsen;
}
/**
* Returns the FQSEN associated with this object.
*/
public function getFqsen(): ?Fqsen
{
return $this->fqsen;
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
if ($this->fqsen === null) {
return 'interface-string';
}
return 'interface-string<' . (string) $this->fqsen . '>';
}
}

View File

@@ -0,0 +1,37 @@
<?php
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
declare(strict_types=1);
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing a Compound Type.
*
* A Intersection Type is not so much a special keyword or object reference but is a series of Types that are separated
* using an AND operator (`&`). This combination of types signifies that whatever is associated with this Intersection
* type may contain a value with any of the given types.
*
* @psalm-immutable
*/
final class Intersection extends AggregatedType
{
/**
* Initializes a intersection type (i.e. `\A&\B`) and tests if the provided types all implement the Type interface.
*
* @param array<Type> $types
*/
public function __construct(array $types)
{
parent::__construct($types, '&');
}
}

View File

@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
/**
* Value Object representing iterable type
*
* @psalm-immutable
*/
final class Iterable_ extends AbstractList
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
if ($this->keyType) {
return 'iterable<' . $this->keyType . ',' . $this->valueType . '>';
}
if ($this->valueType instanceof Mixed_) {
return 'iterable';
}
return 'iterable<' . $this->valueType . '>';
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing an unknown, or mixed, type.
*
* @psalm-immutable
*/
final class Mixed_ implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'mixed';
}
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing the return-type 'never'.
*
* Never is generally only used when working with return types as it signifies that the method that only
* ever throw or exit.
*
* @psalm-immutable
*/
final class Never_ implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'never';
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing a null value or type.
*
* @psalm-immutable
*/
final class Null_ implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'null';
}
}

View File

@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing a nullable type. The real type is wrapped.
*
* @psalm-immutable
*/
final class Nullable implements Type
{
/** @var Type The actual type that is wrapped */
private Type $realType;
/**
* Initialises this nullable type using the real type embedded
*/
public function __construct(Type $realType)
{
$this->realType = $realType;
}
/**
* Provide access to the actual type directly, if needed.
*/
public function getActualType(): Type
{
return $this->realType;
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return '?' . $this->realType->__toString();
}
}

View File

@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use InvalidArgumentException;
use phpDocumentor\Reflection\Fqsen;
use phpDocumentor\Reflection\Type;
use function strpos;
/**
* Value Object representing an object.
*
* An object can be either typed or untyped. When an object is typed it means that it has an identifier, the FQSEN,
* pointing to an element in PHP. Object types that are untyped do not refer to a specific class but represent objects
* in general.
*
* @psalm-immutable
*/
final class Object_ implements Type
{
private ?Fqsen $fqsen;
/**
* Initializes this object with an optional FQSEN, if not provided this object is considered 'untyped'.
*
* @throws InvalidArgumentException When provided $fqsen is not a valid type.
*/
public function __construct(?Fqsen $fqsen = null)
{
if (strpos((string) $fqsen, '::') !== false || strpos((string) $fqsen, '()') !== false) {
throw new InvalidArgumentException(
'Object types can only refer to a class, interface or trait but a method, function, constant or '
. 'property was received: ' . (string) $fqsen
);
}
$this->fqsen = $fqsen;
}
/**
* Returns the FQSEN associated with this object.
*/
public function getFqsen(): ?Fqsen
{
return $this->fqsen;
}
public function __toString(): string
{
if ($this->fqsen) {
return (string) $this->fqsen;
}
return 'object';
}
}

View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing the 'parent' type.
*
* Parent, as a Type, represents the parent class of class in which the associated element was defined.
*
* @psalm-immutable
*/
final class Parent_ implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'parent';
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing the 'resource' Type.
*
* @psalm-immutable
*/
final class Resource_ implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'resource';
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing the 'scalar' pseudo-type, which is either a string, integer, float or boolean.
*
* @psalm-immutable
*/
final class Scalar implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'scalar';
}
}

View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing the 'self' type.
*
* Self, as a Type, represents the class in which the associated element was defined.
*
* @psalm-immutable
*/
final class Self_ implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'self';
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing the 'static' type.
*
* Self, as a Type, represents the class in which the associated element was called. This differs from self as self does
* not take inheritance into account but static means that the return type is always that of the class of the called
* element.
*
* See the documentation on late static binding in the PHP Documentation for more information on the difference between
* static and self.
*
* @psalm-immutable
*/
final class Static_ implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'static';
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing the type 'string'.
*
* @psalm-immutable
*/
class String_ implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'string';
}
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing the '$this' pseudo-type.
*
* $this, as a Type, represents the instance of the class associated with the element as it was called. $this is
* commonly used when documenting fluent interfaces since it represents that the same object is returned.
*
* @psalm-immutable
*/
final class This implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return '$this';
}
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing the return-type 'void'.
*
* Void is generally only used when working with return types as it signifies that the method intentionally does not
* return any value.
*
* @psalm-immutable
*/
final class Void_ implements Type
{
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*/
public function __toString(): string
{
return 'void';
}
}