fix:repo cleanup

This commit is contained in:
2025-11-08 20:09:07 +00:00
parent f1da93791d
commit dedcc73567
1204 changed files with 121800 additions and 16971 deletions
+21
View File
@@ -2,6 +2,24 @@
All notable changes are documented in this file using the [Keep a CHANGELOG](https://keepachangelog.com/) principles.
## [4.2.0] - 2025-09-14
### Changed
* [#3](https://github.com/sebastianbergmann/cli-parser/pull/3): Print most similar options when reporting unknown options
## [4.1.0] - 2025-09-13
### Changed
* [#2](https://github.com/sebastianbergmann/cli-parser/pull/2): Print similar options when reporting ambiguous options
## [4.0.0] - 2025-02-07
### Removed
* This component is no longer supported on PHP 8.2
## [3.0.2] - 2024-07-03
### Changed
@@ -42,6 +60,9 @@ All notable changes are documented in this file using the [Keep a CHANGELOG](htt
* Initial release
[4.2.0]: https://github.com/sebastianbergmann/cli-parser/compare/4.1.0...4.2.0
[4.1.0]: https://github.com/sebastianbergmann/cli-parser/compare/4.0.0...4.1.0
[4.0.0]: https://github.com/sebastianbergmann/cli-parser/compare/3.0...4.0.0
[3.0.2]: https://github.com/sebastianbergmann/cli-parser/compare/3.0.1...3.0.2
[3.0.1]: https://github.com/sebastianbergmann/cli-parser/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/sebastianbergmann/cli-parser/compare/2.0...3.0.0
+1 -1
View File
@@ -1,6 +1,6 @@
BSD 3-Clause License
Copyright (c) 2020-2024, Sebastian Bergmann
Copyright (c) 2020-2025, Sebastian Bergmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
+1 -1
View File
@@ -1,4 +1,4 @@
[![Latest Stable Version](https://poser.pugx.org/sebastian/cli-parser/v/stable.png)](https://packagist.org/packages/sebastian/cli-parser)
[![Latest Stable Version](https://poser.pugx.org/sebastian/cli-parser/v)](https://packagist.org/packages/sebastian/cli-parser)
[![CI Status](https://github.com/sebastianbergmann/cli-parser/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/cli-parser/actions)
[![codecov](https://codecov.io/gh/sebastianbergmann/cli-parser/branch/main/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/cli-parser)
+4 -4
View File
@@ -17,14 +17,14 @@
},
"prefer-stable": true,
"require": {
"php": ">=8.2"
"php": ">=8.3"
},
"require-dev": {
"phpunit/phpunit": "^11.0"
"phpunit/phpunit": "^12.0"
},
"config": {
"platform": {
"php": "8.2.0"
"php": "8.3.0"
},
"optimize-autoloader": true,
"sort-packages": true
@@ -36,7 +36,7 @@
},
"extra": {
"branch-alias": {
"dev-main": "3.0-dev"
"dev-main": "4.2-dev"
}
}
}
+56 -15
View File
@@ -19,17 +19,19 @@ use function current;
use function explode;
use function is_array;
use function is_int;
use function is_string;
use function key;
use function levenshtein;
use function next;
use function preg_replace;
use function reset;
use function rtrim;
use function sort;
use function str_ends_with;
use function str_starts_with;
use function strlen;
use function strstr;
use function substr;
use function usort;
final class Parser
{
@@ -42,11 +44,11 @@ final class Parser
* @throws RequiredOptionArgumentMissingException
* @throws UnknownOptionException
*
* @return array{0: list<array{0: non-empty-string, 1: ?non-empty-string}>, 1: list<non-empty-string>}
* @return array{0: list<array{0: string, 1: ?string}>, 1: list<string>}
*/
public function parse(array $argv, string $shortOptions, ?array $longOptions = null): array
{
if (empty($argv)) {
if ($argv === []) {
return [[], []];
}
@@ -111,8 +113,8 @@ final class Parser
}
/**
* @param list<array{0: non-empty-string, 1: ?non-empty-string}> $options
* @param list<string> $argv
* @param list<array{0: string, 1: ?string}> $options
* @param list<string> $argv
*
* @throws RequiredOptionArgumentMissingException
*/
@@ -125,7 +127,7 @@ final class Parser
$optionArgument = null;
if ($argument[$i] === ':' || ($spec = strstr($shortOptions, $option)) === false) {
throw new UnknownOptionException('-' . $option);
throw new UnknownOptionException('-' . $option, []);
}
if (strlen($spec) > 1 && $spec[1] === ':') {
@@ -142,8 +144,6 @@ final class Parser
throw new RequiredOptionArgumentMissingException('-' . $option);
}
assert(is_string($optionArgument));
next($argv);
}
}
@@ -153,9 +153,9 @@ final class Parser
}
/**
* @param list<string> $longOptions
* @param list<array{0: non-empty-string, 1: ?non-empty-string}> $options
* @param list<string> $argv
* @param list<string> $longOptions
* @param list<array{0: string, 1: ?string}> $options
* @param list<string> $argv
*
* @throws AmbiguousOptionException
* @throws OptionDoesNotAllowArgumentException
@@ -170,12 +170,19 @@ final class Parser
$optionArgument = null;
if (count($list) > 1) {
/** @phpstan-ignore offsetAccess.notFound */
$optionArgument = $list[1];
}
$optionLength = strlen($option);
$similarOptions = [];
foreach ($longOptions as $i => $longOption) {
$similarOptions[] = [
levenshtein($longOption, $option),
'--' . rtrim($longOption, '='),
];
$opt_start = substr($longOption, 0, $optionLength);
if ($opt_start !== $option) {
@@ -184,12 +191,25 @@ final class Parser
$opt_rest = substr($longOption, $optionLength);
if ($opt_rest !== '' && $i + 1 < $count && $option[0] !== '=' && str_starts_with($longOptions[$i + 1], $option)) {
throw new AmbiguousOptionException('--' . $option);
if ($opt_rest !== '' &&
$i + 1 < $count &&
$option[0] !== '=' &&
/** @phpstan-ignore offsetAccess.notFound */
str_starts_with($longOptions[$i + 1], $option)
) {
$candidates = [];
foreach ($longOptions as $aLongOption) {
if (str_starts_with($aLongOption, $option)) {
$candidates[] = '--' . rtrim($aLongOption, '=');
}
}
throw new AmbiguousOptionException('--' . $option, $candidates);
}
if (str_ends_with($longOption, '=')) {
if (!str_ends_with($longOption, '==') && !strlen((string) $optionArgument)) {
if (!str_ends_with($longOption, '==') && (string) $optionArgument === '') {
if (false === $optionArgument = current($argv)) {
throw new RequiredOptionArgumentMissingException('--' . $option);
}
@@ -206,6 +226,27 @@ final class Parser
return;
}
throw new UnknownOptionException('--' . $option);
throw new UnknownOptionException('--' . $option, $this->formatSimilarOptions($similarOptions));
}
/**
* @param list<array{int, string}> $similarOptions
*
* @return array<string>
*/
private function formatSimilarOptions(array $similarOptions): array
{
usort($similarOptions, static function (array $a, array $b)
{
return $a[0] <=> $b[0];
});
$similarFormatted = [];
foreach (array_slice($similarOptions, 0, 5) as [$distance, $label]) {
$similarFormatted[] = $label;
}
return $similarFormatted;
}
}
@@ -9,17 +9,22 @@
*/
namespace SebastianBergmann\CliParser;
use function implode;
use function sprintf;
use RuntimeException;
final class AmbiguousOptionException extends RuntimeException implements Exception
{
public function __construct(string $option)
/**
* @param array<string> $candiates
*/
public function __construct(string $option, array $candiates)
{
parent::__construct(
sprintf(
'Option "%s" is ambiguous',
'Option "%s" is ambiguous. Similar options are: %s',
$option,
implode(', ', $candiates),
),
);
}
@@ -9,18 +9,30 @@
*/
namespace SebastianBergmann\CliParser;
use function implode;
use function sprintf;
use RuntimeException;
final class UnknownOptionException extends RuntimeException implements Exception
{
public function __construct(string $option)
/**
* @param array<string> $similarOptions
*/
public function __construct(string $option, array $similarOptions)
{
parent::__construct(
sprintf(
'Unknown option "%s"',
$option,
),
$message = sprintf(
'Unknown option "%s"',
$option,
);
if ($similarOptions !== []) {
$message = sprintf(
'Unknown option "%s". Most similar options are %s',
$option,
implode(', ', $similarOptions),
);
}
parent::__construct($message);
}
}
@@ -1,59 +0,0 @@
# Change Log
All notable changes to `sebastianbergmann/code-unit-reverse-lookup` are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
## [4.0.1] - 2024-07-03
### Changed
* This project now uses PHPStan instead of Psalm for static analysis
## [4.0.0] - 2024-02-02
### Removed
* This component is no longer supported on PHP 8.1
## [3.0.0] - 2023-02-03
### Removed
* This component is no longer supported on PHP 7.3, PHP 7.4, and PHP 8.0
## [2.0.3] - 2020-09-28
### Changed
* Changed PHP version constraint in `composer.json` from `^7.3 || ^8.0` to `>=7.3`
## [2.0.2] - 2020-06-26
### Added
* This component is now supported on PHP 8
## [2.0.1] - 2020-06-15
### Changed
* Tests etc. are now ignored for archive exports
## 2.0.0 - 2020-02-07
### Removed
* This component is no longer supported on PHP 5.6, PHP 7.0, PHP 7.1, and PHP 7.2
## 1.0.0 - 2016-02-13
### Added
* Initial release
[4.0.1]: https://github.com/sebastianbergmann/code-unit-reverse-lookup/compare/4.0.0...4.0.1
[4.0.0]: https://github.com/sebastianbergmann/code-unit-reverse-lookup/compare/3.0...4.0.0
[3.0.0]: https://github.com/sebastianbergmann/code-unit-reverse-lookup/compare/2.0.3...3.0.0
[2.0.3]: https://github.com/sebastianbergmann/code-unit-reverse-lookup/compare/2.0.2...2.0.3
[2.0.2]: https://github.com/sebastianbergmann/code-unit-reverse-lookup/compare/2.0.1...2.0.2
[2.0.1]: https://github.com/sebastianbergmann/code-unit-reverse-lookup/compare/2.0.0...2.0.1
[2.0.0]: https://github.com/sebastianbergmann/code-unit-reverse-lookup/compare/1.0.0...2.0.0
-29
View File
@@ -1,29 +0,0 @@
BSD 3-Clause License
Copyright (c) 2016-2024, Sebastian Bergmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-21
View File
@@ -1,21 +0,0 @@
[![Latest Stable Version](https://poser.pugx.org/sebastian/code-unit-reverse-lookup/v/stable.png)](https://packagist.org/packages/sebastian/code-unit-reverse-lookup)
[![CI Status](https://github.com/sebastianbergmann/code-unit-reverse-lookup/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/code-unit-reverse-lookup/actions)
[![codecov](https://codecov.io/gh/sebastianbergmann/code-unit-reverse-lookup/branch/main/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/code-unit-reverse-lookup)
# sebastian/code-unit-reverse-lookup
Looks up which function or method a line of code belongs to.
## Installation
You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):
```
composer require sebastian/code-unit-reverse-lookup
```
If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:
```
composer require --dev sebastian/code-unit-reverse-lookup
```
@@ -1,30 +0,0 @@
# Security Policy
If you believe you have found a security vulnerability in the library that is developed in this repository, please report it to us through coordinated disclosure.
**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.**
Instead, please email `[email protected]`.
Please include as much of the information listed below as you can to help us better understand and resolve the issue:
* The type of issue
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
## Web Context
The library that is developed in this repository was either extracted from [PHPUnit](https://github.com/sebastianbergmann/phpunit) or developed specifically as a dependency for PHPUnit.
The library is developed with a focus on development environments and the command-line. No specific testing or hardening with regard to using the library in an HTTP or web context or with untrusted input data is performed. The library might also contain functionality that intentionally exposes internal application data for debugging purposes.
If the library is used in a web application, the application developer is responsible for filtering inputs or escaping outputs as necessary and for verifying that the used functionality is safe for use within the intended context.
Vulnerabilities specific to the use outside a development context will be fixed as applicable, provided that the fix does not have an averse effect on the primary use case for development purposes.
@@ -1,40 +0,0 @@
{
"name": "sebastian/code-unit-reverse-lookup",
"description": "Looks up which function or method a line of code belongs to",
"homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/",
"license": "BSD-3-Clause",
"authors": [
{
"name": "Sebastian Bergmann",
"email": "[email protected]"
}
],
"support": {
"issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues",
"security": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/security/policy"
},
"config": {
"platform": {
"php": "8.2.0"
},
"optimize-autoloader": true,
"sort-packages": true
},
"prefer-stable": true,
"require": {
"php": ">=8.2"
},
"require-dev": {
"phpunit/phpunit": "^11.0"
},
"autoload": {
"classmap": [
"src/"
]
},
"extra": {
"branch-alias": {
"dev-main": "4.0-dev"
}
}
}
@@ -1,132 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit-reverse-lookup.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnitReverseLookup;
use function array_merge;
use function assert;
use function class_exists;
use function function_exists;
use function get_declared_classes;
use function get_declared_traits;
use function get_defined_functions;
use function is_array;
use function is_int;
use function is_string;
use function range;
use function trait_exists;
use ReflectionClass;
use ReflectionFunction;
use ReflectionMethod;
final class Wizard
{
/**
* @var array<string, array<int, string>>
*/
private array $lookupTable = [];
/**
* @var array<class-string, true>
*/
private array $processedClasses = [];
/**
* @var array<string, true>
*/
private array $processedFunctions = [];
public function lookup(string $filename, int $lineNumber): string
{
if (!isset($this->lookupTable[$filename][$lineNumber])) {
$this->updateLookupTable();
}
if (isset($this->lookupTable[$filename][$lineNumber])) {
return $this->lookupTable[$filename][$lineNumber];
}
return $filename . ':' . $lineNumber;
}
private function updateLookupTable(): void
{
$this->processClassesAndTraits();
$this->processFunctions();
}
private function processClassesAndTraits(): void
{
$classes = get_declared_classes();
$traits = get_declared_traits();
assert(is_array($traits));
foreach (array_merge($classes, $traits) as $classOrTrait) {
assert(class_exists($classOrTrait) || trait_exists($classOrTrait));
if (isset($this->processedClasses[$classOrTrait])) {
continue;
}
foreach ((new ReflectionClass($classOrTrait))->getMethods() as $method) {
$this->processFunctionOrMethod($method);
}
$this->processedClasses[$classOrTrait] = true;
}
}
private function processFunctions(): void
{
foreach (get_defined_functions()['user'] as $function) {
assert(function_exists($function));
if (isset($this->processedFunctions[$function])) {
continue;
}
$this->processFunctionOrMethod(new ReflectionFunction($function));
$this->processedFunctions[$function] = true;
}
}
private function processFunctionOrMethod(ReflectionFunction|ReflectionMethod $functionOrMethod): void
{
if ($functionOrMethod->isInternal()) {
return;
}
$name = $functionOrMethod->getName();
if ($functionOrMethod instanceof ReflectionMethod) {
$name = $functionOrMethod->getDeclaringClass()->getName() . '::' . $name;
}
$fileName = $functionOrMethod->getFileName();
assert(is_string($fileName));
if (!isset($this->lookupTable[$fileName])) {
$this->lookupTable[$fileName] = [];
}
$startLine = $functionOrMethod->getStartLine();
$endLine = $functionOrMethod->getEndLine();
assert(is_int($startLine));
assert(is_int($endLine));
assert($endLine >= $startLine);
foreach (range($startLine, $endLine) as $line) {
$this->lookupTable[$fileName][$line] = $name;
}
}
}
-106
View File
@@ -1,106 +0,0 @@
# ChangeLog
All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
## [3.0.3] - 2025-03-19
### Fixed
* [#9](https://github.com/sebastianbergmann/code-unit/issues/9): `Mapper::stringToCodeUnits('Foo::bar')` does not find method `Foo::bar` when a function named `\bar` is defined
## [3.0.2] - 2024-12-12
### Fixed
* [#8](https://github.com/sebastianbergmann/code-unit/issues/8): `Mapper::stringToCodeUnits()` does not consider "inheritance" between traits
## [3.0.1] - 2024-07-03
### Changed
* This project now uses PHPStan instead of Psalm for static analysis
## [3.0.0] - 2024-02-02
### Removed
* This component is no longer supported on PHP 8.1
## [2.0.0] - 2023-02-03
### Added
* Added `SebastianBergmann\CodeUnit\FileUnit` value object that represents a sourcecode file
### Removed
* `SebastianBergmann\CodeUnit\CodeUnitCollection::fromArray()` has been removed
* `SebastianBergmann\CodeUnit\Mapper::stringToCodeUnits()` no longer supports `ClassName<*>`
* This component is no longer supported on PHP 7.3, PHP 7.4, and PHP 8.0
## [1.0.8] - 2020-10-26
### Fixed
* `SebastianBergmann\CodeUnit\Exception` now correctly extends `\Throwable`
## [1.0.7] - 2020-10-02
### Fixed
* `SebastianBergmann\CodeUnit\Mapper::stringToCodeUnits()` no longer attempts to create `CodeUnit` objects for code units that are not declared in userland
## [1.0.6] - 2020-09-28
### Changed
* Changed PHP version constraint in `composer.json` from `^7.3 || ^8.0` to `>=7.3`
## [1.0.5] - 2020-06-26
### Fixed
* [#3](https://github.com/sebastianbergmann/code-unit/issues/3): Regression in 1.0.4
## [1.0.4] - 2020-06-26
### Added
* This component is now supported on PHP 8
## [1.0.3] - 2020-06-15
### Changed
* Tests etc. are now ignored for archive exports
## [1.0.2] - 2020-04-30
### Fixed
* `Mapper::stringToCodeUnits()` raised the wrong exception for `Class::method` when a class named `Class` exists but does not have a method named `method`
## [1.0.1] - 2020-04-27
### Fixed
* [#2](https://github.com/sebastianbergmann/code-unit/issues/2): `Mapper::stringToCodeUnits()` breaks when `ClassName<extended>` is used for class that extends built-in class
## [1.0.0] - 2020-03-30
* Initial release
[3.0.3]: https://github.com/sebastianbergmann/code-unit/compare/3.0.2...3.0.3
[3.0.2]: https://github.com/sebastianbergmann/code-unit/compare/3.0.1...3.0.2
[3.0.1]: https://github.com/sebastianbergmann/code-unit/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/sebastianbergmann/code-unit/compare/2.0...3.0.0
[2.0.0]: https://github.com/sebastianbergmann/code-unit/compare/1.0.8...2.0.0
[1.0.8]: https://github.com/sebastianbergmann/code-unit/compare/1.0.7...1.0.8
[1.0.7]: https://github.com/sebastianbergmann/code-unit/compare/1.0.6...1.0.7
[1.0.6]: https://github.com/sebastianbergmann/code-unit/compare/1.0.5...1.0.6
[1.0.5]: https://github.com/sebastianbergmann/code-unit/compare/1.0.4...1.0.5
[1.0.4]: https://github.com/sebastianbergmann/code-unit/compare/1.0.3...1.0.4
[1.0.3]: https://github.com/sebastianbergmann/code-unit/compare/1.0.2...1.0.3
[1.0.2]: https://github.com/sebastianbergmann/code-unit/compare/1.0.1...1.0.2
[1.0.1]: https://github.com/sebastianbergmann/code-unit/compare/1.0.0...1.0.1
[1.0.0]: https://github.com/sebastianbergmann/code-unit/compare/530c3900e5db9bcb8516da545bef0d62536cedaa...1.0.0
-29
View File
@@ -1,29 +0,0 @@
BSD 3-Clause License
Copyright (c) 2020-2025, Sebastian Bergmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-24
View File
@@ -1,24 +0,0 @@
[![No Maintenance Intended](https://unmaintained.tech/badge.svg)](https://unmaintained.tech/)
[![Latest Stable Version](https://poser.pugx.org/sebastian/code-unit/v)](https://packagist.org/packages/sebastian/code-unit)
[![CI Status](https://github.com/sebastianbergmann/code-unit/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/code-unit/actions)
[![codecov](https://codecov.io/gh/sebastianbergmann/code-unit/branch/main/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/code-unit)
# sebastian/code-unit
Collection of value objects that represent the PHP code units.
## Installation
You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):
```
composer require sebastian/code-unit
```
If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:
```
composer require --dev sebastian/code-unit
```
Please note that this is now a [low maintenance project](https://github.com/sebastianbergmann/code-unit/blob/main/.github/CONTRIBUTING.md#low-maintenance-project).
-30
View File
@@ -1,30 +0,0 @@
# Security Policy
If you believe you have found a security vulnerability in the library that is developed in this repository, please report it to us through coordinated disclosure.
**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.**
Instead, please email `[email protected]`.
Please include as much of the information listed below as you can to help us better understand and resolve the issue:
* The type of issue
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
## Web Context
The library that is developed in this repository was either extracted from [PHPUnit](https://github.com/sebastianbergmann/phpunit) or developed specifically as a dependency for PHPUnit.
The library is developed with a focus on development environments and the command-line. No specific testing or hardening with regard to using the library in an HTTP or web context or with untrusted input data is performed. The library might also contain functionality that intentionally exposes internal application data for debugging purposes.
If the library is used in a web application, the application developer is responsible for filtering inputs or escaping outputs as necessary and for verifying that the used functionality is safe for use within the intended context.
Vulnerabilities specific to the use outside a development context will be fixed as applicable, provided that the fix does not have an averse effect on the primary use case for development purposes.
-52
View File
@@ -1,52 +0,0 @@
{
"name": "sebastian/code-unit",
"description": "Collection of value objects that represent the PHP code units",
"type": "library",
"homepage": "https://github.com/sebastianbergmann/code-unit",
"license": "BSD-3-Clause",
"authors": [
{
"name": "Sebastian Bergmann",
"email": "[email protected]",
"role": "lead"
}
],
"support": {
"issues": "https://github.com/sebastianbergmann/code-unit/issues",
"security": "https://github.com/sebastianbergmann/code-unit/security/policy"
},
"prefer-stable": true,
"require": {
"php": ">=8.2"
},
"require-dev": {
"phpunit/phpunit": "^11.5"
},
"config": {
"platform": {
"php": "8.2.0"
},
"optimize-autoloader": true,
"sort-packages": true
},
"autoload": {
"classmap": [
"src/"
]
},
"autoload-dev": {
"classmap": [
"tests/_fixture"
],
"files": [
"tests/_fixture/file_with_multiple_code_units.php",
"tests/_fixture/function.php",
"tests/_fixture/issue_9.php"
]
},
"extra": {
"branch-alias": {
"dev-main": "3.0-dev"
}
}
}
-21
View File
@@ -1,21 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
/**
* @immutable
*/
final readonly class ClassMethodUnit extends CodeUnit
{
public function isClassMethod(): bool
{
return true;
}
}
-21
View File
@@ -1,21 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
/**
* @immutable
*/
final readonly class ClassUnit extends CodeUnit
{
public function isClass(): bool
{
return true;
}
}
-528
View File
@@ -1,528 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
use function assert;
use function count;
use function file;
use function file_exists;
use function is_readable;
use function range;
use function sprintf;
use ReflectionClass;
use ReflectionFunction;
use ReflectionMethod;
/**
* @immutable
*/
abstract readonly class CodeUnit
{
/**
* @var non-empty-string
*/
private string $name;
/**
* @var non-empty-string
*/
private string $sourceFileName;
/**
* @var list<int>
*/
private array $sourceLines;
/**
* @param class-string $className
*
* @throws InvalidCodeUnitException
* @throws ReflectionException
*/
public static function forClass(string $className): ClassUnit
{
self::ensureUserDefinedClass($className);
$reflector = new ReflectionClass($className);
return new ClassUnit(
$className,
// @phpstan-ignore argument.type
$reflector->getFileName(),
range(
// @phpstan-ignore argument.type
$reflector->getStartLine(),
// @phpstan-ignore argument.type
$reflector->getEndLine(),
),
);
}
/**
* @param class-string $className
*
* @throws InvalidCodeUnitException
* @throws ReflectionException
*/
public static function forClassMethod(string $className, string $methodName): ClassMethodUnit
{
self::ensureUserDefinedClass($className);
$reflector = self::reflectorForClassMethod($className, $methodName);
return new ClassMethodUnit(
$className . '::' . $methodName,
// @phpstan-ignore argument.type
$reflector->getFileName(),
range(
// @phpstan-ignore argument.type
$reflector->getStartLine(),
// @phpstan-ignore argument.type
$reflector->getEndLine(),
),
);
}
/**
* @param non-empty-string $path
*
* @throws InvalidCodeUnitException
*/
public static function forFileWithAbsolutePath(string $path): FileUnit
{
self::ensureFileExistsAndIsReadable($path);
$lines = file($path);
assert($lines !== false);
return new FileUnit(
$path,
$path,
range(
1,
count($lines),
),
);
}
/**
* @param class-string $interfaceName
*
* @throws InvalidCodeUnitException
* @throws ReflectionException
*/
public static function forInterface(string $interfaceName): InterfaceUnit
{
self::ensureUserDefinedInterface($interfaceName);
$reflector = new ReflectionClass($interfaceName);
return new InterfaceUnit(
$interfaceName,
// @phpstan-ignore argument.type
$reflector->getFileName(),
range(
// @phpstan-ignore argument.type
$reflector->getStartLine(),
// @phpstan-ignore argument.type
$reflector->getEndLine(),
),
);
}
/**
* @param class-string $interfaceName
*
* @throws InvalidCodeUnitException
* @throws ReflectionException
*/
public static function forInterfaceMethod(string $interfaceName, string $methodName): InterfaceMethodUnit
{
self::ensureUserDefinedInterface($interfaceName);
$reflector = self::reflectorForClassMethod($interfaceName, $methodName);
return new InterfaceMethodUnit(
$interfaceName . '::' . $methodName,
// @phpstan-ignore argument.type
$reflector->getFileName(),
range(
// @phpstan-ignore argument.type
$reflector->getStartLine(),
// @phpstan-ignore argument.type
$reflector->getEndLine(),
),
);
}
/**
* @param class-string $traitName
*
* @throws InvalidCodeUnitException
* @throws ReflectionException
*/
public static function forTrait(string $traitName): TraitUnit
{
self::ensureUserDefinedTrait($traitName);
$reflector = new ReflectionClass($traitName);
return new TraitUnit(
$traitName,
// @phpstan-ignore argument.type
$reflector->getFileName(),
range(
// @phpstan-ignore argument.type
$reflector->getStartLine(),
// @phpstan-ignore argument.type
$reflector->getEndLine(),
),
);
}
/**
* @param class-string $traitName
*
* @throws InvalidCodeUnitException
* @throws ReflectionException
*/
public static function forTraitMethod(string $traitName, string $methodName): TraitMethodUnit
{
self::ensureUserDefinedTrait($traitName);
$reflector = self::reflectorForClassMethod($traitName, $methodName);
return new TraitMethodUnit(
$traitName . '::' . $methodName,
// @phpstan-ignore argument.type
$reflector->getFileName(),
range(
// @phpstan-ignore argument.type
$reflector->getStartLine(),
// @phpstan-ignore argument.type
$reflector->getEndLine(),
),
);
}
/**
* @param callable-string $functionName
*
* @throws InvalidCodeUnitException
* @throws ReflectionException
*/
public static function forFunction(string $functionName): FunctionUnit
{
$reflector = self::reflectorForFunction($functionName);
if (!$reflector->isUserDefined()) {
throw new InvalidCodeUnitException(
sprintf(
'"%s" is not a user-defined function',
$functionName,
),
);
}
return new FunctionUnit(
// @phpstan-ignore argument.type
$functionName,
// @phpstan-ignore argument.type
$reflector->getFileName(),
range(
// @phpstan-ignore argument.type
$reflector->getStartLine(),
// @phpstan-ignore argument.type
$reflector->getEndLine(),
),
);
}
/**
* @param non-empty-string $name
* @param non-empty-string $sourceFileName
* @param list<int> $sourceLines
*/
private function __construct(string $name, string $sourceFileName, array $sourceLines)
{
$this->name = $name;
$this->sourceFileName = $sourceFileName;
$this->sourceLines = $sourceLines;
}
/**
* @return non-empty-string
*/
public function name(): string
{
return $this->name;
}
/**
* @return non-empty-string
*/
public function sourceFileName(): string
{
return $this->sourceFileName;
}
/**
* @return list<int>
*/
public function sourceLines(): array
{
return $this->sourceLines;
}
/**
* @phpstan-assert-if-true ClassUnit $this
*/
public function isClass(): bool
{
return false;
}
/**
* @phpstan-assert-if-true ClassMethodUnit $this
*/
public function isClassMethod(): bool
{
return false;
}
/**
* @phpstan-assert-if-true InterfaceUnit $this
*/
public function isInterface(): bool
{
return false;
}
/**
* @phpstan-assert-if-true InterfaceMethodUnit $this
*/
public function isInterfaceMethod(): bool
{
return false;
}
/**
* @phpstan-assert-if-true TraitUnit $this
*/
public function isTrait(): bool
{
return false;
}
/**
* @phpstan-assert-if-true TraitMethodUnit $this
*/
public function isTraitMethod(): bool
{
return false;
}
/**
* @phpstan-assert-if-true FunctionUnit $this
*/
public function isFunction(): bool
{
return false;
}
/**
* @phpstan-assert-if-true FileUnit $this
*/
public function isFile(): bool
{
return false;
}
/**
* @param non-empty-string $path
*
* @throws InvalidCodeUnitException
*/
private static function ensureFileExistsAndIsReadable(string $path): void
{
if (!(file_exists($path) && is_readable($path))) {
throw new InvalidCodeUnitException(
sprintf(
'File "%s" does not exist or is not readable',
$path,
),
);
}
}
/**
* @param class-string $className
*
* @throws InvalidCodeUnitException
*/
private static function ensureUserDefinedClass(string $className): void
{
try {
$reflector = new ReflectionClass($className);
if ($reflector->isInterface()) {
throw new InvalidCodeUnitException(
sprintf(
'"%s" is an interface and not a class',
$className,
),
);
}
if ($reflector->isTrait()) {
throw new InvalidCodeUnitException(
sprintf(
'"%s" is a trait and not a class',
$className,
),
);
}
if (!$reflector->isUserDefined()) {
throw new InvalidCodeUnitException(
sprintf(
'"%s" is not a user-defined class',
$className,
),
);
}
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
throw new ReflectionException(
$e->getMessage(),
$e->getCode(),
$e,
);
}
// @codeCoverageIgnoreEnd
}
/**
* @param class-string $interfaceName
*
* @throws InvalidCodeUnitException
*/
private static function ensureUserDefinedInterface(string $interfaceName): void
{
try {
$reflector = new ReflectionClass($interfaceName);
if (!$reflector->isInterface()) {
throw new InvalidCodeUnitException(
sprintf(
'"%s" is not an interface',
$interfaceName,
),
);
}
if (!$reflector->isUserDefined()) {
throw new InvalidCodeUnitException(
sprintf(
'"%s" is not a user-defined interface',
$interfaceName,
),
);
}
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
throw new ReflectionException(
$e->getMessage(),
$e->getCode(),
$e,
);
}
// @codeCoverageIgnoreEnd
}
/**
* @param class-string $traitName
*
* @throws InvalidCodeUnitException
*/
private static function ensureUserDefinedTrait(string $traitName): void
{
try {
$reflector = new ReflectionClass($traitName);
if (!$reflector->isTrait()) {
throw new InvalidCodeUnitException(
sprintf(
'"%s" is not a trait',
$traitName,
),
);
}
// @codeCoverageIgnoreStart
if (!$reflector->isUserDefined()) {
throw new InvalidCodeUnitException(
sprintf(
'"%s" is not a user-defined trait',
$traitName,
),
);
}
} catch (\ReflectionException $e) {
throw new ReflectionException(
$e->getMessage(),
$e->getCode(),
$e,
);
}
// @codeCoverageIgnoreEnd
}
/**
* @param class-string $className
*
* @throws ReflectionException
*/
private static function reflectorForClassMethod(string $className, string $methodName): ReflectionMethod
{
try {
return new ReflectionMethod($className, $methodName);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
throw new ReflectionException(
$e->getMessage(),
$e->getCode(),
$e,
);
}
// @codeCoverageIgnoreEnd
}
/**
* @param callable-string $functionName
*
* @throws ReflectionException
*/
private static function reflectorForFunction(string $functionName): ReflectionFunction
{
try {
return new ReflectionFunction($functionName);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
throw new ReflectionException(
$e->getMessage(),
$e->getCode(),
$e,
);
}
// @codeCoverageIgnoreEnd
}
}
@@ -1,75 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
use function array_merge;
use function count;
use Countable;
use IteratorAggregate;
/**
* @template-implements IteratorAggregate<int, CodeUnit>
*
* @immutable
*/
final readonly class CodeUnitCollection implements Countable, IteratorAggregate
{
/**
* @var list<CodeUnit>
*/
private array $codeUnits;
public static function fromList(CodeUnit ...$codeUnits): self
{
// @phpstan-ignore argument.type
return new self($codeUnits);
}
/**
* @param list<CodeUnit> $codeUnits
*/
private function __construct(array $codeUnits)
{
$this->codeUnits = $codeUnits;
}
/**
* @return list<CodeUnit>
*/
public function asArray(): array
{
return $this->codeUnits;
}
public function getIterator(): CodeUnitCollectionIterator
{
return new CodeUnitCollectionIterator($this);
}
public function count(): int
{
return count($this->codeUnits);
}
public function isEmpty(): bool
{
return $this->codeUnits === [];
}
public function mergeWith(self $other): self
{
return new self(
array_merge(
$this->asArray(),
$other->asArray(),
),
);
}
}
@@ -1,54 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
use Iterator;
/**
* @template-implements Iterator<int, CodeUnit>
*/
final class CodeUnitCollectionIterator implements Iterator
{
/**
* @var list<CodeUnit>
*/
private array $codeUnits;
private int $position = 0;
public function __construct(CodeUnitCollection $collection)
{
$this->codeUnits = $collection->asArray();
}
public function rewind(): void
{
$this->position = 0;
}
public function valid(): bool
{
return isset($this->codeUnits[$this->position]);
}
public function key(): int
{
return $this->position;
}
public function current(): CodeUnit
{
return $this->codeUnits[$this->position];
}
public function next(): void
{
$this->position++;
}
}
-21
View File
@@ -1,21 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
/**
* @immutable
*/
final readonly class FileUnit extends CodeUnit
{
public function isFile(): bool
{
return true;
}
}
-21
View File
@@ -1,21 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
/**
* @immutable
*/
final readonly class FunctionUnit extends CodeUnit
{
public function isFunction(): bool
{
return true;
}
}
@@ -1,21 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
/**
* @immutable
*/
final readonly class InterfaceMethodUnit extends CodeUnit
{
public function isInterfaceMethod(): bool
{
return true;
}
}
-21
View File
@@ -1,21 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
/**
* @immutable
*/
final readonly class InterfaceUnit extends CodeUnit
{
public function isInterface(): bool
{
return true;
}
}
-202
View File
@@ -1,202 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
use function array_keys;
use function array_merge;
use function array_unique;
use function array_values;
use function class_exists;
use function explode;
use function function_exists;
use function interface_exists;
use function ksort;
use function method_exists;
use function sort;
use function sprintf;
use function str_contains;
use function trait_exists;
use ReflectionClass;
use ReflectionFunction;
use ReflectionMethod;
final class Mapper
{
/**
* @return array<string,list<int>>
*/
public function codeUnitsToSourceLines(CodeUnitCollection $codeUnits): array
{
$result = [];
foreach ($codeUnits as $codeUnit) {
$sourceFileName = $codeUnit->sourceFileName();
if (!isset($result[$sourceFileName])) {
$result[$sourceFileName] = [];
}
$result[$sourceFileName] = array_merge($result[$sourceFileName], $codeUnit->sourceLines());
}
foreach (array_keys($result) as $sourceFileName) {
$result[$sourceFileName] = array_values(array_unique($result[$sourceFileName]));
sort($result[$sourceFileName]);
}
ksort($result);
return $result;
}
/**
* @throws InvalidCodeUnitException
* @throws ReflectionException
*/
public function stringToCodeUnits(string $unit): CodeUnitCollection
{
if (str_contains($unit, '::')) {
[$firstPart, $secondPart] = explode('::', $unit);
if ($this->isUserDefinedMethod($firstPart, $secondPart)) {
return CodeUnitCollection::fromList(CodeUnit::forClassMethod($firstPart, $secondPart));
}
if ($this->isUserDefinedFunction($secondPart)) {
return CodeUnitCollection::fromList(CodeUnit::forFunction($secondPart));
}
if ($this->isUserDefinedInterface($firstPart)) {
return CodeUnitCollection::fromList(CodeUnit::forInterfaceMethod($firstPart, $secondPart));
}
if ($this->isUserDefinedTrait($firstPart)) {
return CodeUnitCollection::fromList(CodeUnit::forTraitMethod($firstPart, $secondPart));
}
} else {
if ($this->isUserDefinedClass($unit)) {
return CodeUnitCollection::fromList(
...array_merge(
[CodeUnit::forClass($unit)],
$this->traits(new ReflectionClass($unit)),
),
);
}
if ($this->isUserDefinedInterface($unit)) {
return CodeUnitCollection::fromList(CodeUnit::forInterface($unit));
}
if ($this->isUserDefinedTrait($unit)) {
return CodeUnitCollection::fromList(CodeUnit::forTrait($unit));
}
if ($this->isUserDefinedFunction($unit)) {
return CodeUnitCollection::fromList(CodeUnit::forFunction($unit));
}
}
throw new InvalidCodeUnitException(
sprintf(
'"%s" is not a valid code unit',
$unit,
),
);
}
/**
* @phpstan-assert-if-true callable-string $functionName
*/
private function isUserDefinedFunction(string $functionName): bool
{
if (!function_exists($functionName)) {
return false;
}
return (new ReflectionFunction($functionName))->isUserDefined();
}
/**
* @phpstan-assert-if-true class-string $className
*/
private function isUserDefinedClass(string $className): bool
{
if (!class_exists($className)) {
return false;
}
return (new ReflectionClass($className))->isUserDefined();
}
/**
* @phpstan-assert-if-true interface-string $interfaceName
*/
private function isUserDefinedInterface(string $interfaceName): bool
{
if (!interface_exists($interfaceName)) {
return false;
}
return (new ReflectionClass($interfaceName))->isUserDefined();
}
/**
* @phpstan-assert-if-true trait-string $traitName
*/
private function isUserDefinedTrait(string $traitName): bool
{
if (!trait_exists($traitName)) {
return false;
}
return (new ReflectionClass($traitName))->isUserDefined();
}
/**
* @phpstan-assert-if-true class-string $className
*/
private function isUserDefinedMethod(string $className, string $methodName): bool
{
if (!class_exists($className)) {
return false;
}
if (!method_exists($className, $methodName)) {
return false;
}
return (new ReflectionMethod($className, $methodName))->isUserDefined();
}
/**
* @param ReflectionClass<object> $class
*
* @return list<TraitUnit>
*/
private function traits(ReflectionClass $class): array
{
$result = [];
foreach ($class->getTraits() as $trait) {
if (!$trait->isUserDefined()) {
// @codeCoverageIgnoreStart
continue;
// @codeCoverageIgnoreEnd
}
$result[] = CodeUnit::forTrait($trait->getName());
$result = array_merge($result, $this->traits($trait));
}
return $result;
}
}
-21
View File
@@ -1,21 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
/**
* @immutable
*/
final readonly class TraitMethodUnit extends CodeUnit
{
public function isTraitMethod(): bool
{
return true;
}
}
-21
View File
@@ -1,21 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
/**
* @immutable
*/
final readonly class TraitUnit extends CodeUnit
{
public function isTrait(): bool
{
return true;
}
}
@@ -1,16 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
use Throwable;
interface Exception extends Throwable
{
}
@@ -1,16 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
use RuntimeException;
final class InvalidCodeUnitException extends RuntimeException implements Exception
{
}
@@ -1,16 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
use RuntimeException;
final class NoTraitException extends RuntimeException implements Exception
{
}
@@ -1,16 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/code-unit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeUnit;
use RuntimeException;
final class ReflectionException extends RuntimeException implements Exception
{
}
+42
View File
@@ -2,6 +2,42 @@
All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
## [7.1.3] - 2025-08-20
### Changed
* [#130](https://github.com/sebastianbergmann/comparator/pull/130): Provide a diff when `ClosureComparator` fails
## [7.1.2] - 2025-08-10
### Fixed
* `SebastianBergmann\Comparator\Comparator` should not have been marked as private implementation detail of this library
## [7.1.1] - 2025-08-10
### Changed
* Do not use `SplObjectStorage` methods that will be deprecated in PHP 8.5
## [7.1.0] - 2025-06-17
### Added
* [#127](https://github.com/sebastianbergmann/comparator/issues/127): Support for comparing `Closure` objects
## [7.0.1] - 2025-03-07
### Fixed
* [#122](https://github.com/sebastianbergmann/comparator/issues/122): `INF` is considered equal to `-INF`
## [7.0.0] - 2025-02-07
### Removed
* Removed support for PHP 8.2
## [6.3.2] - 2025-08-10
### Changed
@@ -216,6 +252,12 @@ All notable changes are documented in this file using the [Keep a CHANGELOG](htt
* Added `SebastianBergmann\Comparator\Factory::reset()` to unregister all non-default comparators
* Added support for `phpunit/phpunit-mock-objects` version `^5.0`
[7.1.3]: https://github.com/sebastianbergmann/comparator/compare/7.1.2...7.1.3
[7.1.2]: https://github.com/sebastianbergmann/comparator/compare/7.1.1...7.1.2
[7.1.1]: https://github.com/sebastianbergmann/comparator/compare/7.1.0...7.1.1
[7.1.0]: https://github.com/sebastianbergmann/comparator/compare/7.0.1...7.1.0
[7.0.1]: https://github.com/sebastianbergmann/comparator/compare/7.0.0...7.0.1
[7.0.0]: https://github.com/sebastianbergmann/comparator/compare/6.3...7.0.0
[6.3.2]: https://github.com/sebastianbergmann/comparator/compare/6.3.1...6.3.2
[6.3.1]: https://github.com/sebastianbergmann/comparator/compare/6.3.0...6.3.1
[6.3.0]: https://github.com/sebastianbergmann/comparator/compare/6.2.1...6.3.0
+6 -6
View File
@@ -28,9 +28,9 @@
},
"prefer-stable": true,
"require": {
"php": ">=8.2",
"sebastian/diff": "^6.0",
"sebastian/exporter": "^6.0",
"php": ">=8.3",
"sebastian/diff": "^7.0",
"sebastian/exporter": "^7.0",
"ext-dom": "*",
"ext-mbstring": "*"
},
@@ -38,11 +38,11 @@
"ext-bcmath": "For comparing BcMath\\Number objects"
},
"require-dev": {
"phpunit/phpunit": "^11.4"
"phpunit/phpunit": "^12.2"
},
"config": {
"platform": {
"php": "8.2.0"
"php": "8.3.0"
},
"optimize-autoloader": true,
"sort-packages": true
@@ -59,7 +59,7 @@
},
"extra": {
"branch-alias": {
"dev-main": "6.3-dev"
"dev-main": "7.1-dev"
}
}
}
+9 -5
View File
@@ -19,9 +19,9 @@ use function trim;
use SebastianBergmann\Exporter\Exporter;
/**
* Arrays are equal if they contain the same key-value pairs.
* The order of the keys does not matter.
* The types of key-value pairs do not matter.
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
class ArrayComparator extends Comparator
{
@@ -31,6 +31,10 @@ class ArrayComparator extends Comparator
}
/**
* Arrays are equal if they contain the same key-value pairs.
* The order of the keys does not matter.
* The types of key-value pairs do not matter.
*
* @param array<mixed> $processed
*
* @throws ComparisonFailure
@@ -87,13 +91,13 @@ class ArrayComparator extends Comparator
$expectedAsString .= sprintf(
" %s => %s\n",
$exporter->export($key),
$e->getExpectedAsString() ? $this->indent($e->getExpectedAsString()) : $exporter->shortenedExport($e->getExpected()),
$e->getExpectedAsString() !== '' ? $this->indent($e->getExpectedAsString()) : $exporter->shortenedExport($e->getExpected()),
);
$actualAsString .= sprintf(
" %s => %s\n",
$exporter->export($key),
$e->getActualAsString() ? $this->indent($e->getActualAsString()) : $exporter->shortenedExport($e->getActual()),
$e->getActualAsString() !== '' ? $this->indent($e->getActualAsString()) : $exporter->shortenedExport($e->getActual()),
);
$equal = false;
+3
View File
@@ -9,6 +9,9 @@
*/
namespace SebastianBergmann\Comparator;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*/
abstract class Comparator
{
private Factory $factory;
+4 -1
View File
@@ -13,6 +13,9 @@ use RuntimeException;
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*/
final class ComparisonFailure extends RuntimeException
{
private mixed $expected;
@@ -52,7 +55,7 @@ final class ComparisonFailure extends RuntimeException
public function getDiff(): string
{
if (!$this->actualAsString && !$this->expectedAsString) {
if ($this->actualAsString === '' && $this->expectedAsString === '') {
return '';
}
+21 -28
View File
@@ -16,6 +16,11 @@ use DOMDocument;
use DOMNode;
use ValueError;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
final class DOMNodeComparator extends ObjectComparator
{
public function accepts(mixed $expected, mixed $actual): bool
@@ -33,8 +38,8 @@ final class DOMNodeComparator extends ObjectComparator
assert($expected instanceof DOMNode);
assert($actual instanceof DOMNode);
$expectedAsString = $this->nodeToText($expected, true, $ignoreCase);
$actualAsString = $this->nodeToText($actual, true, $ignoreCase);
$expectedAsString = $this->nodeToText($expected, $ignoreCase);
$actualAsString = $this->nodeToText($actual, $ignoreCase);
if ($expectedAsString !== $actualAsString) {
$type = $expected instanceof DOMDocument ? 'documents' : 'nodes';
@@ -50,42 +55,30 @@ final class DOMNodeComparator extends ObjectComparator
}
/**
* Returns the normalized, whitespace-cleaned, and indented textual
* representation of a DOMNode.
* Canonicalizes nodes, removes empty text nodes and merges adjacent text nodes,
* and optionally ignores case.
*
* @see https://github.com/sebastianbergmann/phpunit/pull/1236#issuecomment-41765023
*/
private function nodeToText(DOMNode $node, bool $canonicalize, bool $ignoreCase): string
private function nodeToText(DOMNode $node, bool $ignoreCase): string
{
if ($canonicalize) {
$document = new DOMDocument;
$document = new DOMDocument;
try {
$c14n = $node->C14N();
try {
$c14n = $node->C14N();
assert(!empty($c14n));
assert($c14n !== false && $c14n !== '');
@$document->loadXML($c14n);
} catch (ValueError) {
}
$node = $document;
@$document->loadXML($c14n);
// @codeCoverageIgnoreStart
} catch (ValueError) {
// @codeCoverageIgnoreEnd
}
if ($node instanceof DOMDocument) {
$document = $node;
} else {
$document = $node->ownerDocument;
}
assert($document instanceof DOMDocument);
$document->formatOutput = true;
$document->normalizeDocument();
if ($node instanceof DOMDocument) {
$text = $node->saveXML();
} else {
$text = $document->saveXML($node);
}
$text = $document->saveXML();
assert($text !== false);
@@ -18,6 +18,11 @@ use DateTime;
use DateTimeImmutable;
use DateTimeZone;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
final class DateTimeComparator extends ObjectComparator
{
public function accepts(mixed $expected, mixed $actual): bool
@@ -13,6 +13,11 @@ use function assert;
use function sprintf;
use UnitEnum;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
final class EnumerationComparator extends Comparator
{
public function accepts(mixed $expected, mixed $actual): bool
@@ -13,7 +13,9 @@ use function assert;
use Exception;
/**
* Compares Exception instances for equality.
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
final class ExceptionComparator extends ObjectComparator
{
+6
View File
@@ -14,6 +14,9 @@ use function array_unshift;
use function extension_loaded;
use function version_compare;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*/
final class Factory
{
private static ?Factory $instance = null;
@@ -56,7 +59,9 @@ final class Factory
}
}
// @codeCoverageIgnoreStart
throw new RuntimeException('No suitable Comparator implementation found');
// @codeCoverageIgnoreEnd
}
/**
@@ -95,6 +100,7 @@ final class Factory
private function registerDefaultComparators(): void
{
$this->registerDefaultComparator(new ClosureComparator);
$this->registerDefaultComparator(new MockObjectComparator);
$this->registerDefaultComparator(new DateTimeComparator);
$this->registerDefaultComparator(new DOMNodeComparator);
@@ -15,7 +15,9 @@ use function str_starts_with;
use PHPUnit\Framework\MockObject\Stub;
/**
* Compares PHPUnit\Framework\MockObject\MockObject instances for equality.
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
final class MockObjectComparator extends ObjectComparator
{
@@ -17,6 +17,11 @@ use function max;
use function number_format;
use BcMath\Number;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
final class NumberComparator extends ObjectComparator
{
public function accepts(mixed $expected, mixed $actual): bool
@@ -19,6 +19,11 @@ use function is_string;
use function sprintf;
use SebastianBergmann\Exporter\Exporter;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
final class NumericComparator extends ScalarComparator
{
public function accepts(mixed $expected, mixed $actual): bool
@@ -16,6 +16,11 @@ use function sprintf;
use function substr_replace;
use SebastianBergmann\Exporter\Exporter;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
class ObjectComparator extends ArrayComparator
{
public function accepts(mixed $expected, mixed $actual): bool
@@ -13,6 +13,11 @@ use function assert;
use function is_resource;
use SebastianBergmann\Exporter\Exporter;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
final class ResourceComparator extends Comparator
{
public function accepts(mixed $expected, mixed $actual): bool
@@ -30,6 +35,7 @@ final class ResourceComparator extends Comparator
$exporter = new Exporter;
/** @phpstan-ignore notEqual.notAllowed */
if ($actual != $expected) {
throw new ComparisonFailure(
$expected,
+12 -6
View File
@@ -9,6 +9,7 @@
*/
namespace SebastianBergmann\Comparator;
use function assert;
use function is_bool;
use function is_object;
use function is_scalar;
@@ -21,12 +22,14 @@ use function substr;
use SebastianBergmann\Exporter\Exporter;
/**
* Compares scalar or NULL values for equality.
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
class ScalarComparator extends Comparator
{
private const OVERLONG_THRESHOLD = 40;
private const KEEP_CONTEXT_CHARS = 25;
private const int OVERLONG_THRESHOLD = 40;
private const int KEEP_CONTEXT_CHARS = 25;
public function accepts(mixed $expected, mixed $actual): bool
{
@@ -74,6 +77,7 @@ class ScalarComparator extends Comparator
);
}
/** @phpstan-ignore notEqual.notAllowed */
if ($expectedToCompare != $actualToCompare) {
throw new ComparisonFailure(
$expected,
@@ -108,11 +112,13 @@ class ScalarComparator extends Comparator
private static function findCommonPrefix(string $string1, string $string2): string
{
for ($i = 0; $i < strlen($string1); $i++) {
if (!isset($string2[$i]) || $string1[$i] != $string2[$i]) {
if (!isset($string2[$i]) || $string1[$i] !== $string2[$i]) {
break;
}
}
assert(isset($i));
return substr($string1, 0, $i);
}
@@ -140,14 +146,14 @@ class ScalarComparator extends Comparator
$lastCharIndex1 = strlen($string1) - 1;
$lastCharIndex2 = strlen($string2) - 1;
if ($string1[$lastCharIndex1] != $string2[$lastCharIndex2]) {
if ($string1[$lastCharIndex1] !== $string2[$lastCharIndex2]) {
return '';
}
while (
$lastCharIndex1 > 0 &&
$lastCharIndex2 > 0 &&
$string1[$lastCharIndex1] == $string2[$lastCharIndex2]
$string1[$lastCharIndex1] === $string2[$lastCharIndex2]
) {
$lastCharIndex1--;
$lastCharIndex2--;
@@ -13,6 +13,11 @@ use function assert;
use SebastianBergmann\Exporter\Exporter;
use SplObjectStorage;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
final class SplObjectStorageComparator extends Comparator
{
public function accepts(mixed $expected, mixed $actual): bool
+6 -1
View File
@@ -13,6 +13,11 @@ use function gettype;
use function sprintf;
use SebastianBergmann\Exporter\Exporter;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*
* @internal This class is not covered by the backward compatibility promise for sebastian/comparator
*/
final class TypeComparator extends Comparator
{
public function accepts(mixed $expected, mixed $actual): bool
@@ -25,7 +30,7 @@ final class TypeComparator extends Comparator
*/
public function assertEquals(mixed $expected, mixed $actual, float $delta = 0.0, bool $canonicalize = false, bool $ignoreCase = false): void
{
if (gettype($expected) != gettype($actual)) {
if (gettype($expected) !== gettype($actual)) {
throw new ComparisonFailure(
$expected,
$actual,
@@ -11,6 +11,9 @@ namespace SebastianBergmann\Comparator;
use Throwable;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*/
interface Exception extends Throwable
{
}
@@ -9,6 +9,9 @@
*/
namespace SebastianBergmann\Comparator;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
*/
final class RuntimeException extends \RuntimeException implements Exception
{
}
+7
View File
@@ -2,6 +2,12 @@
All notable changes are documented in this file using the [Keep a CHANGELOG](https://keepachangelog.com/) principles.
## [5.0.0] - 2025-02-07
### Removed
* This component is no longer supported on PHP 8.2
## [4.0.1] - 2024-07-03
### Changed
@@ -72,6 +78,7 @@ All notable changes are documented in this file using the [Keep a CHANGELOG](htt
* Initial release
[5.0.0]: https://github.com/sebastianbergmann/complexity/compare/4.0...5.0.0
[4.0.1]: https://github.com/sebastianbergmann/complexity/compare/4.0.0...4.0.1
[4.0.0]: https://github.com/sebastianbergmann/complexity/compare/3.2...4.0.0
[3.2.0]: https://github.com/sebastianbergmann/complexity/compare/3.1.0...3.2.0
+1 -1
View File
@@ -1,6 +1,6 @@
BSD 3-Clause License
Copyright (c) 2020-2024, Sebastian Bergmann
Copyright (c) 2020-2025, Sebastian Bergmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
+1 -1
View File
@@ -1,4 +1,4 @@
[![Latest Stable Version](https://poser.pugx.org/sebastian/complexity/v/stable.png)](https://packagist.org/packages/sebastian/complexity)
[![Latest Stable Version](https://poser.pugx.org/sebastian/complexity/v)](https://packagist.org/packages/sebastian/complexity)
[![CI Status](https://github.com/sebastianbergmann/complexity/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/complexity/actions)
[![codecov](https://codecov.io/gh/sebastianbergmann/complexity/branch/main/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/complexity)
+4 -4
View File
@@ -17,15 +17,15 @@
},
"prefer-stable": true,
"require": {
"php": ">=8.2",
"php": ">=8.3",
"nikic/php-parser": "^5.0"
},
"require-dev": {
"phpunit/phpunit": "^11.0"
"phpunit/phpunit": "^12.0"
},
"config": {
"platform": {
"php": "8.2.0"
"php": "8.3.0"
},
"optimize-autoloader": true,
"sort-packages": true
@@ -37,7 +37,7 @@
},
"extra": {
"branch-alias": {
"dev-main": "4.0-dev"
"dev-main": "5.0-dev"
}
}
}
-1
View File
@@ -51,7 +51,6 @@ final class Calculator
assert($nodes !== null);
return $this->calculateForAbstractSyntaxTree($nodes);
// @codeCoverageIgnoreStart
} catch (Error $error) {
throw new RuntimeException(
@@ -32,7 +32,7 @@ final readonly class ComplexityCollection implements Countable, IteratorAggregat
public static function fromList(Complexity ...$items): self
{
return new self($items);
return new self(array_values($items));
}
/**
@@ -13,7 +13,6 @@ use function assert;
use function is_array;
use PhpParser\Node;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
@@ -111,7 +110,6 @@ final class ComplexityCalculatingVisitor extends NodeVisitorAbstract
}
assert(isset($parent->namespacedName));
assert($parent->namespacedName instanceof Name);
return $parent->namespacedName->toString() . '::' . $node->name->toString();
}
@@ -122,12 +120,7 @@ final class ComplexityCalculatingVisitor extends NodeVisitorAbstract
private function functionName(Function_ $node): string
{
assert(isset($node->namespacedName));
assert($node->namespacedName instanceof Name);
$functionName = $node->namespacedName->toString();
assert($functionName !== '');
return $functionName;
return $node->namespacedName->toString();
}
}
@@ -31,7 +31,7 @@ final class CyclomaticComplexityCalculatingVisitor extends NodeVisitorAbstract
*/
private int $cyclomaticComplexity = 1;
public function enterNode(Node $node): void
public function enterNode(Node $node): null
{
switch ($node::class) {
case BooleanAnd::class:
@@ -49,6 +49,8 @@ final class CyclomaticComplexityCalculatingVisitor extends NodeVisitorAbstract
case While_::class:
$this->cyclomaticComplexity++;
}
return null;
}
/**
+11 -4
View File
@@ -2,6 +2,12 @@
All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
## [7.0.0] - 2025-02-07
### Removed
* This component is no longer supported on PHP 8.3
## [6.0.2] - 2024-07-03
### Changed
@@ -21,7 +27,7 @@ All notable changes are documented in this file using the [Keep a CHANGELOG](htt
* `SebastianBergmann\Diff\Chunk::getStart()`, `SebastianBergmann\Diff\Chunk::getStartRange()`, `SebastianBergmann\Diff\Chunk::getEnd()`, `SebastianBergmann\Diff\Chunk::getEndRange()`, and `SebastianBergmann\Diff\Chunk::getLines()`
* `SebastianBergmann\Diff\Diff::getFrom()`, `SebastianBergmann\Diff\Diff::getTo()`, and `SebastianBergmann\Diff\Diff::getChunks()`
* `SebastianBergmann\Diff\Line::getContent()` and `SebastianBergmann\Diff\Diff::getType()`
* Removed support for PHP 8.1
* This component is no longer supported on PHP 8.1
## [5.1.1] - 2024-03-02
@@ -75,7 +81,7 @@ All notable changes are documented in this file using the [Keep a CHANGELOG](htt
### Removed
* Removed support for PHP 7.3, PHP 7.4, and PHP 8.0
* This component is no longer supported on PHP 7.3, PHP 7.4, and PHP 8.0
## [4.0.4] - 2020-10-26
@@ -105,7 +111,7 @@ All notable changes are documented in this file using the [Keep a CHANGELOG](htt
### Removed
* Removed support for PHP 7.1 and PHP 7.2
* This component is no longer supported on PHP 7.1 and PHP 7.2
## [3.0.2] - 2019-02-04
@@ -129,7 +135,7 @@ All notable changes are documented in this file using the [Keep a CHANGELOG](htt
### Removed
* Removed support for PHP 7.0
* This component is no longer supported on PHP 7.0
### Fixed
@@ -151,6 +157,7 @@ All notable changes are documented in this file using the [Keep a CHANGELOG](htt
* This component is no longer supported on PHP 5.6
[7.0.0]: https://github.com/sebastianbergmann/diff/compare/6.0...7.0.0
[6.0.2]: https://github.com/sebastianbergmann/diff/compare/6.0.1...6.0.2
[6.0.1]: https://github.com/sebastianbergmann/diff/compare/6.0.0...6.0.1
[6.0.0]: https://github.com/sebastianbergmann/diff/compare/5.1...6.0.0
+1 -1
View File
@@ -1,6 +1,6 @@
BSD 3-Clause License
Copyright (c) 2002-2024, Sebastian Bergmann
Copyright (c) 2002-2025, Sebastian Bergmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
+13 -67
View File
@@ -1,4 +1,4 @@
[![Latest Stable Version](https://poser.pugx.org/sebastian/diff/v/stable.png)](https://packagist.org/packages/sebastian/diff)
[![Latest Stable Version](https://poser.pugx.org/sebastian/diff/v)](https://packagist.org/packages/sebastian/diff)
[![CI Status](https://github.com/sebastianbergmann/diff/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/diff/actions)
[![codecov](https://codecov.io/gh/sebastianbergmann/diff/branch/main/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/diff)
@@ -27,14 +27,17 @@ composer require --dev sebastian/diff
The `Differ` class can be used to generate a textual representation of the difference between two strings:
```php
<?php
<?php declare(strict_types=1);
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
$differ = new Differ(new UnifiedDiffOutputBuilder);
$differ = new Differ;
print $differ->diff('foo', 'bar');
```
The code above yields the output below:
```diff
--- Original
+++ New
@@ -43,73 +46,16 @@ The code above yields the output below:
+bar
```
There are three output builders available in this package:
The `UnifiedDiffOutputBuilder` used in the example above generates output in "unified diff"
format and is used by PHPUnit, for example.
#### UnifiedDiffOutputBuilder
The `StrictUnifiedDiffOutputBuilder` generates output in "strict unified diff" format with
hunks, similar to `diff -u` and compatible with `patch` or `git apply`.
This is default builder, which generates the output close to udiff and is used by PHPUnit.
The `DiffOnlyOutputBuilder` generates output that only contains the lines that differ.
```php
<?php
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
$builder = new UnifiedDiffOutputBuilder(
"--- Original\n+++ New\n", // custom header
false // do not add line numbers to the diff
);
$differ = new Differ($builder);
print $differ->diff('foo', 'bar');
```
#### StrictUnifiedDiffOutputBuilder
Generates (strict) Unified diff's (unidiffs) with hunks,
similar to `diff -u` and compatible with `patch` and `git apply`.
```php
<?php
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder;
$builder = new StrictUnifiedDiffOutputBuilder([
'collapseRanges' => true, // ranges of length one are rendered with the trailing `,1`
'commonLineThreshold' => 6, // number of same lines before ending a new hunk and creating a new one (if needed)
'contextLines' => 3, // like `diff: -u, -U NUM, --unified[=NUM]`, for patch/git apply compatibility best to keep at least @ 3
'fromFile' => '',
'fromFileDate' => null,
'toFile' => '',
'toFileDate' => null,
]);
$differ = new Differ($builder);
print $differ->diff('foo', 'bar');
```
#### DiffOnlyOutputBuilder
Output only the lines that differ.
```php
<?php
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\DiffOnlyOutputBuilder;
$builder = new DiffOnlyOutputBuilder(
"--- Original\n+++ New\n"
);
$differ = new Differ($builder);
print $differ->diff('foo', 'bar');
```
#### DiffOutputBuilderInterface
You can pass any output builder to the `Differ` class as longs as it implements the `DiffOutputBuilderInterface`.
If none of these three output builders match your use case then you can implement
`DiffOutputBuilderInterface` to generate custom output.
#### Parsing diff
+5 -5
View File
@@ -21,17 +21,17 @@
"prefer-stable": true,
"config": {
"platform": {
"php": "8.2.0"
"php": "8.3.0"
},
"optimize-autoloader": true,
"sort-packages": true
},
"require": {
"php": ">=8.2"
"php": ">=8.3"
},
"require-dev": {
"phpunit/phpunit": "^11.0",
"symfony/process": "^4.2 || ^5"
"phpunit/phpunit": "^12.0",
"symfony/process": "^7.2"
},
"autoload": {
"classmap": [
@@ -45,7 +45,7 @@
},
"extra": {
"branch-alias": {
"dev-main": "6.0-dev"
"dev-main": "7.0-dev"
}
}
}
-6
View File
@@ -73,12 +73,6 @@ final class Chunk implements IteratorAggregate
*/
public function setLines(array $lines): void
{
foreach ($lines as $line) {
if (!$line instanceof Line) {
throw new InvalidArgumentException;
}
}
$this->lines = $lines;
}
+8 -8
View File
@@ -30,11 +30,11 @@ use SebastianBergmann\Diff\Output\DiffOutputBuilderInterface;
final class Differ
{
public const OLD = 0;
public const ADDED = 1;
public const REMOVED = 2;
public const DIFF_LINE_END_WARNING = 3;
public const NO_LINE_END_EOF_WARNING = 4;
public const int OLD = 0;
public const int ADDED = 1;
public const int REMOVED = 2;
public const int DIFF_LINE_END_WARNING = 3;
public const int NO_LINE_END_EOF_WARNING = 4;
private DiffOutputBuilderInterface $outputBuilder;
public function __construct(DiffOutputBuilderInterface $outputBuilder)
@@ -84,11 +84,11 @@ final class Differ
reset($to);
foreach ($common as $token) {
while (($fromToken = reset($from)) !== $token) {
while ((/* from-token */ reset($from)) !== $token) {
$diff[] = [array_shift($from), self::REMOVED];
}
while (($toToken = reset($to)) !== $token) {
while ((/* to-token */ reset($to)) !== $token) {
$diff[] = [array_shift($to), self::ADDED];
}
@@ -137,7 +137,7 @@ final class Differ
return new TimeEfficientLongestCommonSubsequenceCalculator;
}
private function calculateEstimatedFootprint(array $from, array $to): float|int
private function calculateEstimatedFootprint(array $from, array $to): int
{
$itemSize = PHP_INT_SIZE === 4 ? 76 : 144;
+3 -3
View File
@@ -11,9 +11,9 @@ namespace SebastianBergmann\Diff;
final class Line
{
public const ADDED = 1;
public const REMOVED = 2;
public const UNCHANGED = 3;
public const int ADDED = 1;
public const int REMOVED = 2;
public const int UNCHANGED = 3;
private int $type;
private string $content;
@@ -15,7 +15,6 @@ use function array_reverse;
use function array_slice;
use function count;
use function in_array;
use function max;
final class MemoryEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
{
@@ -16,6 +16,8 @@ abstract class AbstractChunkOutputBuilder implements DiffOutputBuilderInterface
/**
* Takes input of the diff array and returns the common parts.
* Iterates through diff line by line.
*
* @return array<int, positive-int>
*/
protected function getCommonChunks(array $diff, int $lineThreshold = 5): array
{
@@ -9,9 +9,11 @@
*/
namespace SebastianBergmann\Diff\Output;
use function assert;
use function fclose;
use function fopen;
use function fwrite;
use function is_resource;
use function str_ends_with;
use function stream_get_contents;
use function substr;
@@ -34,6 +36,8 @@ final class DiffOnlyOutputBuilder implements DiffOutputBuilderInterface
{
$buffer = fopen('php://memory', 'r+b');
assert(is_resource($buffer));
if ('' !== $this->header) {
fwrite($buffer, $this->header);
@@ -11,12 +11,14 @@ namespace SebastianBergmann\Diff\Output;
use function array_merge;
use function array_splice;
use function assert;
use function count;
use function fclose;
use function fopen;
use function fwrite;
use function is_bool;
use function is_int;
use function is_resource;
use function is_string;
use function max;
use function min;
@@ -99,6 +101,9 @@ final class StrictUnifiedDiffOutputBuilder implements DiffOutputBuilderInterface
$this->changed = false;
$buffer = fopen('php://memory', 'r+b');
assert(is_resource($buffer));
fwrite($buffer, $this->header);
$this->writeDiffHunks($buffer, $diff);
@@ -10,10 +10,12 @@
namespace SebastianBergmann\Diff\Output;
use function array_splice;
use function assert;
use function count;
use function fclose;
use function fopen;
use function fwrite;
use function is_resource;
use function max;
use function min;
use function str_ends_with;
@@ -46,6 +48,8 @@ final class UnifiedDiffOutputBuilder extends AbstractChunkOutputBuilder
{
$buffer = fopen('php://memory', 'r+b');
assert(is_resource($buffer));
if ('' !== $this->header) {
fwrite($buffer, $this->header);
+4
View File
@@ -9,6 +9,7 @@
*/
namespace SebastianBergmann\Diff;
use const PREG_UNMATCHED_AS_NULL;
use function array_pop;
use function assert;
use function count;
@@ -71,6 +72,9 @@ final class Parser
return $diffs;
}
/**
* @param string[] $lines
*/
private function parseFileDiff(Diff $diff, array $lines): void
{
$chunks = [];
@@ -11,7 +11,6 @@ namespace SebastianBergmann\Diff;
use function array_reverse;
use function count;
use function max;
use SplFixedArray;
final class TimeEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
+28
View File
@@ -2,6 +2,30 @@
All notable changes in `sebastianbergmann/environment` are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
## [8.0.3] - 2025-08-12
### Changed
* [#75](https://github.com/sebastianbergmann/environment/pull/75): Make `Runtime::isOpcacheActive()` public
## [8.0.2] - 2025-05-21
### Fixed
* [#74](https://github.com/sebastianbergmann/environment/pull/74): Regression introduced in version 8.0.0
## [8.0.1] - 2025-05-21
### Fixed
* Take Xdebug mode into account for `Runtime::canCollectCodeCoverage()`
## [8.0.0] - 2025-02-07
### Removed
* This component is no longer supported on PHP 8.2
## [7.2.1] - 2025-05-21
### Fixed
@@ -215,6 +239,10 @@ All notable changes in `sebastianbergmann/environment` are documented in this fi
* This component is no longer supported on PHP 5.6
[8.0.3]: https://github.com/sebastianbergmann/environment/compare/8.0.2...8.0.3
[8.0.2]: https://github.com/sebastianbergmann/environment/compare/8.0.1...8.0.2
[8.0.1]: https://github.com/sebastianbergmann/environment/compare/8.0.0...8.0.1
[8.0.0]: https://github.com/sebastianbergmann/environment/compare/7.2...8.0.0
[7.2.1]: https://github.com/sebastianbergmann/environment/compare/7.2.0...7.2.1
[7.2.0]: https://github.com/sebastianbergmann/environment/compare/7.1.0...7.2.0
[7.1.0]: https://github.com/sebastianbergmann/environment/compare/7.0.0...7.1.0
+4 -4
View File
@@ -16,17 +16,17 @@
},
"config": {
"platform": {
"php": "8.2.0"
"php": "8.3.0"
},
"optimize-autoloader": true,
"sort-packages": true
},
"prefer-stable": true,
"require": {
"php": ">=8.2"
"php": ">=8.3"
},
"require-dev": {
"phpunit/phpunit": "^11.3"
"phpunit/phpunit": "^12.0"
},
"suggest": {
"ext-posix": "*"
@@ -38,7 +38,7 @@
},
"extra": {
"branch-alias": {
"dev-main": "7.2-dev"
"dev-main": "8.0-dev"
}
}
}
+32 -13
View File
@@ -20,6 +20,7 @@ use function function_exists;
use function getenv;
use function in_array;
use function is_array;
use function is_int;
use function is_resource;
use function is_string;
use function posix_isatty;
@@ -38,17 +39,17 @@ final class Console
/**
* @var int
*/
public const STDIN = 0;
public const int STDIN = 0;
/**
* @var int
*/
public const STDOUT = 1;
public const int STDOUT = 1;
/**
* @var int
*/
public const STDERR = 2;
public const int STDERR = 2;
/**
* Returns true if STDOUT supports colorization.
@@ -117,8 +118,10 @@ final class Console
*
* @param int|resource $fileDescriptor
*/
public function isInteractive($fileDescriptor = self::STDOUT): bool
public function isInteractive(mixed $fileDescriptor = self::STDOUT): bool
{
assert(is_int($fileDescriptor) || is_resource($fileDescriptor));
if (is_resource($fileDescriptor)) {
if (function_exists('stream_isatty') && @stream_isatty($fileDescriptor)) {
return true;
@@ -127,7 +130,7 @@ final class Console
if (function_exists('fstat')) {
$stat = @fstat(STDOUT);
return $stat && 0o020000 === ($stat['mode'] & 0o170000);
return $stat !== false && 0o020000 === ($stat['mode'] & 0o170000);
}
return false;
@@ -146,15 +149,29 @@ final class Console
*/
private function getNumberOfColumnsInteractive(): int
{
if (function_exists('shell_exec') && preg_match('#\d+ (\d+)#', shell_exec('stty size') ?: '', $match) === 1) {
if ((int) $match[1] > 0) {
return (int) $match[1];
}
}
if (function_exists('shell_exec')) {
$stty = shell_exec('stty size');
if (function_exists('shell_exec') && preg_match('#columns = (\d+);#', shell_exec('stty') ?: '', $match) === 1) {
if ((int) $match[1] > 0) {
return (int) $match[1];
if ($stty === false || $stty === null) {
$stty = '';
}
if (preg_match('#\d+ (\d+)#', $stty, $match) === 1) {
if ((int) $match[1] > 0) {
return (int) $match[1];
}
}
$stty = shell_exec('stty');
if ($stty === false || $stty === null) {
$stty = '';
}
if (preg_match('#columns = (\d+);#', $stty, $match) === 1) {
if ((int) $match[1] > 0) {
return (int) $match[1];
}
}
}
@@ -169,6 +186,7 @@ final class Console
$ansicon = getenv('ANSICON');
$columns = 80;
/** @phpstan-ignore booleanAnd.rightNotBoolean */
if (is_string($ansicon) && preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim($ansicon), $matches)) {
$columns = (int) $matches[1];
} elseif (function_exists('proc_open')) {
@@ -195,6 +213,7 @@ final class Console
fclose($pipes[2]);
proc_close($process);
/** @phpstan-ignore if.condNotBoolean */
if (preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', (string) $info, $matches)) {
$columns = (int) $matches[2];
}
+9 -5
View File
@@ -218,7 +218,7 @@ final class Runtime
*/
public function hasPCOV(): bool
{
return $this->isPHP() && extension_loaded('pcov') && ini_get('pcov.enabled');
return $this->isPHP() && extension_loaded('pcov') && ini_get('pcov.enabled') === '1';
}
/**
@@ -240,11 +240,15 @@ final class Runtime
$diff = [];
$files = [];
if ($file = php_ini_loaded_file()) {
$file = php_ini_loaded_file();
if ($file !== false) {
$files[] = $file;
}
if ($scanned = php_ini_scanned_files()) {
$scanned = php_ini_scanned_files();
if ($scanned !== false) {
$files = array_merge(
$files,
array_map(
@@ -260,7 +264,7 @@ final class Runtime
foreach ($values as $value) {
$set = ini_get($value);
if (empty($set)) {
if ($set === false || $set === '') {
continue;
}
@@ -273,7 +277,7 @@ final class Runtime
return $diff;
}
private function isOpcacheActive(): bool
public function isOpcacheActive(): bool
{
if (!extension_loaded('Zend OPcache')) {
return false;
+8 -12
View File
@@ -2,28 +2,24 @@
All notable changes are documented in this file using the [Keep a CHANGELOG](https://keepachangelog.com/) principles.
## [6.3.2] - 2025-09-24
## [7.0.2] - 2025-09-24
### Changed
* Suppress `unexpected NAN value was coerced to string` warning triggered on PHP 8.5
## [6.3.1] - 2025-09-22
## [7.0.1] - 2025-09-22
### Changed
* Suppress `not representable as an int, cast occurred` warning triggered on PHP 8.5
## [6.3.0] - 2024-12-05
## [7.0.0] - 2025-02-07
### Added
### Removed
* Optional constructor argument to control maximum string length
* This component is no longer supported on PHP 8.2
### Deprecated
* Optional argument for `shortenedRecursiveExport()` and `shortenedExport()` to control maximum string length
[6.3.2]: https://github.com/sebastianbergmann/exporter/compare/6.3.1...6.3.2
[6.3.1]: https://github.com/sebastianbergmann/exporter/compare/6.3.0...6.3.1
[6.3.0]: https://github.com/sebastianbergmann/exporter/compare/6.2.0...6.3.0
[7.0.2]: https://github.com/sebastianbergmann/exporter/compare/7.0.1...7.0.2
[7.0.1]: https://github.com/sebastianbergmann/exporter/compare/7.0.0...7.0.1
[7.0.0]: https://github.com/sebastianbergmann/exporter/compare/6.3...7.0.0
+5 -5
View File
@@ -32,19 +32,19 @@
},
"config": {
"platform": {
"php": "8.2.0"
"php": "8.3.0"
},
"optimize-autoloader": true,
"sort-packages": true
},
"prefer-stable": true,
"require": {
"php": ">=8.2",
"php": ">=8.3",
"ext-mbstring": "*",
"sebastian/recursion-context": "^6.0"
"sebastian/recursion-context": "^7.0"
},
"require-dev": {
"phpunit/phpunit": "^11.3"
"phpunit/phpunit": "^12.0"
},
"autoload": {
"classmap": [
@@ -58,7 +58,7 @@
},
"extra": {
"branch-alias": {
"dev-main": "6.3-dev"
"dev-main": "7.0-dev"
}
}
}
+6 -5
View File
@@ -92,7 +92,7 @@ final readonly class Exporter
$maxLengthForStrings = $this->maxLengthForStrings;
}
if (!$processed) {
if ($processed === null) {
$processed = new RecursionContext;
}
@@ -197,7 +197,7 @@ final readonly class Exporter
// private $propertyName => "\0ClassName\0propertyName"
// protected $propertyName => "\0*\0propertyName"
// public $propertyName => "propertyName"
if (preg_match('/\0.+\0(.+)/', (string) $key, $matches)) {
if (preg_match('/\0.+\0(.+)/', (string) $key, $matches) === 1) {
$key = $matches[1];
}
@@ -262,7 +262,7 @@ final readonly class Exporter
}
if (is_array($value)) {
assert(is_array($data[$key]) || is_object($data[$key]));
assert(isset($data[$key]) && (is_array($data[$key]) || is_object($data[$key])));
if ($processed->contains($data[$key]) !== false) {
$result[] = '*RECURSION*';
@@ -302,6 +302,7 @@ final readonly class Exporter
if (is_resource($value)) {
return sprintf(
'resource(%d) of type (%s)',
/** @phpstan-ignore cast.useless */
(int) $value,
get_resource_type($value),
);
@@ -330,7 +331,7 @@ final readonly class Exporter
return $this->exportString($value);
}
if (!$processed) {
if ($processed === null) {
$processed = new RecursionContext;
}
@@ -365,7 +366,7 @@ final readonly class Exporter
private function exportString(string $value): string
{
// Match for most non-printable chars somewhat taking multibyte chars into account
if (preg_match('/[^\x09-\x0d\x1b\x20-\xff]/', $value)) {
if (preg_match('/[^\x09-\x0d\x1b\x20-\xff]/', $value) === 1) {
return 'Binary String: 0x' . bin2hex($value);
}
+21
View File
@@ -2,6 +2,24 @@
All notable changes in `sebastian/global-state` are documented in this file using the [Keep a CHANGELOG](https://keepachangelog.com/) principles.
## [8.0.2] - 2025-08-29
### Changed
* [#39](https://github.com/sebastianbergmann/global-state/pull/39): Restore nullable variables in super-global arrays
## [8.0.1] - 2025-08-28
### Changed
* [#38](https://github.com/sebastianbergmann/global-state/pull/38): Improve performance of `Snapshot::snapshotSuperGlobalArray()`
## [8.0.0] - 2025-02-07
### Removed
* This component is no longer supported on PHP 8.2
## [7.0.2] - 2024-07-03
### Changed
@@ -110,6 +128,9 @@ All notable changes in `sebastian/global-state` are documented in this file usin
* This component is no longer supported on PHP 7.0 and PHP 7.1
[8.0.2]: https://github.com/sebastianbergmann/global-state/compare/8.0.1...8.0.2
[8.0.1]: https://github.com/sebastianbergmann/global-state/compare/8.0.0...8.0.1
[8.0.0]: https://github.com/sebastianbergmann/global-state/compare/7.0...8.0.0
[7.0.2]: https://github.com/sebastianbergmann/global-state/compare/7.0.1...7.0.2
[7.0.1]: https://github.com/sebastianbergmann/global-state/compare/7.0.0...7.0.1
[7.0.0]: https://github.com/sebastianbergmann/global-state/compare/6.0...7.0.0
+1 -1
View File
@@ -1,6 +1,6 @@
BSD 3-Clause License
Copyright (c) 2001-2024, Sebastian Bergmann
Copyright (c) 2001-2025, Sebastian Bergmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
+1 -1
View File
@@ -1,4 +1,4 @@
[![Latest Stable Version](https://poser.pugx.org/sebastian/global-state/v/stable.png)](https://packagist.org/packages/sebastian/global-state)
[![Latest Stable Version](https://poser.pugx.org/sebastian/global-state/v)](https://packagist.org/packages/sebastian/global-state)
[![CI Status](https://github.com/sebastianbergmann/global-state/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/global-state/actions)
[![codecov](https://codecov.io/gh/sebastianbergmann/global-state/branch/main/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/global-state)
+6 -6
View File
@@ -17,19 +17,19 @@
"prefer-stable": true,
"config": {
"platform": {
"php": "8.2.0"
"php": "8.3.0"
},
"optimize-autoloader": true,
"sort-packages": true
},
"require": {
"php": ">=8.2",
"sebastian/object-reflector": "^4.0",
"sebastian/recursion-context": "^6.0"
"php": ">=8.3",
"sebastian/object-reflector": "^5.0",
"sebastian/recursion-context": "^7.0"
},
"require-dev": {
"ext-dom": "*",
"phpunit/phpunit": "^11.0"
"phpunit/phpunit": "^12.0"
},
"autoload": {
"classmap": [
@@ -46,7 +46,7 @@
},
"extra": {
"branch-alias": {
"dev-main": "7.0-dev"
"dev-main": "8.0-dev"
}
}
}
+4 -1
View File
@@ -13,6 +13,7 @@ use function array_diff;
use function array_key_exists;
use function array_keys;
use function array_merge;
use function assert;
use function in_array;
use function is_array;
use ReflectionClass;
@@ -95,7 +96,9 @@ final class Restorer
);
foreach ($keys as $key) {
if (isset($superGlobalVariables[$superGlobalArray][$key])) {
assert(isset($GLOBALS[$superGlobalArray]) && is_array($GLOBALS[$superGlobalArray]));
if (array_key_exists($key, $superGlobalVariables[$superGlobalArray])) {
$GLOBALS[$superGlobalArray][$key] = $superGlobalVariables[$superGlobalArray][$key];
} else {
unset($GLOBALS[$superGlobalArray][$key]);
+27 -11
View File
@@ -96,7 +96,11 @@ final class Snapshot
public function __construct(?ExcludeList $excludeList = null, bool $includeGlobalVariables = true, bool $includeStaticProperties = true, bool $includeConstants = true, bool $includeFunctions = true, bool $includeClasses = true, bool $includeInterfaces = true, bool $includeTraits = true, bool $includeIniSettings = true, bool $includeIncludedFiles = true)
{
$this->excludeList = $excludeList ?: new ExcludeList;
if ($excludeList === null) {
$excludeList = new ExcludeList;
}
$this->excludeList = $excludeList;
if ($includeConstants) {
$this->snapshotConstants();
@@ -128,6 +132,7 @@ final class Snapshot
assert($iniSettings !== false);
/* @phpstan-ignore assign.propertyType */
$this->iniSettings = $iniSettings;
}
@@ -290,10 +295,11 @@ final class Snapshot
foreach (array_keys($GLOBALS) as $key) {
if ($key !== 'GLOBALS' &&
!in_array($key, $superGlobalArrays, true) &&
$this->canBeSerialized($GLOBALS[$key]) &&
!$this->excludeList->isGlobalVariableExcluded($key)) {
/* @noinspection UnserializeExploitsInspection */
$this->globalVariables[$key] = unserialize(serialize($GLOBALS[$key]));
!$this->excludeList->isGlobalVariableExcluded($key) &&
$this->canBeSerialized($GLOBALS[$key])
) {
/* @phpstan-ignore assign.propertyType */
$this->globalVariables[$key] = $this->copyWithSerialize($GLOBALS[$key]);
}
}
}
@@ -304,8 +310,8 @@ final class Snapshot
if (isset($GLOBALS[$superGlobalArray]) && is_array($GLOBALS[$superGlobalArray])) {
foreach ($GLOBALS[$superGlobalArray] as $key => $value) {
/* @noinspection UnserializeExploitsInspection */
$this->superGlobalVariables[$superGlobalArray][$key] = unserialize(serialize($value));
/* @phpstan-ignore assign.propertyType */
$this->superGlobalVariables[$superGlobalArray][$key] = $this->copyWithSerialize($value);
}
}
}
@@ -331,13 +337,12 @@ final class Snapshot
$value = $property->getValue();
if ($this->canBeSerialized($value)) {
/* @noinspection UnserializeExploitsInspection */
$snapshot[$name] = unserialize(serialize($value));
$snapshot[$name] = $this->copyWithSerialize($value);
}
}
}
if (!empty($snapshot)) {
if ($snapshot !== []) {
$this->staticProperties[$className] = $snapshot;
}
}
@@ -356,6 +361,16 @@ final class Snapshot
];
}
private function copyWithSerialize(mixed $variable): mixed
{
if (is_scalar($variable) || $variable === null) {
return $variable;
}
/* @noinspection UnserializeExploitsInspection */
return unserialize(serialize($variable));
}
private function canBeSerialized(mixed $variable): bool
{
if (is_scalar($variable) || $variable === null) {
@@ -396,7 +411,8 @@ final class Snapshot
{
$result = [];
if ($processed->contains($variable)) {
/* @phpstan-ignore argument.type */
if ($processed->contains($variable) !== false) {
return $result;
}
+7
View File
@@ -2,6 +2,12 @@
All notable changes are documented in this file using the [Keep a CHANGELOG](https://keepachangelog.com/) principles.
## [4.0.0] - 2025-02-07
### Removed
* This component is no longer supported on PHP 8.2
## [3.0.1] - 2024-07-03
### Changed
@@ -59,6 +65,7 @@ All notable changes are documented in this file using the [Keep a CHANGELOG](htt
* Initial release
[4.0.0]: https://github.com/sebastianbergmann/lines-of-code/compare/3.0...4.0.0
[3.0.1]: https://github.com/sebastianbergmann/lines-of-code/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/sebastianbergmann/lines-of-code/compare/2.0...3.0.0
[2.0.2]: https://github.com/sebastianbergmann/lines-of-code/compare/2.0.1...2.0.2
+1 -1
View File
@@ -1,6 +1,6 @@
BSD 3-Clause License
Copyright (c) 2020-2024, Sebastian Bergmann
Copyright (c) 2020-2025, Sebastian Bergmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
+1 -1
View File
@@ -1,4 +1,4 @@
[![Latest Stable Version](https://poser.pugx.org/sebastian/lines-of-code/v/stable.png)](https://packagist.org/packages/sebastian/lines-of-code)
[![Latest Stable Version](https://poser.pugx.org/sebastian/lines-of-code/v)](https://packagist.org/packages/sebastian/lines-of-code)
[![CI Status](https://github.com/sebastianbergmann/lines-of-code/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/lines-of-code/actions)
[![codecov](https://codecov.io/gh/sebastianbergmann/lines-of-code/branch/main/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/lines-of-code)
+4 -4
View File
@@ -17,15 +17,15 @@
},
"prefer-stable": true,
"require": {
"php": ">=8.2",
"php": ">=8.3",
"nikic/php-parser": "^5.0"
},
"require-dev": {
"phpunit/phpunit": "^11.0"
"phpunit/phpunit": "^12.0"
},
"config": {
"platform": {
"php": "8.2"
"php": "8.3"
},
"optimize-autoloader": true,
"sort-packages": true
@@ -37,7 +37,7 @@
},
"extra": {
"branch-alias": {
"dev-main": "3.0-dev"
"dev-main": "4.0-dev"
}
}
}
-1
View File
@@ -48,7 +48,6 @@ final class Counter
assert($nodes !== null);
return $this->countInAbstractSyntaxTree($linesOfCode, $nodes);
// @codeCoverageIgnoreStart
} catch (Error $error) {
throw new RuntimeException(
@@ -1,16 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/lines-of-code.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\LinesOfCode;
use InvalidArgumentException;
final class NegativeValueException extends InvalidArgumentException implements Exception
{
}
@@ -43,15 +43,17 @@ final class LineCountingVisitor extends NodeVisitorAbstract
$this->linesOfCode = $linesOfCode;
}
public function enterNode(Node $node): void
public function enterNode(Node $node): null
{
$this->comments = array_merge($this->comments, $node->getComments());
if (!$node instanceof Expr) {
return;
return null;
}
$this->linesWithStatements[] = $node->getStartLine();
return null;
}
public function result(): LinesOfCode
-21
View File
@@ -41,30 +41,9 @@ final readonly class LinesOfCode
* @param non-negative-int $logicalLinesOfCode
*
* @throws IllogicalValuesException
* @throws NegativeValueException
*/
public function __construct(int $linesOfCode, int $commentLinesOfCode, int $nonCommentLinesOfCode, int $logicalLinesOfCode)
{
/** @phpstan-ignore smaller.alwaysFalse */
if ($linesOfCode < 0) {
throw new NegativeValueException('$linesOfCode must not be negative');
}
/** @phpstan-ignore smaller.alwaysFalse */
if ($commentLinesOfCode < 0) {
throw new NegativeValueException('$commentLinesOfCode must not be negative');
}
/** @phpstan-ignore smaller.alwaysFalse */
if ($nonCommentLinesOfCode < 0) {
throw new NegativeValueException('$nonCommentLinesOfCode must not be negative');
}
/** @phpstan-ignore smaller.alwaysFalse */
if ($logicalLinesOfCode < 0) {
throw new NegativeValueException('$logicalLinesOfCode must not be negative');
}
if ($linesOfCode - $commentLinesOfCode !== $nonCommentLinesOfCode) {
throw new IllogicalValuesException('$linesOfCode !== $commentLinesOfCode + $nonCommentLinesOfCode');
}
+7
View File
@@ -2,6 +2,12 @@
All notable changes to `sebastianbergmann/object-enumerator` are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
## [7.0.0] - 2025-02-07
### Removed
* This component is no longer supported on PHP 8.2
## [6.0.1] - 2024-07-03
### Changed
@@ -92,6 +98,7 @@ All notable changes to `sebastianbergmann/object-enumerator` are documented in t
* Initial release
[7.0.0]: https://github.com/sebastianbergmann/object-enumerator/compare/6.0...7.0.0
[6.0.1]: https://github.com/sebastianbergmann/object-enumerator/compare/6.0.0...6.0.1
[6.0.0]: https://github.com/sebastianbergmann/object-enumerator/compare/5.0...6.0.0
[5.0.0]: https://github.com/sebastianbergmann/object-enumerator/compare/4.0.4...5.0.0
+1 -1
View File
@@ -1,6 +1,6 @@
BSD 3-Clause License
Copyright (c) 2016-2024, Sebastian Bergmann
Copyright (c) 2016-2025, Sebastian Bergmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
+1 -1
View File
@@ -1,4 +1,4 @@
[![Latest Stable Version](https://poser.pugx.org/sebastian/object-enumerator/v/stable.png)](https://packagist.org/packages/sebastian/object-enumerator)
[![Latest Stable Version](https://poser.pugx.org/sebastian/object-enumerator/v)](https://packagist.org/packages/sebastian/object-enumerator)
[![CI Status](https://github.com/sebastianbergmann/object-enumerator/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/object-enumerator/actions)
[![codecov](https://codecov.io/gh/sebastianbergmann/object-enumerator/branch/main/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/object-enumerator)

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