diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 5907267..cefe186 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -92,7 +92,7 @@ body: id: php_version attributes: label: PHP version - placeholder: e.g. 8.4.13 + placeholder: e.g. 8.6.0 validations: required: true diff --git a/.github/ISSUE_TEMPLATE/ci_failure.yml b/.github/ISSUE_TEMPLATE/ci_failure.yml index 9c3883f..15f8608 100644 --- a/.github/ISSUE_TEMPLATE/ci_failure.yml +++ b/.github/ISSUE_TEMPLATE/ci_failure.yml @@ -67,7 +67,7 @@ body: id: php_version attributes: label: PHP version - placeholder: e.g. 8.4.13 + placeholder: e.g. 8.6.0 validations: required: true diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml index 62e91a7..1bd6a94 100644 --- a/.github/ISSUE_TEMPLATE/question.yml +++ b/.github/ISSUE_TEMPLATE/question.yml @@ -47,7 +47,7 @@ body: attributes: label: Environment description: Include package, PHP, Composer, OS, extensions or CI details only when relevant. - placeholder: Package 2.4.1, PHP 8.4, Composer 2.9, Ubuntu 24.04... + placeholder: Package 2.4.1, PHP 8.6, Composer 2.9, Ubuntu 24.04... - type: textarea id: additional diff --git a/.github/ISSUE_TEMPLATE/regression_report.yml b/.github/ISSUE_TEMPLATE/regression_report.yml index 36392bc..36beb89 100644 --- a/.github/ISSUE_TEMPLATE/regression_report.yml +++ b/.github/ISSUE_TEMPLATE/regression_report.yml @@ -46,6 +46,6 @@ body: attributes: label: Environment details description: PHP version, Composer version, OS, CI provider (if relevant). - placeholder: PHP 8.3, Composer 2.9, Ubuntu 24.04... + placeholder: PHP 8.6, Composer 2.9, Ubuntu 24.04... validations: required: true diff --git a/.github/workflows/security-standards.yml b/.github/workflows/security-standards.yml index 7f98ace..c2e45b2 100644 --- a/.github/workflows/security-standards.yml +++ b/.github/workflows/security-standards.yml @@ -9,6 +9,10 @@ on: pull_request: branches: [ "main", "master", "develop", "development" ] +concurrency: + group: arraykit-${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: true + jobs: release: if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') @@ -22,6 +26,8 @@ jobs: if: github.event_name != 'push' || !startsWith(github.ref, 'refs/tags/') uses: infocyph/phpforge/.github/workflows/security-standards.yml@main with: + php_versions: '["8.4","8.5","8.6"]' + php_extensions: 'intl' integration_services: '[]' service_topologies: '{}' benchmark_composer_script: "benchmark:representative" @@ -51,13 +57,13 @@ jobs: runwire-compat: if: github.event_name != 'push' || !startsWith(github.ref, 'refs/tags/') - name: "Runwire 3.0 / PHP ${{ matrix.php }}" + name: "Runwire 4.0.1 / PHP ${{ matrix.php }}" runs-on: ubuntu-latest timeout-minutes: 15 strategy: fail-fast: false matrix: - php: ["8.4", "8.5"] + php: ["8.4", "8.5", "8.6"] env: XDEBUG_MODE: off steps: @@ -67,11 +73,11 @@ jobs: with: php-version: ${{ matrix.php }} tools: composer:v2 - extensions: opcache + extensions: opcache, intl ini-values: opcache.enable_cli=1 coverage: none - - name: Install exact Runwire 3.0 - run: composer require --dev "infocyph/runwire:3.0.0" --no-interaction --prefer-dist --no-progress + - name: Install exact Runwire 4.0.1 + run: composer require --dev "infocyph/runwire:4.0.1" --no-interaction --prefer-dist --no-progress - name: Exercise lazy pipeline and host-owned coroutine lifecycle run: >- php vendor/bin/pest @@ -81,7 +87,7 @@ jobs: tests/Feature/Release530BatchETest.php tests/Feature/Release530ReviewRegressionTest.php tests/Feature/Release530BatchFTest.php - - name: Exercise persistent worker with Runwire 3.0 + - name: Exercise persistent worker with Runwire 4.0.1 if: matrix.php == '8.5' run: | mkdir -p build @@ -92,11 +98,11 @@ jobs: --max-growth-mb=16 \ --report=build/runwire-worker-soak.json \ -- php -d opcache.enable_cli=1 tests/Support/release530-persistent-worker.php - - name: Upload Runwire 3.0 worker-soak report + - name: Upload Runwire 4.0.1 worker-soak report if: always() && matrix.php == '8.5' && hashFiles('build/runwire-worker-soak.json') != '' uses: actions/upload-artifact@v7 with: - name: runwire-3.0-php-${{ matrix.php }}-worker-soak + name: runwire-4.0.1-php-${{ matrix.php }}-worker-soak path: build/runwire-worker-soak.json if-no-files-found: error retention-days: 61 @@ -115,7 +121,7 @@ jobs: with: php-version: "8.5" tools: composer:v2 - extensions: opcache + extensions: opcache, intl ini-values: opcache.enable_cli=1 coverage: none - name: Install acceptance dependencies diff --git a/README.md b/README.md index 85fcc96..7b07c0e 100644 --- a/README.md +++ b/README.md @@ -88,9 +88,12 @@ configuration or object models. ## Requirements -* **PHP 8.4** or higher +* **PHP 8.4** or higher (CI matrix: PHP 8.4, 8.5 and 8.6) +* **ext-filter**, **ext-hash** and **ext-tokenizer** -Runwire is optional. ArrayKit 5.3.2 qualifies its passed-instance lazy-runtime integration against `infocyph/runwire` 3.0 on PHP 8.4 and 8.5; ordinary ArrayKit installation has no Runwire runtime dependency. +`ext-intl` is optional; it is required for locale-aware sorting outside the C/POSIX collation locale. + +Runwire is optional. The 5.4 release line targets `infocyph/runwire` `^4.0.1`, with exact 4.0.1 integration tested on PHP 8.4, 8.5 and 8.6. Ordinary ArrayKit installation has no Runwire runtime dependency. ## Installation @@ -160,6 +163,10 @@ $flatZero = ArrayMulti::flatten($data, 0); // [[1, 2], [3, [4, 5]]] $flatOne = ArrayMulti::flatten($data, 1); // [1, 2, 3, [4, 5]] // Multi-column and query helpers +$rows = [ + ['status' => 'active', 'created_at' => '2026-01-01', 'email' => 'alice@example.com', 'role' => 'admin'], + ['status' => 'inactive', 'created_at' => '2026-01-02', 'email' => 'bob@example.com', 'role' => 'editor'], +]; $sortedMany = ArrayMulti::sortByMany($rows, [ ['status', 'asc'], ['created_at', 'desc'], @@ -168,7 +175,7 @@ $active = ArrayMulti::whereStartsWith($rows, 'status', 'act', false); $match = ArrayMulti::whereLike($rows, 'email', '%@example.com'); $first = ArrayMulti::firstWhereIn($rows, 'role', ['admin', 'editor']); $uniqueUsers = ArrayMulti::uniqueBy($rows, 'email'); -$dupeUsers = ArrayMulti::duplicatesBy($rows, fn ($row) => strtolower((string) ($row['email'] ?? ''))); +$dupeUsers = ArrayMulti::duplicatesBy($rows, 'email'); // Collapse one level $collapsed = ArrayMulti::collapse($data); // [1, 2, 3, [4, 5]] @@ -305,6 +312,9 @@ $host = $config->get('db.host'); - `ArrayMulti::flatten($array, 0)` keeps top-level values unchanged; `1` flattens one level; `INF` fully flattens. - `ArraySingle::avg()`, `sum()`, `isPositive()`, and `isNegative()` only consider numeric values (non-numeric values are ignored). +- `ArraySingle::duplicates($values, true)` reports repeated `null` without conflating it with `false`, `0` or `''`. +- Use `ArrayMulti::SORT_LOCALE` for locale-aware sorting instead of PHP's deprecated locale flag; non-C collation uses ICU and may differ from libc. +- Unseeded `ArraySingle::shuffle()` uses secure randomness; seeded shuffles are reproducible but their exact order changed with the new engine. - `ArraySingle::paginate()` requires `page >= 1` and `perPage >= 1` (throws `InvalidArgumentException` otherwise). - Callback-based row helpers (`ArrayMulti::sortBy()`, `sum()`, `maxBy()`, `minBy()`) support `($row, $key)`. - `DotNotation` treats existing `null` keys/properties as present (does not fall back to defaults). diff --git a/benchmarks/ArrayMultiBench.php b/benchmarks/ArrayMultiBench.php index 92ae302..c0c1c07 100644 --- a/benchmarks/ArrayMultiBench.php +++ b/benchmarks/ArrayMultiBench.php @@ -10,6 +10,10 @@ use PhpBench\Attributes\ParamProviders; use PhpBench\Attributes\Revs; +/** + * PhpBench discovers this benchmark through its attributes. + * @api + */ #[Revs(1)] #[Iterations(3)] #[BeforeMethods('setUp')] @@ -42,6 +46,9 @@ public function setUp(array $params): void $this->needles = range(0, $params['needles'] - 1); } + /** + * @throws \InvalidArgumentException + */ public function benchCountBy(): void { ArrayMulti::countBy($this->rows, 'group'); @@ -57,34 +64,53 @@ public function benchFlatten(): void ArrayMulti::flatten($this->rows); } + /** + * @throws \InvalidArgumentException + */ public function benchGroupBy(): void { ArrayMulti::groupBy($this->rows, 'group'); } + /** + * @throws \InvalidArgumentException + */ public function benchKeyBy(): void { ArrayMulti::keyBy($this->rows, 'id'); } - public function benchKeyByNative(): void + /** @return array */ + public function benchKeyByNative(): array { $result = []; foreach ($this->rows as $row) { $result[$row['id']] = $row; } + + return $result; } - public function benchPluck(): void + /** + * @return array + * @throws \InvalidArgumentException + */ + public function benchPluck(): array { - ArrayMulti::pluck($this->rows, 'score', 'id'); + return ArrayMulti::pluck($this->rows, 'score', 'id'); } + /** + * @throws \RuntimeException + */ public function benchSortBy(): void { ArrayMulti::sortBy($this->rows, 'score', true, SORT_NUMERIC); } + /** + * @throws \RuntimeException + */ public function benchSortByMany(): void { ArrayMulti::sortByMany($this->rows, [ @@ -103,9 +129,10 @@ public function benchUniqueByStrict(): void ArrayMulti::uniqueBy($this->rows, 'derived', true); } - public function benchWhere(): void + /** @return array */ + public function benchWhere(): array { - ArrayMulti::where($this->rows, 'score', '>=', 500); + return ArrayMulti::where($this->rows, 'score', '>=', 500); } public function benchWhereIn(): void @@ -113,7 +140,8 @@ public function benchWhereIn(): void ArrayMulti::whereIn($this->rows, 'score', $this->needles, true); } - public function benchWhereInNative(): void + /** @return array */ + public function benchWhereInNative(): array { $result = []; foreach ($this->rows as $key => $row) { @@ -121,6 +149,8 @@ public function benchWhereInNative(): void $result[$key] = $row; } } + + return $result; } public function benchWhereNotIn(): void diff --git a/benchmarks/ArraySingleBench.php b/benchmarks/ArraySingleBench.php index e7199f6..0445559 100644 --- a/benchmarks/ArraySingleBench.php +++ b/benchmarks/ArraySingleBench.php @@ -10,6 +10,10 @@ use PhpBench\Attributes\ParamProviders; use PhpBench\Attributes\Revs; +/** + * PhpBench discovers this benchmark through its attributes. + * @api + */ #[Revs(1)] #[Iterations(3)] #[BeforeMethods('setUp')] @@ -41,6 +45,7 @@ public function setUp(array $params): void $this->needles = array_slice($this->data, 0, min(100, $params['size'])); } + /** @param array{size:int} $params */ public function benchContains(array $params): void { ArraySingle::contains($this->data, $params['size'] - 1, true); @@ -51,14 +56,16 @@ public function benchContainsAll(): void ArraySingle::containsAll($this->data, $this->needles, true); } + /** @param array{size:int} $params */ public function benchContainsAny(array $params): void { ArraySingle::containsAny($this->data, [$params['size'], $this->needles[0]], true); } - public function benchContainsNative(array $params): void + /** @param array{size:int} $params */ + public function benchContainsNative(array $params): bool { - in_array($params['size'] - 1, $this->data, true); + return in_array($params['size'] - 1, $this->data, true); } public function benchDiff(): void @@ -76,17 +83,21 @@ public function benchMap(): void ArraySingle::map($this->data, static fn(int $value): int => $value + 1); } - public function benchMapArrayMap(): void + /** @return array */ + public function benchMapArrayMap(): array { - array_map(static fn(int $value): int => $value + 1, $this->data); + return array_map(static fn(int $value): int => $value + 1, $this->data); } - public function benchMapForeach(): void + /** @return array */ + public function benchMapForeach(): array { $result = []; foreach ($this->data as $key => $value) { $result[$key] = $value + 1; } + + return $result; } public function benchMedian(): void @@ -94,11 +105,15 @@ public function benchMedian(): void ArraySingle::median($this->data); } - public function benchMode(): void + /** @return array */ + public function benchMode(): array { - ArraySingle::mode($this->data); + return ArraySingle::mode($this->data); } + /** + * @throws \InvalidArgumentException + */ public function benchNth(): void { ArraySingle::nth($this->data, 10, 3); @@ -144,7 +159,7 @@ public function benchWhere(): void ArraySingle::where($this->keyed, static fn(int $value): bool => ($value % 2) === 0); } - /** @return array */ + /** @return array */ public function provideSizes(): array { return [ diff --git a/benchmarks/ArrayValueSetBench.php b/benchmarks/ArrayValueSetBench.php index 16435ee..7468c78 100644 --- a/benchmarks/ArrayValueSetBench.php +++ b/benchmarks/ArrayValueSetBench.php @@ -5,12 +5,16 @@ namespace Infocyph\ArrayKit\Benchmarks; use Infocyph\ArrayKit\Array\ArraySingle; -use Infocyph\ArrayKit\Array\ArraySingleOps; +use Infocyph\ArrayKit\Array\ArrayValueSetOps; use PhpBench\Attributes\BeforeMethods; use PhpBench\Attributes\Iterations; use PhpBench\Attributes\ParamProviders; use PhpBench\Attributes\Revs; +/** + * PhpBench discovers this benchmark through its attributes. + * @api + */ #[Revs(1)] #[Iterations(3)] #[BeforeMethods('setUp')] @@ -36,19 +40,23 @@ public function setUp(array $params): void } } - public function benchCanonicalFingerprintSet(): void + /** @return array */ + public function benchCanonicalFingerprintSet(): array { $seen = []; foreach ($this->values as $value) { - $seen[ArraySingleOps::fingerprint($value, true)] = true; + $seen[ArrayValueSetOps::fingerprint($value)] = true; } + + return $seen; } - public function benchDigestWithVerifiedBuckets(): void + /** @return array */ + public function benchDigestWithVerifiedBuckets(): array { $buckets = []; foreach ($this->values as $value) { - $fingerprint = ArraySingleOps::fingerprint($value, true); + $fingerprint = ArrayValueSetOps::fingerprint($value); $digest = hash('xxh128', $fingerprint, true); if (!isset($buckets[$digest])) { $buckets[$digest] = [$fingerprint]; @@ -60,6 +68,8 @@ public function benchDigestWithVerifiedBuckets(): void $buckets[$digest][] = $fingerprint; } } + + return $buckets; } public function benchLooseNestedUnique(): void @@ -85,7 +95,8 @@ public function benchMixedStrictUnique(): void ], true); } - public function benchStrictNestedScan(): void + /** @return array */ + public function benchStrictNestedScan(): array { $seen = []; foreach ($this->values as $value) { @@ -93,6 +104,8 @@ public function benchStrictNestedScan(): void $seen[] = $value; } } + + return $seen; } public function benchStrictNestedUnique(): void diff --git a/benchmarks/CollectionBench.php b/benchmarks/CollectionBench.php index 0e9908d..8c3a09d 100644 --- a/benchmarks/CollectionBench.php +++ b/benchmarks/CollectionBench.php @@ -12,6 +12,10 @@ use PhpBench\Attributes\ParamProviders; use PhpBench\Attributes\Revs; +/** + * PhpBench discovers this benchmark through its attributes. + * @api + */ #[Revs(1)] #[Iterations(3)] #[BeforeMethods('setUp')] @@ -37,11 +41,22 @@ public function benchCollectionMap(): void Collection::make($this->data)->map(static fn(int $value): int => $value * 2); } + /** + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function benchLazyArrayReplayMaterialization(): void { LazyCollection::from($this->data)->all(); } + /** + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function benchLazyChunkMaterialization(): void { LazyCollection::fromFactory(fn(): array => $this->data) @@ -49,11 +64,21 @@ public function benchLazyChunkMaterialization(): void ->all(); } + /** + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function benchLazyFactoryArrayMaterialization(): void { LazyCollection::fromFactory(fn(): array => $this->data)->all(); } + /** + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function benchLazyFilterMaterialization(): void { LazyCollection::fromFactory(fn(): array => $this->data) @@ -61,6 +86,11 @@ public function benchLazyFilterMaterialization(): void ->all(); } + /** + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function benchLazyGeneratorReplayMaterialization(): void { $data = $this->data; @@ -71,6 +101,12 @@ public function benchLazyGeneratorReplayMaterialization(): void LazyCollection::from($source)->all(); } + /** + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function benchLazyMapFilterTake(): void { LazyCollection::fromFactory(fn(): array => $this->data) @@ -80,6 +116,11 @@ public function benchLazyMapFilterTake(): void ->all(); } + /** + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function benchLazyMapMaterialization(): void { LazyCollection::fromFactory(fn(): array => $this->data) diff --git a/benchmarks/ConfigBench.php b/benchmarks/ConfigBench.php index 8d4a978..74c7c51 100644 --- a/benchmarks/ConfigBench.php +++ b/benchmarks/ConfigBench.php @@ -10,6 +10,10 @@ use PhpBench\Attributes\ParamProviders; use PhpBench\Attributes\Revs; +/** + * PhpBench discovers this benchmark through its attributes. + * @api + */ #[Revs(1)] #[Iterations(3)] #[BeforeMethods('setUp')] @@ -24,7 +28,16 @@ final class ConfigBench private Config $uncached; - /** @param array{path:string, reads:int} $params */ + public function __construct() + { + $this->cached = new Config(); + $this->uncached = new Config(); + } + + /** + * @param array{path:string, reads:int} $params + * @throws \RuntimeException + */ public function setUp(array $params): void { $items = [ @@ -59,16 +72,27 @@ public function benchCachedGet(): void } } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ public function benchFill(): void { $this->cached->fill('one.two.added', 1); } + /** + * @throws \RuntimeException + */ public function benchForget(): void { $this->cached->forget('one.two.three'); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ public function benchSet(): void { $this->cached->set('one.two.value', 1); diff --git a/benchmarks/CoreBench.php b/benchmarks/CoreBench.php index 0a1aaa1..ab5eaa5 100644 --- a/benchmarks/CoreBench.php +++ b/benchmarks/CoreBench.php @@ -13,6 +13,10 @@ use PhpBench\Attributes\Revs; use PhpBench\Attributes\Subject; +/** + * PhpBench discovers this benchmark through its attributes. + * @api + */ #[Revs(500)] #[Iterations(5)] #[BeforeMethods('setUp')] @@ -20,20 +24,35 @@ final class CoreBench { private Config $config; + /** @var array */ private array $dot = []; + /** @var list}> */ private array $nested = []; + /** @var list */ private array $queryRows = []; + /** @var list */ private array $queryRowsLarge = []; + /** @var list */ private array $single = []; + /** @var array */ private array $singleAssoc = []; + /** @var list */ private array $uniqueNestedLarge = []; + public function __construct() + { + $this->config = new Config(); + } + + /** + * @throws \RuntimeException + */ public function setUp(): void { $this->single = [ @@ -124,12 +143,18 @@ public function benchArrayMultiFlattenDeep(): void ArrayMulti::flatten([[[[1, 2], 3], [4, [5, [6]]]], 7]); } + /** + * @throws \InvalidArgumentException + */ #[Subject] public function benchArrayMultiKeyBy(): void { ArrayMulti::keyBy($this->nested, 'id'); } + /** + * @throws \InvalidArgumentException + */ #[Subject] public function benchArrayMultiKeyBy10k(): void { @@ -164,12 +189,18 @@ public function benchArrayMultiWhereInNull(): void ArrayMulti::whereIn($this->queryRows, 'role', [null], true); } + /** + * @throws \InvalidArgumentException + */ #[Subject] public function benchArraySingleCountBy(): void { ArraySingle::countBy($this->single); } + /** + * @throws \InvalidArgumentException + */ #[Subject] public function benchArraySingleNth(): void { diff --git a/benchmarks/DotNotationBench.php b/benchmarks/DotNotationBench.php index 49a3bab..c9372a3 100644 --- a/benchmarks/DotNotationBench.php +++ b/benchmarks/DotNotationBench.php @@ -10,6 +10,10 @@ use PhpBench\Attributes\ParamProviders; use PhpBench\Attributes\Revs; +/** + * PhpBench discovers this benchmark through its attributes. + * @api + */ #[Revs(1)] #[Iterations(3)] #[BeforeMethods('setUp')] @@ -20,7 +24,7 @@ final class DotNotationBench private string $path = ''; - /** @var array */ + /** @var array{plain?:int,one?:array{two:array{three:array{four:array{five:array{six:array{seven:array{eight:array{nine:array{ten:int}}}}}}}}},'service.name'?:string,users?:list}>} */ private array $target = []; /** @param array{path:string} $params */ @@ -45,6 +49,9 @@ public function benchColdMissingPath(): void DotNotation::get($this->target, 'cold.' . $this->coldPath++ . '.missing'); } + /** + * @throws \InvalidArgumentException + */ public function benchFill(): void { $target = $this->target; @@ -57,11 +64,14 @@ public function benchForget(): void DotNotation::forget($target, 'users.*.teams.*.name'); } - public function benchNativeNestedGet(): void + public function benchNativeNestedGet(): mixed { - $value = $this->target['one']['two']['three']['four']['five'] ?? null; + return $this->target['one']['two']['three']['four']['five'] ?? null; } + /** + * @throws \InvalidArgumentException + */ public function benchSet(): void { $target = $this->target; diff --git a/benchmarks/EnvParserBench.php b/benchmarks/EnvParserBench.php index b3dcc13..1e37f42 100644 --- a/benchmarks/EnvParserBench.php +++ b/benchmarks/EnvParserBench.php @@ -10,6 +10,10 @@ use PhpBench\Attributes\ParamProviders; use PhpBench\Attributes\Revs; +/** + * PhpBench discovers this benchmark through its attributes. + * @api + */ #[Revs(1)] #[Iterations(3)] #[BeforeMethods('setUp')] @@ -35,11 +39,17 @@ public function setUp(array $params): void $this->contents = implode("\n", $lines); } + /** + * @throws \UnexpectedValueException + */ public function benchParse(): void { EnvParser::parse($this->contents); } + /** + * @throws \UnexpectedValueException + */ public function benchParseRaw(): void { EnvParser::parseRaw($this->contents); diff --git a/benchmarks/LazyFileConfigBench.php b/benchmarks/LazyFileConfigBench.php index e3806f7..8fb455a 100644 --- a/benchmarks/LazyFileConfigBench.php +++ b/benchmarks/LazyFileConfigBench.php @@ -10,6 +10,10 @@ use PhpBench\Attributes\Iterations; use PhpBench\Attributes\Revs; +/** + * PhpBench discovers this benchmark through its attributes. + * @api + */ #[Revs(1)] #[Iterations(3)] #[BeforeMethods('setUp')] @@ -18,23 +22,32 @@ final class LazyFileConfigBench { private string $cacheDirectory = ''; - private LazyFileConfig $flatConfig; + private ?LazyFileConfig $flatConfig = null; - private LazyFileConfig $loadedConfig; + private ?LazyFileConfig $loadedConfig = null; - private LazyFileConfig $missingConfig; + private ?LazyFileConfig $missingConfig = null; - private LazyFileConfig $namespaceCacheConfig; + private ?LazyFileConfig $namespaceCacheConfig = null; - private LazyFileConfig $sourceConfig; + private ?LazyFileConfig $sourceConfig = null; private string $sourceDirectory = ''; - private LazyFileConfig $warmConfig; + private ?LazyFileConfig $warmConfig = null; + /** + * @throws \RuntimeException + * @throws \UnexpectedValueException + * @throws \InvalidArgumentException + */ public function setUp(): void { - $base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'arraykit-lazy-bench-' . getmypid(); + $pid = getmypid(); + if ($pid === false) { + throw new \RuntimeException('Unable to determine benchmark process ID.'); + } + $base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'arraykit-lazy-bench-' . $pid; $this->sourceDirectory = $base . DIRECTORY_SEPARATOR . 'source'; $this->cacheDirectory = $base . DIRECTORY_SEPARATOR . 'cache'; mkdir($this->sourceDirectory, 0777, true); @@ -58,65 +71,96 @@ public function setUp(): void public function tearDown(): void { - $remove = static function (string $path) use (&$remove): void { - if (is_file($path)) { - unlink($path); - - return; - } - - if (!is_dir($path)) { - return; - } - - foreach (scandir($path) ?: [] as $entry) { - if ($entry === '.' || $entry === '..') { - continue; - } - - $remove($path . DIRECTORY_SEPARATOR . $entry); - } - - rmdir($path); - }; - - $remove(dirname($this->sourceDirectory)); + self::removePath(dirname($this->sourceDirectory)); } + /** + * @throws \LogicException + * @throws \RuntimeException + */ public function benchAlreadyLoadedNamespace(): void { - $this->loadedConfig->get('app.nested.value'); + ($this->loadedConfig ?? throw new \LogicException('Benchmark setup was not run.'))->get('app.nested.value'); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + * @throws \LogicException + */ public function benchCacheWarm(): void { - $this->warmConfig->warmNamespaceCache('app'); + ($this->warmConfig ?? throw new \LogicException('Benchmark setup was not run.'))->warmNamespaceCache('app'); } + /** + * @throws \LogicException + * @throws \RuntimeException + */ public function benchFlatLeafHit(): void { - $this->flatConfig->get('app.nested.value'); + ($this->flatConfig ?? throw new \LogicException('Benchmark setup was not run.'))->get('app.nested.value'); } + /** + * @throws \LogicException + * @throws \RuntimeException + */ public function benchMissingNamespace(): void { - $this->missingConfig->get('missing.value'); + ($this->missingConfig ?? throw new \LogicException('Benchmark setup was not run.'))->get('missing.value'); } + /** + * @throws \LogicException + * @throws \RuntimeException + */ public function benchNamespaceCacheLoad(): void { - $this->namespaceCacheConfig->get('app'); + ($this->namespaceCacheConfig ?? throw new \LogicException('Benchmark setup was not run.'))->get('app'); } + /** + * @throws \LogicException + * @throws \RuntimeException + */ public function benchRepeatedMissingLookup(): void { for ($index = 0; $index < 100; $index++) { - $this->missingConfig->get('missing.value'); + ($this->missingConfig ?? throw new \LogicException('Benchmark setup was not run.'))->get('missing.value'); } } + /** + * @throws \LogicException + * @throws \RuntimeException + */ public function benchSourceLoad(): void { - $this->sourceConfig->get('app.nested.value'); + ($this->sourceConfig ?? throw new \LogicException('Benchmark setup was not run.'))->get('app.nested.value'); + } + + private static function removePath(string $path): void + { + if (is_file($path)) { + unlink($path); + + return; + } + + if (!is_dir($path)) { + return; + } + + $entries = scandir($path); + foreach ($entries === false ? [] : $entries as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + + self::removePath($path . DIRECTORY_SEPARATOR . $entry); + } + + rmdir($path); } } diff --git a/benchmarks/MembershipCrossoverBench.php b/benchmarks/MembershipCrossoverBench.php index ccf39b5..3e5d678 100644 --- a/benchmarks/MembershipCrossoverBench.php +++ b/benchmarks/MembershipCrossoverBench.php @@ -12,6 +12,10 @@ use PhpBench\Attributes\RetryThreshold; use PhpBench\Attributes\Revs; +/** + * PhpBench discovers this benchmark through its attributes. + * @api + */ #[Revs(3)] #[Iterations(5)] #[RetryThreshold(100)] @@ -56,9 +60,9 @@ public function benchContainsAllAdaptive(): void ArraySingle::containsAll($this->haystack, $this->allNeedles, true); } - public function benchContainsAllScan(): void + public function benchContainsAllScan(): bool { - array_all( + return array_all( $this->allNeedles, fn(int $needle): bool => in_array($needle, $this->haystack, true), ); @@ -69,9 +73,9 @@ public function benchContainsAnyAdaptive(): void ArraySingle::containsAny($this->haystack, $this->needles, true); } - public function benchContainsAnyScan(): void + public function benchContainsAnyScan(): bool { - array_any( + return array_any( $this->needles, fn(int $needle): bool => in_array($needle, $this->haystack, true), ); @@ -82,7 +86,8 @@ public function benchDiffAdaptive(): void ArraySingle::diff($this->haystack, $this->needles, true); } - public function benchDiffScan(): void + /** @return array */ + public function benchDiffScan(): array { $results = []; foreach ($this->haystack as $key => $value) { @@ -90,6 +95,8 @@ public function benchDiffScan(): void $results[$key] = $value; } } + + return $results; } public function benchIntersectAdaptive(): void @@ -97,7 +104,8 @@ public function benchIntersectAdaptive(): void ArraySingle::intersect($this->haystack, $this->needles, true); } - public function benchIntersectScan(): void + /** @return array */ + public function benchIntersectScan(): array { $results = []; foreach ($this->haystack as $key => $value) { @@ -105,6 +113,8 @@ public function benchIntersectScan(): void $results[$key] = $value; } } + + return $results; } public function benchWhereInAdaptive(): void @@ -112,7 +122,8 @@ public function benchWhereInAdaptive(): void ArrayMulti::whereIn($this->rows, 'id', $this->needles, true); } - public function benchWhereInScan(): void + /** @return array */ + public function benchWhereInScan(): array { $results = []; foreach ($this->rows as $key => $row) { @@ -120,6 +131,8 @@ public function benchWhereInScan(): void $results[$key] = $row; } } + + return $results; } /** @return array */ diff --git a/benchmarks/RunwireLazyCollectionBench.php b/benchmarks/RunwireLazyCollectionBench.php index 22f5e31..f543961 100644 --- a/benchmarks/RunwireLazyCollectionBench.php +++ b/benchmarks/RunwireLazyCollectionBench.php @@ -12,6 +12,10 @@ use PhpBench\Attributes\ParamProviders; use PhpBench\Attributes\Revs; +/** + * PhpBench discovers this benchmark through its attributes. + * @api + */ #[Revs(1)] #[Iterations(3)] #[BeforeMethods('setUp')] @@ -21,11 +25,15 @@ final class RunwireLazyCollectionBench /** @var array */ private array $data = []; - private RequestContext $request; + private ?RequestContext $request = null; - private RuntimeContext $runtime; + private ?RuntimeContext $runtime = null; - /** @param array{size:int} $params */ + /** + * @param array{size:int} $params + * @throws \InvalidArgumentException + * @throws \LogicException + */ public function setUp(array $params): void { $this->data = range(1, $params['size']); @@ -33,22 +41,47 @@ public function setUp(array $params): void $this->request = RequestContext::create($this->runtime); } + /** + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function benchBoundRequestMapFilter(): void { LazyCollection::from($this->data) - ->withRunwire($this->runtime, $this->request, checkpointEvery: 256) + ->withRunwire( + $this->runtime ?? throw new \LogicException('Benchmark setup was not run.'), + $this->request ?? throw new \LogicException('Benchmark setup was not run.'), + checkpointEvery: 256, + ) ->mapLazy(static fn(int $value): int => $value * 2) ->filterLazy(static fn(int $value): bool => ($value % 3) === 0) ->all(); } + /** + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function benchBoundRequestMaterialization(): void { LazyCollection::from($this->data) - ->withRunwire($this->runtime, $this->request, checkpointEvery: 256) + ->withRunwire( + $this->runtime ?? throw new \LogicException('Benchmark setup was not run.'), + $this->request ?? throw new \LogicException('Benchmark setup was not run.'), + checkpointEvery: 256, + ) ->all(); } + /** + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function benchUnboundMapFilter(): void { LazyCollection::from($this->data) @@ -57,6 +90,11 @@ public function benchUnboundMapFilter(): void ->all(); } + /** + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function benchUnboundMaterialization(): void { LazyCollection::from($this->data)->all(); diff --git a/benchmarks/release-representative.php b/benchmarks/release-representative.php index 46d56fa..2aa982b 100644 --- a/benchmarks/release-representative.php +++ b/benchmarks/release-representative.php @@ -26,7 +26,11 @@ $root = dirname(__DIR__); $worker = __DIR__ . '/release-workload.php'; $buildDirectory = $root . '/build'; -$baselineDirectory = sys_get_temp_dir() . '/arraykit-release-baseline-' . getmypid(); +$pid = getmypid(); +if ($pid === false) { + throw new RuntimeException('Unable to determine benchmark process ID.'); +} +$baselineDirectory = sys_get_temp_dir() . '/arraykit-release-baseline-' . $pid; if (!is_dir($buildDirectory) && !mkdir($buildDirectory, 0777, true)) { throw new RuntimeException('Unable to create release benchmark build directory.'); @@ -59,8 +63,8 @@ fwrite(STDOUT, sprintf( "Representative release benchmark generated for %s and %s.\n", - $baseline['environment']['release'], - $candidate['environment']['release'], + RELEASE_BASELINE_TAG . '@' . $baselineSha, + 'candidate@' . $candidateSha, )); } finally { releaseRemoveBaseline($root, $baselineDirectory); @@ -69,7 +73,10 @@ /** * @param array $environment * @param list $specs - * @return array + * @return array{schema_version:int,generated_at:string,environment:array,workloads:list>} + * @throws RuntimeException + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\InvalidArgumentException */ function releaseBenchmarkDocument( string $root, @@ -105,6 +112,9 @@ function releaseBenchmarkDocument( /** * @param array{name:string,operations:int,warmup:int} $spec * @return array + * @throws \RuntimeException + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\InvalidArgumentException */ function releaseBenchmarkWorkload( string $root, @@ -150,7 +160,7 @@ function releaseBenchmarkWorkload( $medianRpm = releasePercentile($rpms, 50); $spread = $medianRpm > 0 - ? ((max($rpms) - min($rpms)) / $medianRpm) * 100 + ? ((max($rpms) - min($rpms)) / $medianRpm) * 100.0 : 100.0; return [ @@ -175,7 +185,7 @@ function releaseBenchmarkWorkload( 'error_rate' => $attempted > 0 ? $failed / $attempted : 0.0, 'latency_ms' => [ 'minimum' => $latencies === [] ? null : min($latencies), - 'average' => $latencies === [] ? null : array_sum($latencies) / count($latencies), + 'average' => $latencies === [] ? null : array_sum($latencies) / (float) count($latencies), 'p50' => releasePercentile($latencies, 50), 'p95' => releasePercentile($latencies, 95), 'p99' => releasePercentile($latencies, 99), @@ -183,12 +193,12 @@ function releaseBenchmarkWorkload( ], 'cpu' => [ 'average_percent' => releaseAverage($cpuAverages), - 'peak_percent' => $cpuPeaks === [] ? null : max($cpuPeaks), + 'peak_percent' => max($cpuPeaks), ], 'memory' => [ 'average_mb' => releaseAverage($memoryAverages), - 'peak_mb' => $memoryPeaks === [] ? null : max($memoryPeaks), - 'growth_mb' => $memoryGrowth === [] ? null : max($memoryGrowth), + 'peak_mb' => max($memoryPeaks), + 'growth_mb' => max($memoryGrowth), ], 'stability' => [ 'status' => $failed === 0 && $spread <= RELEASE_STABILITY_SPREAD_PERCENT @@ -213,6 +223,9 @@ function releaseBenchmarkWorkload( * memory_peak_mb:float, * memory_growth_mb:float * } + * @throws RuntimeException + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\InvalidArgumentException */ function releaseBenchmarkTrial( string $root, @@ -232,8 +245,9 @@ function releaseBenchmarkTrial( 'opcache.enable_cli=1', '-d', 'opcache.jit=0', + '-d', + 'auto_prepend_file=' . $root . '/vendor/autoload.php', $worker, - $root, $workload, (string) $operations, (string) $warmup, @@ -258,7 +272,7 @@ function releaseBenchmarkTrial( throw new RuntimeException('Release benchmark worker returned invalid JSON.'); } - $results[] = $decoded; + $results[] = releaseValidateWorkerResult($decoded); } $elapsedSeconds = max((hrtime(true) - $startedAt) / 1_000_000_000, 0.000001); @@ -273,18 +287,15 @@ function releaseBenchmarkTrial( $memoryPeak = []; foreach ($results as $result) { - $attempted += (int) ($result['attempted'] ?? 0); - $successful += (int) ($result['successful'] ?? 0); - $failed += (int) ($result['failed'] ?? 0); - $latencies = [ - ...$latencies, - ...array_map('floatval', is_array($result['latencies_ms'] ?? null) ? $result['latencies_ms'] : []), - ]; - $cpuSeconds += (float) ($result['cpu_seconds'] ?? 0.0); - $cpuPeaks[] = (float) ($result['cpu_percent'] ?? 0.0); - $memoryInitial[] = (float) ($result['memory_initial_mb'] ?? 0.0); - $memoryFinal[] = (float) ($result['memory_final_mb'] ?? 0.0); - $memoryPeak[] = (float) ($result['memory_peak_mb'] ?? 0.0); + $attempted += $result['attempted']; + $successful += $result['successful']; + $failed += $result['failed']; + $latencies = [...$latencies, ...$result['latencies_ms']]; + $cpuSeconds += $result['cpu_seconds']; + $cpuPeaks[] = $result['cpu_percent']; + $memoryInitial[] = $result['memory_initial_mb']; + $memoryFinal[] = $result['memory_final_mb']; + $memoryPeak[] = $result['memory_peak_mb']; } $averageInitial = releaseAverage($memoryInitial) ?? 0.0; @@ -294,9 +305,9 @@ function releaseBenchmarkTrial( 'attempted' => $attempted, 'successful' => $successful, 'failed' => $failed, - 'successful_rpm' => ($successful / $elapsedSeconds) * 60, + 'successful_rpm' => ((float) $successful / (float) $elapsedSeconds) * 60.0, 'latencies_ms' => $latencies, - 'cpu_average_percent' => ($cpuSeconds / $elapsedSeconds) * 100, + 'cpu_average_percent' => ($cpuSeconds / (float) $elapsedSeconds) * 100.0, 'cpu_peak_percent' => $cpuPeaks === [] ? 0.0 : max($cpuPeaks), 'memory_average_mb' => $averageFinal, 'memory_peak_mb' => $memoryPeak === [] ? 0.0 : max($memoryPeak), @@ -304,6 +315,50 @@ function releaseBenchmarkTrial( ]; } +/** + * @param array $result + * @return array{attempted:int,successful:int,failed:int,latencies_ms:list,cpu_seconds:float,cpu_percent:float,memory_initial_mb:float,memory_final_mb:float,memory_peak_mb:float} + * @throws RuntimeException + */ +function releaseValidateWorkerResult(array $result): array +{ + $attempted = $result['attempted'] ?? null; + $successful = $result['successful'] ?? null; + $failed = $result['failed'] ?? null; + $rawLatencies = $result['latencies_ms'] ?? null; + if (!is_int($attempted) || !is_int($successful) || !is_int($failed) + || $attempted < 0 || $successful < 0 || $failed < 0 + || $attempted !== $successful + $failed + || !is_array($rawLatencies) || !array_is_list($rawLatencies) + || count($rawLatencies) !== $attempted + ) { + throw new RuntimeException('Release benchmark worker returned invalid operation counts or latency samples.'); + } + $latencies = array_map(releaseMetric(...), $rawLatencies); + + return [ + 'attempted' => $attempted, + 'successful' => $successful, + 'failed' => $failed, + 'latencies_ms' => $latencies, + 'cpu_seconds' => releaseMetric($result['cpu_seconds'] ?? null), + 'cpu_percent' => releaseMetric($result['cpu_percent'] ?? null), + 'memory_initial_mb' => releaseMetric($result['memory_initial_mb'] ?? null), + 'memory_final_mb' => releaseMetric($result['memory_final_mb'] ?? null), + 'memory_peak_mb' => releaseMetric($result['memory_peak_mb'] ?? null), + ]; +} + +/** @throws RuntimeException */ +function releaseMetric(mixed $value): float +{ + if ((!is_int($value) && !is_float($value)) || !is_finite((float) $value) || $value < 0) { + throw new RuntimeException('Release benchmark worker returned an invalid numeric metric.'); + } + + return (float) $value; +} + /** * @return array */ @@ -337,7 +392,7 @@ function releaseEnvironment(): array 'php_sapi' => PHP_SAPI, 'operating_system' => $operatingSystem, 'cpu_model' => $cpuModel, - 'memory_limit' => (string) ini_get('memory_limit'), + 'memory_limit' => ini_get('memory_limit'), 'opcache' => 'cli-enabled', 'jit' => false, 'xdebug' => extension_loaded('xdebug'), @@ -346,11 +401,13 @@ function releaseEnvironment(): array ]; } +/** @param list $values */ function releaseAverage(array $values): ?float { - return $values === [] ? null : array_sum($values) / count($values); + return $values === [] ? null : array_sum($values) / (float) count($values); } +/** @param list $values */ function releasePercentile(array $values, int $percentile): ?float { if ($values === []) { @@ -358,12 +415,21 @@ function releasePercentile(array $values, int $percentile): ?float } sort($values, SORT_NUMERIC); - $index = (int) ceil(($percentile / 100) * count($values)) - 1; + $index = (int) ceil(((float) $percentile / 100.0) * (float) count($values)) - 1; $index = max(0, min(count($values) - 1, $index)); - return (float) $values[$index]; + return $values[$index]; } +/** + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\ProcessStartFailedException + * @throws \Symfony\Component\Process\Exception\RuntimeException + * @throws \Symfony\Component\Process\Exception\ProcessTimedOutException + * @throws \Symfony\Component\Process\Exception\ProcessSignaledException + * @throws \Symfony\Component\Process\Exception\InvalidArgumentException + * @throws RuntimeException + */ function releasePrepareBaseline(string $root, string $baselineDirectory): void { releaseRemoveBaseline($root, $baselineDirectory); @@ -396,6 +462,16 @@ function releasePrepareBaseline(string $root, string $baselineDirectory): void ], $baselineDirectory, 240); } +/** + * @param list $command + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\InvalidArgumentException + * @throws \Symfony\Component\Process\Exception\ProcessStartFailedException + * @throws \Symfony\Component\Process\Exception\RuntimeException + * @throws \Symfony\Component\Process\Exception\ProcessTimedOutException + * @throws \Symfony\Component\Process\Exception\ProcessSignaledException + * @throws \RuntimeException + */ function releaseProcess(array $command, string $workingDirectory, int $timeout = 120): string { $process = new Process($command, $workingDirectory, ['XDEBUG_MODE' => 'off']); @@ -413,6 +489,14 @@ function releaseProcess(array $command, string $workingDirectory, int $timeout = return $process->getOutput(); } +/** + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\InvalidArgumentException + * @throws \Symfony\Component\Process\Exception\ProcessStartFailedException + * @throws \Symfony\Component\Process\Exception\RuntimeException + * @throws \Symfony\Component\Process\Exception\ProcessTimedOutException + * @throws \Symfony\Component\Process\Exception\ProcessSignaledException + */ function releaseRemoveBaseline(string $root, string $baselineDirectory): void { if (!is_dir($baselineDirectory)) { @@ -426,14 +510,19 @@ function releaseRemoveBaseline(string $root, string $baselineDirectory): void $remove->setTimeout(60); $remove->run(); - if (is_dir($baselineDirectory)) { - releaseRemoveDirectory($baselineDirectory); - } + clearstatcache(true, $baselineDirectory); + releaseRemoveDirectory($baselineDirectory); } function releaseRemoveDirectory(string $directory): void { - foreach (scandir($directory) ?: [] as $entry) { + if (!is_dir($directory)) { + return; + } + + $entries = scandir($directory); + + foreach ($entries === false ? [] : $entries as $entry) { if ($entry === '.' || $entry === '..') { continue; } @@ -451,6 +540,7 @@ function releaseRemoveDirectory(string $directory): void /** * @param array $document + * @throws \RuntimeException */ function releaseWriteJson(string $path, array $document): void { diff --git a/benchmarks/release-workload.php b/benchmarks/release-workload.php index 3bfd380..24af896 100644 --- a/benchmarks/release-workload.php +++ b/benchmarks/release-workload.php @@ -12,16 +12,19 @@ use Infocyph\ArrayKit\Config\LazyFileConfig; use RuntimeException; -[$script, $root, $workload, $operations, $warmup] = $argv + [null, null, null, null, null]; -unset($script); +$workload = $argv[1] ?? null; +$operations = $argv[2] ?? null; +$warmup = $argv[3] ?? null; -if (!is_string($root) || !is_string($workload) || !is_numeric($operations) || !is_numeric($warmup)) { +if (!is_string($workload) || !is_numeric($operations) || !is_numeric($warmup)) { throw new RuntimeException( - 'Usage: release-workload.php ', + 'Usage: php -d auto_prepend_file= release-workload.php ', ); } -require rtrim($root, DIRECTORY_SEPARATOR) . '/vendor/autoload.php'; +if (!class_exists(ArrayMulti::class)) { + throw new RuntimeException('Benchmark runner must bootstrap ArrayKit before launching this worker.'); +} $operations = max(1, (int) $operations); $warmup = max(0, (int) $warmup); @@ -77,7 +80,7 @@ 'elapsed_seconds' => $elapsedSeconds, 'latencies_ms' => $latencies, 'cpu_seconds' => max(0.0, $cpuSeconds), - 'cpu_percent' => max(0.0, ($cpuSeconds / $elapsedSeconds) * 100), + 'cpu_percent' => max(0.0, ($cpuSeconds / (float) $elapsedSeconds) * 100.0), 'memory_initial_mb' => $memoryBefore / 1_048_576, 'memory_final_mb' => $memoryAfter / 1_048_576, 'memory_peak_mb' => memory_get_peak_usage(true) / 1_048_576, @@ -110,18 +113,31 @@ function releaseArrayQueryWorkload(): \Closure }; } -function releaseCpuSeconds(array $usage): float +/** + * @param array|false $usage + * @throws RuntimeException + */ +function releaseCpuSeconds(array|false $usage): float { - $user = ((int) ($usage['ru_utime.tv_sec'] ?? 0)) - + (((int) ($usage['ru_utime.tv_usec'] ?? 0)) / 1_000_000); - $system = ((int) ($usage['ru_stime.tv_sec'] ?? 0)) - + (((int) ($usage['ru_stime.tv_usec'] ?? 0)) / 1_000_000); + if ($usage === false) { + throw new RuntimeException('Unable to read process CPU usage.'); + } + $userSeconds = $usage['ru_utime.tv_sec'] ?? null; + $userMicros = $usage['ru_utime.tv_usec'] ?? null; + $systemSeconds = $usage['ru_stime.tv_sec'] ?? null; + $systemMicros = $usage['ru_stime.tv_usec'] ?? null; + if (!is_int($userSeconds) || !is_int($userMicros) || !is_int($systemSeconds) || !is_int($systemMicros)) { + throw new RuntimeException('Invalid process CPU usage.'); + } + $user = (float) $userSeconds + ((float) $userMicros / 1_000_000.0); + $system = (float) $systemSeconds + ((float) $systemMicros / 1_000_000.0); return $user + $system; } /** * @return \Closure(): void + * @throws \RuntimeException */ function releaseConfigSnapshotWorkload(): \Closure { @@ -149,6 +165,7 @@ function releaseConfigSnapshotWorkload(): \Closure /** * @return \Closure(): void + * @throws \RuntimeException */ function releaseDotConfigWorkload(): \Closure { @@ -182,7 +199,7 @@ function releaseDotConfigWorkload(): \Closure ); if ( - count($ids) !== 64 + !is_array($ids) || count($ids) !== 64 || $flat !== [1, 2, 3] || $config->get('app.nested.value') !== 42 ) { @@ -214,6 +231,7 @@ function releaseLazyArrayWorkload(): \Closure /** * @param list $temporaryDirectories * @return \Closure(): void + * @throws RuntimeException */ function releaseLazyFileColdWorkload(array &$temporaryDirectories): \Closure { @@ -234,6 +252,8 @@ function releaseLazyFileColdWorkload(array &$temporaryDirectories): \Closure /** * @param list $temporaryDirectories * @return \Closure(): void + * @throws \RuntimeException + * @throws \InvalidArgumentException */ function releaseLazyFileGeneratedWorkload(array &$temporaryDirectories): \Closure { @@ -257,6 +277,7 @@ function releaseLazyFileGeneratedWorkload(array &$temporaryDirectories): \Closur /** * @param list $temporaryDirectories * @return array{0:string,1:string} + * @throws \RuntimeException */ function releaseLazyFileDirectories(array &$temporaryDirectories): array { @@ -285,7 +306,9 @@ function releaseRemoveDirectory(string $directory): void return; } - foreach (scandir($directory) ?: [] as $entry) { + $entries = scandir($directory); + + foreach ($entries === false ? [] : $entries as $entry) { if ($entry === '.' || $entry === '..') { continue; } diff --git a/composer.json b/composer.json index 12fa277..98ab303 100644 --- a/composer.json +++ b/composer.json @@ -20,14 +20,18 @@ ], "require": { "php": ">=8.4", - "ext-hash": "*" + "ext-filter": "*", + "ext-hash": "*", + "ext-tokenizer": "*" }, "require-dev": { + "ext-intl": "*", "infocyph/phpforge": "dev-main@dev", - "infocyph/runwire": "^3.0" + "infocyph/runwire": "^4.0.1" }, "suggest": { - "infocyph/runwire": "Optional LazyCollection cancellation and cooperative-yield integration; integration tested against Runwire 3.0." + "ext-intl": "Required for locale-aware sorting outside the C/POSIX collation locale.", + "infocyph/runwire": "Optional LazyCollection cancellation and cooperative-yield integration; integration targets Runwire 4.0.1 or later in the 4.x series." }, "minimum-stability": "stable", "prefer-stable": true, diff --git a/docs/array-helpers.rst b/docs/array-helpers.rst index 07cc5d8..a1b1cdb7 100644 --- a/docs/array-helpers.rst +++ b/docs/array-helpers.rst @@ -356,6 +356,14 @@ Behavior Notes - ``ArrayMulti::whereIn()`` / ``whereNotIn()`` treat ``null`` as a real value when the key exists. - ``ArrayMulti::where()`` / ``firstWhere()`` distinguish explicit ``null`` from the two-argument shorthand form. +- Strict ``duplicates()`` reports repeated ``null`` separately from ``false``, + ``0`` and empty strings. +- Numeric sums preserve native integer precision until PHP promotes the result + to a float. Mixed numeric types follow native PHP numeric promotion. +- Use ``ArrayMulti::SORT_LOCALE`` instead of PHP's deprecated locale sort flag. + The legacy integer value (5) is unchanged. C/POSIX collation uses bytewise + comparisons; other locales use ICU via ``ext-intl`` and can differ from + historical libc ordering. Missing ICU support fails explicitly for non-C locales. - ``ArrayMulti::flatten($array, 0)`` returns unchanged top-level values. - Use ``depthGuarded()``, ``flattenGuarded()``, and ``sortRecursiveGuarded()`` when processing untrusted/deep inputs. - Guarded recursive sorting accepts scalar/array values only. It refuses object values, including objects nested inside arrays, because PHP sorting may compare arbitrarily deep public object graphs outside a traversal budget. Normalize object data before guarded sorting, or use ordinary ``sortRecursive()`` only for trusted inputs. @@ -367,3 +375,29 @@ Behavior Notes - ``BaseArrayHelper::random()`` throws ``InvalidArgumentException`` when requested count exceeds array size. - Recursive/reference-containing arrays are outside the supported input contract for unguarded equality, fingerprint, flatten, and recursive-sort helpers. + +Locale-Aware Sorting +-------------------- + +Use the active ``LC_COLLATE`` locale and ArrayKit's locale sort option: + +.. code-block:: php + + use Infocyph\ArrayKit\Array\ArrayMulti; + + $rows = [['name' => 'Zoe'], ['name' => 'Ada']]; + $sorted = ArrayMulti::sortBy($rows, 'name', options: ArrayMulti::SORT_LOCALE); + +The option also works with ``sortByDesc()``, individual ``sortByMany()`` +criteria, ``sortRecursive()`` and ``sortRecursiveGuarded()``. Recursive +sorting orders associative keys and list values. Locale comparison failures +raise ``RuntimeException``. Configure the process locale during bootstrap; +avoid changing global locale state per request in persistent workers. + +Randomized and Reproducible Shuffling +------------------------------------- + +``ArraySingle::shuffle($values)`` uses PHP's secure randomizer. Passing an +integer seed instead selects an isolated Xoshiro256StarStar engine for +reproducible, non-cryptographic shuffles. Do not use seeded output for secrets. +The exact seeded permutation is not stable across engine changes. diff --git a/docs/collection.rst b/docs/collection.rst index bd931e2..502f142 100644 --- a/docs/collection.rst +++ b/docs/collection.rst @@ -310,10 +310,10 @@ renewable sources when each traversal can create a fresh iterable. Optional Runwire Binding ------------------------ -Runwire is optional. ArrayKit 5.3.2 targets Runwire 3.0 and tests the -integration on PHP 8.4 and 8.5. Ordinary ``LazyCollection`` use does not -require or load Runwire. When a host already owns a Runwire runtime, pass those exact instances -to ``withRunwire()``: +Runwire is optional. ArrayKit 5.4 targets Runwire ``^4.0.1``; exact 4.0.1 +is tested on PHP 8.4, 8.5 and 8.6. Ordinary ``LazyCollection`` use does not +require or load Runwire. When a host already owns a compatible Runwire runtime, +pass those exact instances to ``withRunwire()``: .. code-block:: php diff --git a/docs/config-layering.rst b/docs/config-layering.rst index 50ac276..a5e70c5 100644 --- a/docs/config-layering.rst +++ b/docs/config-layering.rst @@ -77,7 +77,9 @@ Resilient Lazy Source Cache ``ResilientLazyFileConfig`` treats generated namespace-cache corruption as a cache miss and retries the authoritative source namespace. Invalid source files still fail normally; resilience applies only to disposable generated cache -artifacts. +artifacts. A generated namespace file that becomes unreadable after resolution +is also treated as a cache miss; an unreadable authoritative source still +raises ``UnexpectedValueException``. Malformed generated namespace files and invalid ``.arraykit-flat.php`` indexes are disposable cache artifacts. Generated files live in immutable generations diff --git a/docs/config.rst b/docs/config.rst index dd7378f..44d60fd 100644 --- a/docs/config.rst +++ b/docs/config.rst @@ -261,6 +261,11 @@ Use nullable/default-friendly typed getters when you want soft type access: $cache = $config->getArray('cache', []); $mode = $config->getEnum('app.mode', AppMode::class, AppMode::Prod); +``getEnum()`` requires the exact backing scalar type: an integer-backed enum +will not accept a numeric string, and a string-backed enum will not accept an +integer. Missing or incompatible values return the supplied default (or +``null``). A nonexistent enum class raises ``InvalidArgumentException``. + Writing Values -------------- diff --git a/docs/index.rst b/docs/index.rst index 892dde3..75da4c5 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -29,6 +29,7 @@ Contents lifecycle traits-and-helpers migration + release-5.4.0 release-5.3.0 rule-reference diff --git a/docs/installation.rst b/docs/installation.rst index 42d9c27..92dc1d5 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -12,12 +12,29 @@ Requirements ArrayKit has the following requirements: -* **PHP 8.4+** -* **ext-hash** (used by collision-safe strict value-set acceleration) +* **PHP 8.4+** (CI matrix: PHP 8.4, 8.5 and 8.6) +* **ext-filter**, **ext-hash** (strict value-set acceleration) and **ext-tokenizer** + +For locale-aware sorting outside the C/POSIX collation locale, install the optional +``ext-intl`` extension. Autoload is PSR-4 based and loads namespaced helper functions from ``Infocyph\ArrayKit\*`` by default. +Optional Runwire integration +---------------------------- + +ArrayKit 5.4 targets Runwire ``^4.0.1``. The integration matrix tests exact +Runwire 4.0.1 on PHP 8.4, 8.5 and 8.6. Only applications that bind a Runwire +runtime to ``LazyCollection`` need to install Runwire explicitly: + +.. code-block:: bash + + composer require 'infocyph/runwire:^4.0.1' + +See :doc:`collection` for host-owned runtime and request binding. No runtime +is created by ArrayKit. + Optional global helpers ----------------------- diff --git a/docs/lazy-config.rst b/docs/lazy-config.rst index b449c01..2a97053 100644 --- a/docs/lazy-config.rst +++ b/docs/lazy-config.rst @@ -183,7 +183,7 @@ Read from the warmed cache on later requests: // Exact scalar reads can come from the active .arraykit-flat.php without loading db.php. $host = $config->get('db.host'); - // Structural reads load bootstrap/cache/config/db.php when available. + // Structural reads load db.php from the active cache generation when available. $database = $config->get('db'); Important lazy-cache details: @@ -193,6 +193,10 @@ Important lazy-cache details: - Source-backed warm-up rereads current source/environment values; explicit in-memory runtime overrides remain authoritative. - ``flushNamespaceCache()`` publishes a generation with the selected cached namespaces removed; unrelated root files are preserved. - Namespace and generated cache PHP files are trusted deployment-owned inputs, not a sandbox boundary. +- A resolved namespace file that is no longer readable raises + ``UnexpectedValueException`` rather than being marked loaded. A file that + returns a non-array also raises this exception. For generated-cache fallback, + see :doc:`config-layering`. - Prefer deployment/bootstrap/admin warm-up, not request-time regeneration. - Retire old generation directories only after workers that may still reference them have been replaced. diff --git a/docs/migration.rst b/docs/migration.rst index 73c4a20..dff1b67 100644 --- a/docs/migration.rst +++ b/docs/migration.rst @@ -3,6 +3,32 @@ Migration and Compatibility This page highlights behavior and API additions that may affect usage patterns. +5.4 Upgrade +----------- + +The 5.4 release line retains PHP 8.4 as its minimum and tests PHP 8.4, 8.5 +and 8.6. Before upgrading from 5.3.2: + +1. Ensure ``ext-filter``, ``ext-hash`` and ``ext-tokenizer`` are installed. +2. If using optional Runwire bindings, upgrade the host to Runwire ``^4.0.1``. + Exact 4.0.1 is tested; older Runwire lines are not qualified by this release. +3. Replace ``SORT_LOCALE_STRING`` with ``ArrayMulti::SORT_LOCALE`` (integer + value 5). C/POSIX collation uses bytewise comparison; other locales require + ``ext-intl`` and use ICU, whose order can differ from libc. +4. Review any fixtures or application logic that depend on a particular seeded + shuffle permutation. The deterministic engine changed from Mt19937 to + Xoshiro256StarStar; identical seeds remain reproducible within the engine. + Unseeded shuffles use secure randomness and do not advance global Mt19937. + +Strict duplicate detection now reports repeated ``null`` values. Numeric +accumulation retains integer precision where PHP can represent the result; +backed enum getters reject mismatched scalar types. A namespace file that +becomes unreadable after resolution raises ``UnexpectedValueException`` +without marking that namespace loaded. Resilient generated-cache fallback +remains available through ``ResilientLazyFileConfig``. + +See :doc:`release-5.4.0` for the release summary and verification limits. + 5.3 Upgrade ----------- @@ -45,9 +71,9 @@ reference aliasing, and lazy config refresh against newly published source generations. It also fixes numeric namespace discovery, numeric and enum edge cases, median overflow and private pipeline method dispatch. -Optional Runwire integration is qualified for Runwire 3.0 only. Production -installation does not require Runwire; applications that explicitly bind a -Runwire runtime must use a compatible 3.0 host instance. +The 5.3.2 maintenance line qualified optional Runwire integration against +Runwire 3.0. Production installation did not require Runwire. For the current +compatibility target, see the 5.4 upgrade notes above. Normal array/snapshot APIs retain their signatures. Snapshotting now visits nested arrays to detach external references; object values remain shallow. @@ -93,8 +119,9 @@ Behavior Changes - ``wrap()`` now treats only ``null`` as absence. Falsey non-null scalars are wrapped instead of being discarded. -- Seeded ``ArraySingle::shuffle()`` uses an isolated randomizer and no longer - reseeds or advances PHP's global Mersenne Twister state. +- Seeded ``ArraySingle::shuffle()`` uses an isolated randomizer rather than + reseeding PHP's global Mersenne Twister state. See the 5.4 upgrade notes + for the subsequent engine and unseeded behavior changes. - ``groupBy()``, ``keyBy()`` / ``indexBy()``, and ``countBy()`` skip rows whose derived field is missing. Present values must produce integer or string keys; ``null`` and other invalid key types now throw ``InvalidArgumentException``. diff --git a/docs/release-5.4.0.rst b/docs/release-5.4.0.rst new file mode 100644 index 0000000..64c17aa --- /dev/null +++ b/docs/release-5.4.0.rst @@ -0,0 +1,55 @@ +ArrayKit 5.4.0 +============== + +Highlights +---------- + +- Optional Runwire integration targets ``^4.0.1``, with exact 4.0.1 + exercised on PHP 8.4, 8.5 and 8.6. +- PHP 8.4 remains the minimum; all three PHP versions are included in the + quality and integration matrices. +- Locale-aware sorting no longer relies on deprecated PHP locale APIs. +- Strict duplicate detection, numeric precision, lazy namespace loading and + deterministic shuffling have additional regression coverage. + +Compatibility and Upgrade +------------------------- + +Install the required ``ext-filter``, ``ext-hash`` and ``ext-tokenizer`` +extensions. Install optional ``ext-intl`` if using non-C locale sorting. +Runwire remains optional for consumers; ordinary synchronous use does not +need a Runwire installation. + +Replace the deprecated locale sort flag with ``ArrayMulti::SORT_LOCALE`` +(value 5). ICU collation for non-C locales can differ from earlier libc +ordering. Seeded shuffles use Xoshiro256StarStar instead of Mt19937, so exact +permutations from older releases are not guaranteed; unseeded shuffling uses +secure randomness. Seeded shuffles are not suitable for secrets. + +See :doc:`migration`, :doc:`installation` and :doc:`array-helpers`. + +Correctness and Lifecycle +------------------------- + +Strict duplicates include repeated null values without merging distinct +types. Integer sums retain native precision where representable; enum getters +preserve strict backing-type matching. A resolved configuration namespace +that becomes unreadable fails without marking the namespace loaded. +Generated-cache resilience remains opt-in via ``ResilientLazyFileConfig``. + +ArrayKit forwards host-owned Runwire request and coroutine bindings; it does +not manage a runtime or complete a host request. See :doc:`collection`, +:doc:`lazy-config` and :doc:`config-layering`. + +Verification +------------ + +The release candidate passed PHPStan, Psalm, both dependency-resolution QA +matrices, benchmark result-contract checks, documentation and the exact +Runwire integration matrix. Two 300-second persistent-worker soaks passed +the 16 MiB memory-growth limit. Hosted benchmark results do not certify the +strict 2% regression budget because a stable benchmark environment was not +asserted. + +The release qualification applies to the exercised configurations and +workloads, not every possible application or deployment. diff --git a/docs/rule-reference.rst b/docs/rule-reference.rst index e75b299..c3ebaac 100644 --- a/docs/rule-reference.rst +++ b/docs/rule-reference.rst @@ -185,6 +185,8 @@ ArraySharedOps (Internal) .. code-block:: php + public static function decrementDepth(float|int $depth): float|int + public static function each(array $array, callable $callback): array public static function every(array $array, callable $callback): bool public static function partition(array $array, callable $callback): array @@ -256,6 +258,9 @@ ArraySingle ArrayMulti ---------------------------------- +The public ``ArrayMulti::SORT_LOCALE`` constant has integer value 5. Use it +for locale-aware sorting; see :doc:`array-helpers` for ICU requirements. + .. code-block:: php public static function only(array $array, array|string $keys): array diff --git a/src/Array/ArrayMulti.php b/src/Array/ArrayMulti.php index 049ba88..3b3c3fc 100644 --- a/src/Array/ArrayMulti.php +++ b/src/Array/ArrayMulti.php @@ -7,6 +7,7 @@ use Infocyph\ArrayKit\Array\Concerns\ArrayMultiQuerySortTrait; use InvalidArgumentException; +/** @api */ class ArrayMulti { use ArrayMultiQuerySortTrait; @@ -14,6 +15,7 @@ class ArrayMulti /** * @param array $array * @return array + * @throws \InvalidArgumentException */ public static function chunk(array $array, int $size, bool $preserveKeys = false): array { @@ -68,6 +70,7 @@ public static function depth(array $array): int * Safe depth calculation with recursion/node guards. * * @param array $array + * @throws \RuntimeException */ public static function depthGuarded( array $array, @@ -167,6 +170,7 @@ public static function flattenByKey(array $array): array * * @param array $array * @return array + * @throws \RuntimeException */ public static function flattenGuarded( array $array, @@ -230,7 +234,6 @@ public static function mergeRecursiveDistinct(array $base, array $overrides): ar public static function only(array $array, array|string $keys): array { $result = []; - /** @var array $pickKeys */ $pickKeys = (array) $keys; $pick = array_flip($pickKeys); @@ -257,7 +260,7 @@ public static function overlay(array $base, array $overlay): array /** * @param array $array - * @return array + * @return array{array, array} */ public static function partition(array $array, callable $callback): array { @@ -283,6 +286,7 @@ public static function reduce(array $array, callable $callback, mixed $initial = * @param array $array * @param array|callable $mapper * @return array + * @throws \InvalidArgumentException */ public static function rekey(array $array, array|callable $mapper): array { @@ -331,6 +335,7 @@ public static function skipWhile(array $array, callable $callback): array /** * @param array $matrix * @return array + * @throws \InvalidArgumentException */ public static function transpose(array $matrix): array { @@ -378,6 +383,7 @@ public static function values(array $array): array /** * @phpstan-impure + * @throws \RuntimeException */ private static function consumeTraversalNode( int &$visitedNodes, @@ -414,6 +420,7 @@ private static function flattenByKeyInto(array $array, array &$results): void /** * @param array $array * @return array + * @throws \RuntimeException */ private static function flattenIntoGuarded( array $array, @@ -460,6 +467,7 @@ private static function flattenIntoGuarded( /** * @param array $item * @param array $result + * @throws \RuntimeException */ private static function flattenNestedGuarded( array $item, @@ -487,7 +495,7 @@ private static function flattenNestedGuarded( foreach (self::flattenIntoGuarded( $item, - $depth - 1, + ArraySharedOps::decrementDepth($depth), $currentDepth + 1, $visitedNodes, $maxDepth, @@ -501,6 +509,7 @@ private static function flattenNestedGuarded( /** * @param array $item * @param array $result + * @throws \RuntimeException */ private static function flattenOneLevelGuarded( array $item, @@ -534,9 +543,12 @@ private static function flattenOneLevelGuarded( */ private static function flattenValues(array $array, float|int $depth): array { - return $depth === 1 ? array_values($array) : static::flatten($array, $depth - 1); + return $depth === 1 ? array_values($array) : static::flatten($array, ArraySharedOps::decrementDepth($depth)); } + /** + * @throws \RuntimeException + */ private static function handleTraversalLimit(bool $throwOnTooDeep, string $message): void { if ($throwOnTooDeep) { @@ -562,6 +574,7 @@ private static function measureDepth(array $array): int /** * @param array $array + * @throws \RuntimeException */ private static function measureDepthGuarded( array $array, @@ -608,6 +621,9 @@ private static function traversalBudgetExhausted(int $visitedNodes, int $maxNode return $maxNodes > 0 && $visitedNodes >= $maxNodes; } + /** + * @throws \RuntimeException + */ private static function traversalDepthAllowed( int $currentDepth, int $maxDepth, @@ -625,6 +641,7 @@ private static function traversalDepthAllowed( /** * @param list $keys * @return array + * @throws \InvalidArgumentException */ private static function validatedMatrixRow(mixed $row, array $keys): array { diff --git a/src/Array/ArrayShape.php b/src/Array/ArrayShape.php index 7e1a10b..f111de8 100644 --- a/src/Array/ArrayShape.php +++ b/src/Array/ArrayShape.php @@ -14,6 +14,7 @@ final class ArrayShape * @param array $row * @param array $shape * @return array + * @throws \InvalidArgumentException */ public static function require(array $row, array $shape): array { diff --git a/src/Array/ArraySharedOps.php b/src/Array/ArraySharedOps.php index 72f9097..018a8f9 100644 --- a/src/Array/ArraySharedOps.php +++ b/src/Array/ArraySharedOps.php @@ -26,12 +26,19 @@ public static function asString(mixed $value): string } if (is_array($value)) { - return json_encode($value) ?: ''; + $encoded = json_encode($value); + + return $encoded === false ? '' : $encoded; } return ''; } + public static function decrementDepth(float|int $depth): float|int + { + return is_int($depth) ? $depth - 1 : $depth - 1.0; + } + /** * @param array $array * @return array @@ -66,7 +73,7 @@ public static function normalizeArrayKey(mixed $value): int|string /** * @param array $array - * @return array + * @return array{array, array} */ public static function partition(array $array, callable $callback): array { @@ -99,7 +106,7 @@ public static function skip(array $array, int $count): array */ public static function skipUntil(array $array, callable $callback): array { - return self::skipWhile($array, fn($value, $key) => !$callback($value, $key)); + return self::skipWhile($array, static fn(mixed $value, int|string $key): bool => !$callback($value, $key)); } /** diff --git a/src/Array/ArraySingle.php b/src/Array/ArraySingle.php index fa7c0ac..413a1af 100644 --- a/src/Array/ArraySingle.php +++ b/src/Array/ArraySingle.php @@ -5,9 +5,10 @@ namespace Infocyph\ArrayKit\Array; use InvalidArgumentException; -use Random\Engine\Mt19937; +use Random\Engine\Xoshiro256StarStar; use Random\Randomizer; +/** @api */ class ArraySingle { /** @@ -33,6 +34,7 @@ public static function avg(array $array): float|int * @param int $size The size of each chunk. * @param bool $preserveKeys Whether to preserve the keys in the chunks. * @return array An array of arrays, each representing a chunk of the original array. + * @throws \InvalidArgumentException */ public static function chunk(array $array, int $size, bool $preserveKeys = false): array { @@ -52,6 +54,7 @@ public static function chunk(array $array, int $size, bool $preserveKeys = false * @param array $keys The array of keys. * @param array $values The array of values. * @return array The combined array. + * @throws \InvalidArgumentException */ public static function combine(array $keys, array $values): array { @@ -127,6 +130,7 @@ public static function containsAny(array $array, array $needles, bool $strict = * * @param array $array * @return array + * @throws \InvalidArgumentException */ public static function countBy(array $array, ?callable $by = null): array { @@ -204,7 +208,6 @@ public static function every(array $array, callable $callback): bool */ public static function except(array $array, array|string $keys): array { - /** @var array $keyList */ $keyList = (array) $keys; return array_diff_key($array, array_flip($keyList)); @@ -440,9 +443,13 @@ public static function median(array $array): float|int $left = $values[$mid - 1]; $right = $values[$mid]; - $sum = $left + $right; + $sum = ArraySingleOps::add($left, $right); - return is_finite((float) $sum) ? $sum / 2 : $left / 2 + $right / 2; + if (!is_finite((float) $sum)) { + return (float) $left / 2.0 + (float) $right / 2.0; + } + + return is_int($sum) ? $sum / 2 : $sum / 2.0; } /** @@ -504,7 +511,7 @@ public static function mode(array $array): array */ public static function negative(array $array): array { - return static::where($array, static fn($value) => is_numeric($value) && $value < 0); + return static::where($array, static fn(mixed $value): bool => is_numeric($value) && $value < 0); } /** @@ -566,7 +573,6 @@ public static function nth(array $array, int $step, int $offset = 0): array */ public static function only(array $array, array|string $keys): array { - /** @var array $keyList */ $keyList = (array) $keys; return array_intersect_key($array, array_flip($keyList)); @@ -637,7 +643,7 @@ public static function partition(array $array, callable $callback): array */ public static function positive(array $array): array { - return static::where($array, static fn($value) => is_numeric($value) && $value > 0); + return static::where($array, static fn(mixed $value): bool => is_numeric($value) && $value > 0); } /** @@ -658,7 +664,7 @@ public static function prepend(array $array, mixed $value, mixed $key = null): a array_unshift($array, $value); } else { if (!is_int($key) && !is_string($key)) { - $key = self::normalizeArrayKey($key); + $key = ArraySharedOps::normalizeArrayKey($key); } $array = [$key => $value] + $array; @@ -717,6 +723,7 @@ public static function reject(array $array, mixed $callback = true): array * @param array $array * @param array|callable $mapper * @return array + * @throws \InvalidArgumentException */ public static function rekey(array $array, array|callable $mapper): array { @@ -796,20 +803,15 @@ public static function separate(array $array): array } /** - * Shuffle values, using isolated deterministic state when a seed is given. + * Shuffle values with a secure randomizer by default. + * A supplied seed selects an isolated, reproducible, non-cryptographic engine. * * @param array $array * @return array */ public static function shuffle(array $array, ?int $seed = null): array { - if ($seed === null) { - shuffle($array); - - return $array; - } - - return new Randomizer(new Mt19937($seed))->shuffleArray($array); + return new Randomizer($seed === null ? null : new Xoshiro256StarStar($seed))->shuffleArray($array); } /** @@ -917,7 +919,7 @@ public static function sum(array $array, ?callable $callback = null): float|int continue; } - $total += $numeric; + $total = ArraySingleOps::add($total, $numeric); } return $total; @@ -930,7 +932,7 @@ public static function sum(array $array, ?callable $callback = null): float|int continue; } - $total += $numeric; + $total = ArraySingleOps::add($total, $numeric); } return $total; @@ -999,11 +1001,9 @@ private static function invokeValueCallback(callable $callback, mixed $value, in return $callback($value, $key); } - private static function normalizeArrayKey(mixed $value): int|string - { - return ArraySharedOps::normalizeArrayKey($value); - } - + /** + * @throws \InvalidArgumentException + */ private static function requireArrayKey(mixed $value, string $operation): int|string { if (is_int($value) || is_string($value)) { diff --git a/src/Array/ArraySingleOps.php b/src/Array/ArraySingleOps.php index ebf239d..decafef 100644 --- a/src/Array/ArraySingleOps.php +++ b/src/Array/ArraySingleOps.php @@ -7,6 +7,11 @@ /** @internal */ final class ArraySingleOps { + public static function add(float|int $left, float|int $right): float|int + { + return is_int($left) && is_int($right) ? $left + $right : (float) $left + (float) $right; + } + /** * @param array $array */ @@ -21,7 +26,7 @@ public static function avg(array $array): float|int continue; } - $total += $numeric; + $total = self::add($total, $numeric); $count++; } @@ -29,7 +34,7 @@ public static function avg(array $array): float|int return 0.0; } - $avg = $total / $count; + $avg = is_int($total) ? $total / $count : $total / (float) $count; if (!is_finite($avg)) { $avg = self::overflowSafeAverage($array, $count, $avg); } @@ -85,14 +90,6 @@ public static function duplicates(array $array, bool $strict): array return ArrayValueSetOps::duplicates($array, $strict); } - /** - * Build a comparable fingerprint for a value. - */ - public static function fingerprint(mixed $value, bool $strict = true): string - { - return ArrayValueSetOps::fingerprint($value, $strict); - } - /** * @param array $array * @param array $values @@ -145,7 +142,7 @@ public static function numericValue(mixed $value): float|int|null } if (is_string($value) && is_numeric($value)) { - return $value + 0; + return array_sum([$value]); } return null; @@ -223,7 +220,7 @@ private static function overflowSafeAverage(array $array, int $count, float $fal { $average = 0.0; $correction = 0.0; - $scale = 2.0 ** (ceil(log($count, 2)) + 1); + $scale = 2.0 ** (ceil(log($count, 2)) + 1.0); foreach ($array as $value) { $numeric = self::numericValue($value); if ($numeric === null) { @@ -236,7 +233,7 @@ private static function overflowSafeAverage(array $array, int $count, float $fal // Power-of-two scaling leaves overflow headroom while preserving // small terms that may remain after large values cancel. - $term = $numeric / $scale; + $term = (float) $numeric / $scale; $next = $average + $term; $correction += abs($average) >= abs($term) ? ($average - $next) + $term @@ -246,7 +243,7 @@ private static function overflowSafeAverage(array $array, int $count, float $fal $limit = PHP_FLOAT_MAX / $scale; - return max(-$limit, min($limit, $average / $count + $correction / $count)) * $scale; + return max(-$limit, min($limit, $average / (float) $count + $correction / (float) $count)) * $scale; } /** diff --git a/src/Array/ArrayValueSetOps.php b/src/Array/ArrayValueSetOps.php index e8c6bfd..647b3f6 100644 --- a/src/Array/ArrayValueSetOps.php +++ b/src/Array/ArrayValueSetOps.php @@ -72,8 +72,8 @@ public static function duplicates(array $array, bool $strict): array $duplicates = []; foreach ($array as $value) { - $fingerprint = self::fingerprintStrict($value); - if (!isset($strictLookup[$fingerprint])) { + $fingerprint = self::fingerprint($value); + if (!isset($strictCounts[$fingerprint])) { $strictLookup[$fingerprint] = $value; $strictCounts[$fingerprint] = 1; @@ -89,11 +89,19 @@ public static function duplicates(array $array, bool $strict): array return $duplicates; } - public static function fingerprint(mixed $value, bool $strict = true): string + public static function fingerprint(mixed $value): string { - return $strict - ? self::fingerprintStrict($value) - : self::fingerprintLoose($value); + return match (true) { + $value === null => 'null:', + is_bool($value) => 'bool:' . ($value ? '1' : '0'), + is_int($value) => 'int:' . $value, + is_float($value) => self::fingerprintFloat($value), + is_string($value) => 'string:' . strlen($value) . ':' . $value, + is_array($value) => 'array:' . self::fingerprintArrayStrict($value), + is_object($value) => 'object:' . $value::class . ':' . spl_object_id($value), + is_resource($value) => 'resource:' . get_resource_type($value) . ':' . (int) $value, + default => 'unknown:' . get_debug_type($value), + }; } /** @@ -143,7 +151,7 @@ public static function strictLookup(array $values): ?array public static function strictLookupContains(array $lookup, mixed $value): bool { return self::isStrictHashable($value) - && isset($lookup[self::fingerprintStrict($value)]); + && isset($lookup[self::fingerprint($value)]); } /** @@ -176,7 +184,7 @@ public static function strictValueAlreadySeen( return self::fingerprintAlreadySeen( $seen, $digestBuckets, - self::fingerprintStrict($value), + self::fingerprint($value), ); } @@ -187,10 +195,7 @@ public static function strictValueAlreadySeen( public static function unique(array $array, bool $strict): array { if (!$strict) { - /** @var array $unique */ - $unique = array_unique($array, \SORT_REGULAR); - - return $unique; + return array_unique($array, \SORT_REGULAR); } $seen = []; @@ -228,7 +233,7 @@ private static function buildStrictLookup(array $array): ?array return null; } - $lookup[self::fingerprintStrict($value)] = true; + $lookup[self::fingerprint($value)] = true; } return $lookup; @@ -286,7 +291,7 @@ private static function countsByFingerprint(array $array): array { $counts = []; foreach ($array as $value) { - $fingerprint = self::fingerprintStrict($value); + $fingerprint = self::fingerprint($value); $counts[$fingerprint] = ($counts[$fingerprint] ?? 0) + 1; } @@ -337,7 +342,7 @@ private static function filterByMembership(array $array, array $values, bool $st foreach ($array as $key => $value) { $matches = $lookup === null ? in_array($value, $values, $strict) - : isset($lookup[self::fingerprintStrict($value)]); + : isset($lookup[self::fingerprint($value)]); if ($matches === $keepMatches) { $results[$key] = $value; @@ -396,19 +401,6 @@ private static function fingerprintAlreadySeen(array &$seen, array &$digestBucke return false; } - /** - * @param array $value - */ - private static function fingerprintArrayLoose(array $value): string - { - $parts = []; - foreach ($value as $key => $item) { - $parts[] = self::fingerprintLoose($key) . '=>' . self::fingerprintLoose($item); - } - - return implode('|', $parts); - } - /** * @param array $value */ @@ -416,8 +408,8 @@ private static function fingerprintArrayStrict(array $value): string { $parts = []; foreach ($value as $key => $item) { - $keyFingerprint = self::fingerprintStrict($key); - $valueFingerprint = self::fingerprintStrict($item); + $keyFingerprint = self::fingerprint($key); + $valueFingerprint = self::fingerprint($item); $parts[] = strlen($keyFingerprint) . ':' . $keyFingerprint . strlen($valueFingerprint) . ':' . $valueFingerprint; } @@ -444,33 +436,6 @@ private static function fingerprintFloat(float $value): string : 'float:' . bin2hex(pack('E', $value)); } - private static function fingerprintLoose(mixed $value): string - { - return match (true) { - is_int($value), is_float($value), is_bool($value), $value === null => 'numeric:' . (float) $value, - is_string($value) => is_numeric($value) ? 'numeric:' . (float) $value : 'string:' . $value, - is_array($value) => 'array:' . self::fingerprintArrayLoose($value), - is_object($value) => 'object-value:' . self::fingerprintArrayLoose(get_object_vars($value)), - is_resource($value) => 'resource:' . get_resource_type($value) . ':' . (int) $value, - default => 'unknown:' . get_debug_type($value), - }; - } - - private static function fingerprintStrict(mixed $value): string - { - return match (true) { - $value === null => 'null:', - is_bool($value) => 'bool:' . ($value ? '1' : '0'), - is_int($value) => 'int:' . $value, - is_float($value) => self::fingerprintFloat($value), - is_string($value) => 'string:' . strlen($value) . ':' . $value, - is_array($value) => 'array:' . self::fingerprintArrayStrict($value), - is_object($value) => 'object:' . $value::class . ':' . spl_object_id($value), - is_resource($value) => 'resource:' . get_resource_type($value) . ':' . (int) $value, - default => 'unknown:' . get_debug_type($value), - }; - } - private static function isStrictHashable(mixed $value): bool { if (gettype($value) === 'resource (closed)') { diff --git a/src/Array/BaseArrayHelper.php b/src/Array/BaseArrayHelper.php index 5e6063f..c81ed54 100644 --- a/src/Array/BaseArrayHelper.php +++ b/src/Array/BaseArrayHelper.php @@ -7,6 +7,7 @@ use ArrayAccess; use InvalidArgumentException; +/** @api */ class BaseArrayHelper { /** @@ -227,7 +228,7 @@ public static function random(array $array, ?int $number = null, bool $preserveK throw new InvalidArgumentException("You requested $number items, but array only has $count."); } - if ($count === 0 || ($number !== null && $number <= 0)) { + if ($array === [] || ($number !== null && $number <= 0)) { return ($number === null) ? null : []; } @@ -254,6 +255,7 @@ public static function random(array $array, ?int $number = null, bool $preserveK * @param int $end The ending number of the sequence. * @param int $step The increment between each number in the sequence. Defaults to 1. * @return array An array containing the sequence of numbers. + * @throws \InvalidArgumentException */ public static function range(int $start, int $end, int $step = 1): array { diff --git a/src/Array/Concerns/ArrayMultiQuerySortTrait.php b/src/Array/Concerns/ArrayMultiQuerySortTrait.php index a9d2caa..93b99b0 100644 --- a/src/Array/Concerns/ArrayMultiQuerySortTrait.php +++ b/src/Array/Concerns/ArrayMultiQuerySortTrait.php @@ -4,17 +4,22 @@ namespace Infocyph\ArrayKit\Array\Concerns; +use Collator; use Infocyph\ArrayKit\Array\ArraySharedOps; use Infocyph\ArrayKit\Array\ArraySingle; use Infocyph\ArrayKit\Array\ArraySingleOps; use Infocyph\ArrayKit\Array\ArrayValueSetOps; use InvalidArgumentException; +use RuntimeException; use function Infocyph\ArrayKit\compare; /** @internal */ trait ArrayMultiQuerySortTrait { + /** Locale sorting option; retains the legacy integer flag without referencing the deprecated PHP constant. */ + public const int SORT_LOCALE = 5; + private const int ROW_MEMBERSHIP_LOOKUP_MIN_VALUES = 256; /** @@ -45,6 +50,7 @@ public static function between(array $array, string $key, float|int $from, float * * @param array $array * @return array + * @throws \InvalidArgumentException */ public static function countBy(array $array, string|callable $groupBy): array { @@ -137,6 +143,7 @@ public static function firstWhereIn(array $array, string $key, array $values, bo * * @param array $array * @return array + * @throws \InvalidArgumentException */ public static function groupBy(array $array, string|callable $groupBy, bool $preserveKeys = false): array { @@ -166,6 +173,7 @@ public static function groupBy(array $array, string|callable $groupBy, bool $pre * * @param array $array * @return array + * @throws \InvalidArgumentException */ public static function indexBy(array $array, string|callable $indexBy): array { @@ -177,6 +185,7 @@ public static function indexBy(array $array, string|callable $indexBy): array * * @param array $array * @return array + * @throws \InvalidArgumentException */ public static function keyBy(array $array, string|callable $keyBy): array { @@ -249,9 +258,7 @@ public static function mapWithKeys(array $array, callable $callback): array */ public static function max(array $array, string|callable $keyOrCallback): float|int|null { - return self::formatNumericResult( - self::selectExtremeValue($array, $keyOrCallback, pickMax: true), - ); + return self::selectExtremeValue($array, $keyOrCallback, pickMax: true); } /** @@ -271,9 +278,7 @@ public static function maxBy(array $array, string|callable $keyOrCallback): mixe */ public static function min(array $array, string|callable $keyOrCallback): float|int|null { - return self::formatNumericResult( - self::selectExtremeValue($array, $keyOrCallback, pickMax: false), - ); + return self::selectExtremeValue($array, $keyOrCallback, pickMax: false); } /** @@ -289,6 +294,7 @@ public static function minBy(array $array, string|callable $keyOrCallback): mixe /** * @param array $array * @return array + * @throws \InvalidArgumentException */ public static function pluck(array $array, string $column, ?string $indexBy = null): array { @@ -358,6 +364,7 @@ public static function some(array $array, callable $callback): bool * * @param array $array * @return array + * @throws \RuntimeException */ public static function sortBy( array $array, @@ -365,6 +372,7 @@ public static function sortBy( bool $desc = false, int $options = \SORT_REGULAR, ): array { + $collator = self::localeCollator($options); if (!is_string($by)) { $scores = []; foreach ($array as $key => $row) { @@ -373,11 +381,12 @@ public static function sortBy( uksort( $array, - static function (int|string $leftKey, int|string $rightKey) use ($scores, $desc, $options): int { + static function (int|string $leftKey, int|string $rightKey) use ($scores, $desc, $options, $collator): int { $comparison = self::compareSortValues( $scores[$leftKey] ?? null, $scores[$rightKey] ?? null, $options, + $collator, ); return self::applySortDirection($comparison, $desc); @@ -387,12 +396,12 @@ static function (int|string $leftKey, int|string $rightKey) use ($scores, $desc, return $array; } - uasort($array, function ($a, $b) use ($by, $desc, $options) { + uasort($array, static function (mixed $a, mixed $b) use ($by, $desc, $options, $collator): int { $valA = is_array($a) ? ($a[$by] ?? null) : null; $valB = is_array($b) ? ($b[$by] ?? null) : null; return self::applySortDirection( - self::compareSortValues($valA, $valB, $options), + self::compareSortValues($valA, $valB, $options, $collator), $desc, ); }); @@ -403,6 +412,7 @@ static function (int|string $leftKey, int|string $rightKey) use ($scores, $desc, /** * @param array $array * @return array + * @throws \RuntimeException */ public static function sortByDesc(array $array, string|callable $by, int $options = \SORT_REGULAR): array { @@ -419,6 +429,7 @@ public static function sortByDesc(array $array, string|callable $by, int $option * @param array $array * @param array> $criteria * @return array + * @throws \RuntimeException */ public static function sortByMany(array $array, array $criteria): array { @@ -444,6 +455,7 @@ public static function sortByMany(array $array, array $criteria): array * * @param array $array * @return array + * @throws \RuntimeException */ public static function sortRecursive(array $array, int $options = \SORT_REGULAR, bool $descending = false): array { @@ -454,18 +466,7 @@ public static function sortRecursive(array $array, int $options = \SORT_REGULAR, } unset($value); - if (ArraySingle::isAssoc($array)) { - $descending - ? krsort($array, $options) - : ksort($array, $options); - } else { - usort( - $array, - static fn(mixed $left, mixed $right): int => $descending - ? -self::compareSortValues($left, $right, $options) - : self::compareSortValues($left, $right, $options), - ); - } + self::sortLevel($array, $options, $descending); return $array; } @@ -475,6 +476,7 @@ public static function sortRecursive(array $array, int $options = \SORT_REGULAR, * * @param array $array * @return array + * @throws \RuntimeException */ public static function sortRecursiveGuarded( array $array, @@ -511,7 +513,7 @@ public static function sum(array $array, string|callable|null $keyOrCallback = n { $total = 0; foreach ($array as $key => $row) { - $total += self::extractSummableValue($row, $keyOrCallback, $key); + $total = ArraySingleOps::add($total, self::extractSummableValue($row, $keyOrCallback, $key)); } return $total; @@ -656,6 +658,7 @@ public static function whereIn(array $array, string $key, array $values, bool $s * * @param array $array * @return array + * @throws \RuntimeException */ public static function whereLike(array $array, string $key, string $pattern, bool $caseSensitive = false): array { @@ -887,14 +890,15 @@ private static function collectByDerivedKeyStrict( } /** - * @param array, desc:bool, options:int}> $criteria + * @param array, desc:bool, options:int, collator:?Collator}> $criteria + * @throws \RuntimeException */ private static function compareByManyCriteria(int|string $leftKey, int|string $rightKey, array $criteria): int { foreach ($criteria as $criterion) { $leftValue = $criterion['values'][$leftKey]; $rightValue = $criterion['values'][$rightKey]; - $comparison = self::compareSortValues($leftValue, $rightValue, $criterion['options']); + $comparison = self::compareSortValues($leftValue, $rightValue, $criterion['options'], $criterion['collator']); if ($comparison !== 0) { return self::applySortDirection($comparison, $criterion['desc']); } @@ -903,10 +907,28 @@ private static function compareByManyCriteria(int|string $leftKey, int|string $r return 0; } + /** + * @throws \RuntimeException + */ + private static function compareLocale(string $left, string $right, ?Collator $collator): int + { + if ($collator === null) { + return strcmp($left, $right); + } + + $result = $collator->compare($left, $right); + if ($result === false) { + throw new RuntimeException('Locale comparison failed: ' . $collator->getErrorMessage()); + } + + return $result; + } + /** * Compare two values according to PHP sort options. + * @throws \RuntimeException */ - private static function compareSortValues(mixed $left, mixed $right, int $options): int + private static function compareSortValues(mixed $left, mixed $right, int $options, ?Collator $collator): int { if ($left === $right) { return 0; @@ -923,7 +945,7 @@ private static function compareSortValues(mixed $left, mixed $right, int $option \SORT_NATURAL => $caseInsensitive ? strnatcasecmp(self::asString($left), self::asString($right)) : strnatcmp(self::asString($left), self::asString($right)), - \SORT_LOCALE_STRING => strcoll(self::asString($left), self::asString($right)), + self::SORT_LOCALE => self::compareLocale(self::asString($left), self::asString($right), $collator), default => $left <=> $right, }; } @@ -1037,14 +1059,10 @@ private static function firstWhereInByScan( return $default; } - private static function formatNumericResult(float|int|null $value): float|int|null - { - return $value; - } - /** * PHP comparisons may recursively walk unbounded object graphs. Object * values therefore fall outside the guarded sort's supported domain. + * @throws \RuntimeException */ private static function hasUnsafeSortObject(mixed $value, bool $throwOnTooDeep): bool { @@ -1064,6 +1082,34 @@ private static function invokeRowCallback(callable $callback, mixed $row, int|st return $callback($row, $key); } + /** + * @throws \RuntimeException + */ + private static function localeCollator(int $options): ?Collator + { + if (($options & ~\SORT_FLAG_CASE) !== self::SORT_LOCALE) { + return null; + } + + $locale = setlocale(\LC_COLLATE, '0'); + if ($locale === false) { + throw new RuntimeException('Unable to determine the active collation locale.'); + } + if (in_array($locale, ['C', 'POSIX', 'C.UTF-8', 'C.utf8'], true)) { + return null; + } + if (!class_exists(Collator::class)) { + throw new RuntimeException('Non-C locale sorting requires ext-intl.'); + } + + $identifier = preg_replace('/\.[^@]+/', '', $locale); + if ($identifier === null) { + throw new RuntimeException('Unable to normalize the active collation locale.'); + } + + return new Collator($identifier); + } + /** * @param array> $criteria * @return array @@ -1097,7 +1143,8 @@ private static function normalizeSortByManyCriteria(array $criteria): array * * @param array $array * @param array> $criteria - * @return array, desc:bool, options:int}> + * @return array, desc:bool, options:int, collator:?Collator}> + * @throws \RuntimeException */ private static function prepareSortByManyCriteria(array $array, array $criteria): array { @@ -1113,12 +1160,16 @@ private static function prepareSortByManyCriteria(array $array, array $criteria) 'values' => $values, 'desc' => $criterion['desc'], 'options' => $criterion['options'], + 'collator' => self::localeCollator($criterion['options']), ]; } return $prepared; } + /** + * @throws \InvalidArgumentException + */ private static function requireArrayKey(mixed $value, string $operation): int|string { if (is_int($value) || is_string($value)) { @@ -1132,6 +1183,7 @@ private static function requireArrayKey(mixed $value, string $operation): int|st /** * @param array $array + * @throws \RuntimeException */ private static function reserveSortNodes( array $array, @@ -1163,15 +1215,6 @@ private static function reserveSortNodes( return true; } - private static function resolveDerivedValue(mixed $row, string|callable $keyOrCallback, int|string $index): mixed - { - if (!is_string($keyOrCallback)) { - return self::invokeRowCallback($keyOrCallback, $row, $index); - } - - return is_array($row) && array_key_exists($keyOrCallback, $row) ? $row[$keyOrCallback] : null; - } - private static function resolveSortByManyValue(mixed $row, string|callable $by, int|string $key): mixed { if (!is_string($by)) { @@ -1244,9 +1287,35 @@ private static function selectExtremeValue(array $array, string|callable $keyOrC return $selected; } + /** + * @param array $array + * @throws \RuntimeException + */ + private static function sortLevel(array &$array, int $options, bool $descending): void + { + $collator = self::localeCollator($options); + $locale = ($options & ~\SORT_FLAG_CASE) === self::SORT_LOCALE; + if (ArraySingle::isAssoc($array) && !$locale) { + $descending ? krsort($array, $options) : ksort($array, $options); + + return; + } + + $compare = static fn(mixed $left, mixed $right): int => self::applySortDirection( + self::compareSortValues($left, $right, $options, $collator), + $descending, + ); + if (ArraySingle::isAssoc($array)) { + uksort($array, $compare); + } else { + usort($array, $compare); + } + } + /** * @param array $array * @return array + * @throws \RuntimeException */ private static function sortRecursiveWithGuards( array $array, @@ -1303,19 +1372,7 @@ private static function sortRecursiveWithGuards( } unset($value); - if (ArraySingle::isAssoc($array)) { - $descending - ? krsort($array, $options) - : ksort($array, $options); - } else { - usort( - $array, - static fn(mixed $left, mixed $right): int => self::applySortDirection( - self::compareSortValues($left, $right, $options), - $descending, - ), - ); - } + self::sortLevel($array, $options, $descending); return $array; } diff --git a/src/Array/Concerns/DotNotationPublicApiTrait.php b/src/Array/Concerns/DotNotationPublicApiTrait.php index 7e1798d..40c1eab 100644 --- a/src/Array/Concerns/DotNotationPublicApiTrait.php +++ b/src/Array/Concerns/DotNotationPublicApiTrait.php @@ -23,6 +23,7 @@ public static function all(array $array): array /** * @param array $array * @return array + * @throws \InvalidArgumentException */ public static function arrayValue(array $array, string $key, mixed $default = null): array { @@ -36,6 +37,7 @@ public static function arrayValue(array $array, string $key, mixed $default = nu /** * @param array $array + * @throws \InvalidArgumentException */ public static function boolean(array $array, string $key, mixed $default = null): bool { @@ -50,6 +52,7 @@ public static function boolean(array $array, string $key, mixed $default = null) /** * @param array $array * @return array + * @throws \InvalidArgumentException */ public static function expand(array $array): array { @@ -64,6 +67,7 @@ public static function expand(array $array): array /** * @param array $array * @param array|string $keys + * @throws \InvalidArgumentException */ public static function fill(array &$array, array|string $keys, mixed $value = null): void { @@ -84,6 +88,7 @@ public static function flatten(array $array, string $prepend = ''): array /** * @param array $array + * @throws \InvalidArgumentException */ public static function float(array $array, string $key, mixed $default = null): float { @@ -144,6 +149,7 @@ public static function get(array $array, array|int|string|null $keys = null, mix * * @param array $array * @param array|int|string|null $keys + * @throws \RuntimeException */ public static function getSafe( array $array, @@ -256,6 +262,7 @@ public static function hasWildcard(string $path): bool /** * @param array $array + * @throws \InvalidArgumentException */ public static function integer(array $array, string $key, mixed $default = null): int { @@ -287,6 +294,8 @@ public static function matches(array $array, string $path): bool * Move a dot path from one key to another. * * @param array $array + * @throws \Throwable + * @throws \InvalidArgumentException */ public static function move(array &$array, string $from, string $to, bool $overwrite = true): bool { @@ -311,6 +320,7 @@ public static function offsetGet(array $array, string $key): mixed /** * @param array $array + * @throws \InvalidArgumentException */ public static function offsetSet(array &$array, string $key, mixed $value): void { @@ -357,6 +367,8 @@ public static function pluck(array $array, array|string $keys, mixed $default = * Rename a dot path from one key to another. * * @param array $array + * @throws \Throwable + * @throws \InvalidArgumentException */ public static function rename(array &$array, string $from, string $to, bool $overwrite = true): bool { @@ -383,9 +395,7 @@ public static function rename(array &$array, string $from, string $to, bool $ove self::forget($staged, $from); self::set($staged, $to, $value, $overwrite); } catch (\Throwable $error) { - foreach ($originals as $id => $original) { - $references[$id] = $original; - } + DotNotationPathOps::restoreMutationReferences($references, $originals); throw $error; } @@ -397,6 +407,7 @@ public static function rename(array &$array, string $from, string $to, bool $ove /** * @param array $array * @param array|string|null $keys + * @throws \InvalidArgumentException */ public static function set(array &$array, array|string|null $keys = null, mixed $value = null, bool $overwrite = true): bool { @@ -419,6 +430,7 @@ public static function set(array &$array, array|string|null $keys = null, mixed /** * @param array $array + * @throws \InvalidArgumentException */ public static function string(array $array, string $key, mixed $default = null): string { diff --git a/src/Array/DotNotation.php b/src/Array/DotNotation.php index 399a17a..3e73115 100644 --- a/src/Array/DotNotation.php +++ b/src/Array/DotNotation.php @@ -6,10 +6,14 @@ use Infocyph\ArrayKit\Array\Concerns\DotNotationPublicApiTrait; +/** @api */ class DotNotation { use DotNotationPublicApiTrait; + /** + * @throws \RuntimeException + */ private static function canResolveSafeKey(int $visitedNodes, int $maxNodes, bool $throwOnTooDeep): bool { if ($maxNodes <= 0 || $visitedNodes < $maxNodes) { @@ -107,6 +111,9 @@ private static function getValue(mixed $target, int|string $key, mixed $default) return self::resolveValue($target, $key, $default); } + /** + * @throws \RuntimeException + */ private static function getValueSafe( mixed $target, int|string $key, @@ -151,6 +158,7 @@ private static function getValueSafe( * * @param array $target * @param array $segments + * @throws \InvalidArgumentException */ private static function handleWildcardSet( array &$target, @@ -170,6 +178,9 @@ private static function handleWildcardSet( } } + /** + * @throws \InvalidArgumentException + */ private static function hasWritableObjectProperty(object $target, string $propertyName): bool { $propertyExists = property_exists($target, $propertyName); @@ -272,6 +283,7 @@ private static function segmentExact(mixed $array, string $path, mixed $default) * Sets a value in the target array/object using dot notation. * * @param array $target + * @throws \InvalidArgumentException */ private static function setValue(array &$target, string $key, mixed $value, bool $overwrite): void { @@ -292,6 +304,7 @@ private static function setValue(array &$target, string $key, mixed $value, bool * * @param array &$target * @param array $segments + * @throws \InvalidArgumentException */ private static function setValueArray( array &$target, @@ -318,6 +331,7 @@ private static function setValueArray( /** * @param array $segments + * @throws \InvalidArgumentException */ private static function setValueBySegments( mixed &$target, @@ -360,6 +374,7 @@ private static function setValueBySegments( * Sets a value in a target that is not an array or object. * * @param array $segments + * @throws \InvalidArgumentException */ private static function setValueFallback( mixed &$target, @@ -377,7 +392,7 @@ private static function setValueFallback( $target = []; if ($position < count($segments)) { self::setValueBySegments($target[$segment], $segments, $position, $value, $overwrite); - } elseif ($overwrite) { + } else { $target[$segment] = $value; } } @@ -386,9 +401,10 @@ private static function setValueFallback( * Sets a value in an object using dot-notation segments. * * @param array $segments + * @throws \InvalidArgumentException */ private static function setValueObject( - object &$target, + object $target, string $segment, array $segments, int $position, @@ -429,6 +445,7 @@ private static function splitPath(string $path): array * Traverses the target array/object to retrieve a value using dot notation. * * @param array $segments + * @throws \RuntimeException */ private static function traverseGet(mixed $target, array $segments, mixed $default, object $missing): mixed { @@ -443,6 +460,7 @@ private static function traverseGet(mixed $target, array $segments, mixed $defau /** * @param array $segments + * @throws \RuntimeException */ private static function traverseGetWithLimits( mixed $target, diff --git a/src/Array/DotNotationPathOps.php b/src/Array/DotNotationPathOps.php index 3ab2653..d21babf 100644 --- a/src/Array/DotNotationPathOps.php +++ b/src/Array/DotNotationPathOps.php @@ -108,6 +108,20 @@ public static function normalizeSegment(string $segment, mixed $target): int|str }; } + /** + * Restore original values through the captured reference cells. + * + * @template TValue + * @param array $references + * @param array $originals + */ + public static function restoreMutationReferences(array &$references, array $originals): void + { + array_walk($references, static function (mixed &$reference, string $id) use ($originals): void { + $reference = $originals[$id]; + }); + } + /** * Retrieve a value from an array using an exact key path. */ @@ -192,6 +206,7 @@ public static function splitPath(string $path): array * * @param array $segments * @param callable(mixed): mixed $defaultResolver + * @throws \RuntimeException */ public static function traverseGet( mixed $target, @@ -310,6 +325,7 @@ private static function captureMutationPath( /** * @phpstan-impure + * @throws \RuntimeException */ private static function consumeTraversalNode( int &$visitedNodes, @@ -328,6 +344,9 @@ private static function consumeTraversalNode( return false; } + /** + * @throws \RuntimeException + */ private static function handleTraversalLimit(object $missing, bool $throwOnTooDeep, string $message): mixed { if ($throwOnTooDeep) { @@ -397,6 +416,7 @@ private static function resolveLast(mixed $target): string|int|null /** * @param array $segments * @param callable(mixed): mixed $defaultResolver + * @throws \RuntimeException */ private static function resolveWildcardItem( mixed $item, @@ -443,6 +463,7 @@ private static function resolveWildcardItem( * * @param array $segments * @param callable(mixed): mixed $defaultResolver + * @throws \RuntimeException */ private static function traverseWildcard( mixed $target, diff --git a/src/ArrayKit.php b/src/ArrayKit.php index cee3c3f..6812b3b 100644 --- a/src/ArrayKit.php +++ b/src/ArrayKit.php @@ -30,7 +30,7 @@ final class ArrayKit { /** - * @var array + * @var array> */ private static array $moduleProxies = []; @@ -43,6 +43,7 @@ public static function collection(mixed $data = []): Collection /** * @param array $items + * @throws \RuntimeException */ public static function config(array $items = []): Config { @@ -54,21 +55,25 @@ public static function config(array $items = []): Config return $config; } + /** @return ModuleProxy */ public static function dot(): ModuleProxy { return self::proxy(DotNotation::class); } + /** @return ModuleProxy */ public static function dotenv(): ModuleProxy { return self::proxy(EnvParser::class); } + /** @return ModuleProxy */ public static function env(): ModuleProxy { return self::proxy(Environment::class); } + /** @return ModuleProxy */ public static function helper(): ModuleProxy { return self::proxy(BaseArrayHelper::class); @@ -99,6 +104,7 @@ public static function lazyConfig( return new LazyFileConfig($directory, $extension, $items, $namespaceCacheDirectory); } + /** @return ModuleProxy */ public static function multi(): ModuleProxy { return self::proxy(ArrayMulti::class); @@ -109,16 +115,23 @@ public static function pipeline(mixed $data): Pipeline return Collection::make($data)->process(); } + /** @return ModuleProxy */ public static function single(): ModuleProxy { return self::proxy(ArraySingle::class); } /** - * @param class-string $className + * @template T of object + * @param class-string $className + * @return ModuleProxy */ private static function proxy(string $className): ModuleProxy { - return self::$moduleProxies[$className] ?? self::$moduleProxies[$className] = new ModuleProxy($className); + // The cache key is the same class string used to construct each proxy. + /** @var ModuleProxy $proxy */ + $proxy = self::$moduleProxies[$className] ?? self::$moduleProxies[$className] = new ModuleProxy($className); + + return $proxy; } } diff --git a/src/Collection/Collection.php b/src/Collection/Collection.php index 168c5ef..20e8bf5 100644 --- a/src/Collection/Collection.php +++ b/src/Collection/Collection.php @@ -17,7 +17,9 @@ * interfaces (ArrayAccess, IteratorAggregate, Countable, JsonSerializable). * Inherits most of its behavior from BaseCollectionTrait. * + * @mixin Pipeline * @phpstan-consistent-constructor + * @psalm-consistent-constructor * * @implements ArrayAccess * @implements IteratorAggregate diff --git a/src/Collection/Concerns/BaseCollectionTrait.php b/src/Collection/Concerns/BaseCollectionTrait.php index 019ebb4..205ca8a 100644 --- a/src/Collection/Concerns/BaseCollectionTrait.php +++ b/src/Collection/Concerns/BaseCollectionTrait.php @@ -118,6 +118,7 @@ public function __isset(string $key): bool * * @param string $key The key of the item to set. * @param mixed $value The value to set. + * @throws \InvalidArgumentException */ public function __set(string $key, mixed $value): void { @@ -364,7 +365,7 @@ public function items(): array public function jsonSerialize(): array { return array_map( - static fn($value) => $value instanceof JsonSerializable ? $value->jsonSerialize() : $value, + static fn(mixed $value): mixed => $value instanceof JsonSerializable ? $value->jsonSerialize() : $value, $this->data, ); } @@ -451,6 +452,7 @@ public function offsetGet(mixed $offset): mixed * * @param mixed $offset The key of the item to set, or null to append. * @param mixed $value The value of the item to set. + * @throws \InvalidArgumentException */ public function offsetSet(mixed $offset, mixed $value): void { @@ -525,6 +527,7 @@ public function process(): Pipeline * @param array|string|null $keys The key(s) to set. * @param mixed $value The value to set. * @return bool True on success. + * @throws \InvalidArgumentException */ public function set(array|string|null $keys = null, mixed $value = null): bool { diff --git a/src/Collection/HookedCollection.php b/src/Collection/HookedCollection.php index e0dcefb..e869151 100644 --- a/src/Collection/HookedCollection.php +++ b/src/Collection/HookedCollection.php @@ -11,6 +11,8 @@ * Class HookedCollection * * A collection that supports get/set hooks for dynamic transformations. + * + * @api */ class HookedCollection extends Collection { @@ -61,6 +63,7 @@ public function offsetGet(mixed $offset): mixed * * @param mixed $offset The array key * @param mixed $value The value to set + * @throws \InvalidArgumentException */ #[\Override] public function offsetSet(mixed $offset, mixed $value): void diff --git a/src/Collection/LazyCollection.php b/src/Collection/LazyCollection.php index aa69004..696e100 100644 --- a/src/Collection/LazyCollection.php +++ b/src/Collection/LazyCollection.php @@ -91,6 +91,9 @@ public static function make(mixed $data = []): self /** * @return array + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable */ public function all(): array { @@ -99,6 +102,7 @@ public function all(): array /** * @return self> + * @throws \InvalidArgumentException */ public function chunkLazy(int $size, bool $preserveKeys = false): self { @@ -133,6 +137,9 @@ function (?RunwireLazyBinding $binding) use ($size, $preserveKeys): Generator { /** * @return Generator + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable */ public function cursor(): Generator { @@ -160,7 +167,11 @@ function (?RunwireLazyBinding $binding) use ($callback): Generator { /** * @return Traversable + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable */ + #[\Override] public function getIterator(): Traversable { return $this->cursor(); @@ -187,6 +198,7 @@ function (?RunwireLazyBinding $binding) use ($callback): Generator { /** * @return self + * @throws \InvalidArgumentException */ public function take(int $limit): self { @@ -248,6 +260,8 @@ function (?RunwireLazyBinding $binding) use ($callback): Generator { * Bind explicit Runwire runtime/request/scope instances to this collection. * * @return self + * @throws \InvalidArgumentException + * @throws \LogicException */ public function withRunwire( RuntimeContext $runtime, @@ -292,7 +306,15 @@ private static function pullReplayEntry(Generator $sourceCursor, bool &$advanceP $advancePending = false; } - return $sourceCursor->valid() ? [$sourceCursor->key(), $sourceCursor->current()] : null; + if (!$sourceCursor->valid()) { + return null; + } + + // A valid generator has a current value of its declared yielded type, including null when allowed. + /** @var TSourceValue $value */ + $value = $sourceCursor->current(); + + return [$sourceCursor->key(), $value]; } /** @@ -336,6 +358,7 @@ private static function replayableFactory(iterable $source): \Closure * @param list $cache * @param Generator|null $sourceCursor * @return Generator + * @throws \Throwable */ private static function replayCursor( iterable $source, @@ -395,6 +418,9 @@ private static function replayCursor( /** * @return Generator + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable */ private function cursorWithBinding(?RunwireLazyBinding $binding): Generator { @@ -410,20 +436,18 @@ private function cursorWithBinding(?RunwireLazyBinding $binding): Generator /** * @return Generator + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable */ private function sourceCursorWithBinding(?RunwireLazyBinding $binding): Generator { $binding?->checkpoint(); $factory = $this->factory; - $iterable = $factory($binding); - $iterator = (static function () use ($iterable): Generator { - yield from $iterable; - })(); - $processed = 0; - while ($iterator->valid()) { - yield $iterator->key() => $iterator->current(); + foreach ($factory($binding) as $key => $value) { + yield $key => $value; $processed++; if ( @@ -432,8 +456,6 @@ private function sourceCursorWithBinding(?RunwireLazyBinding $binding): Generato ) { $binding->checkpoint(); } - - $iterator->next(); } } } diff --git a/src/Collection/Pipeline.php b/src/Collection/Pipeline.php index 10b7df8..1181db7 100644 --- a/src/Collection/Pipeline.php +++ b/src/Collection/Pipeline.php @@ -8,6 +8,7 @@ use Infocyph\ArrayKit\Array\ArraySingle; use Infocyph\ArrayKit\Array\BaseArrayHelper; +/** @api */ class Pipeline { /** @@ -40,6 +41,7 @@ public function between(string $key, float|int $from, float|int $to): Collection /** * chunk the array (single-dim). + * @throws \InvalidArgumentException */ public function chunk(int $size, bool $preserveKeys = false): Collection { @@ -63,6 +65,7 @@ public function collapse(): Collection * (We treat $this->working as the *keys*, user passes an array of values.) * * @param array $values + * @throws \InvalidArgumentException */ public function combine(array $values): Collection { @@ -75,6 +78,7 @@ public function combine(array $values): Collection * Count items grouped by value/callback buckets. * * @return array + * @throws \InvalidArgumentException */ public function countBy(callable|string|null $groupBy = null): array { @@ -253,6 +257,7 @@ public function isMultiDimensional(): bool /** * Key rows by a derived key (last write wins on duplicates). + * @throws \InvalidArgumentException */ public function keyBy(string|callable $keyBy): Collection { @@ -351,6 +356,7 @@ public function mode(): array /** * Return every n-th element, using ArraySingle::nth. + * @throws \InvalidArgumentException */ public function nth(int $step, int $offset = 0): Collection { @@ -392,6 +398,7 @@ public function overlay(array $overlay): Collection /** * "Paginate" the array by slicing it into a smaller segment, using ArraySingle::paginate. + * @throws \InvalidArgumentException */ public function paginate(int $page, int $perPage): Collection { @@ -422,7 +429,10 @@ public function pipe(callable $callback): Collection return $this->collection; } - /** Extract a column (optionally re-index) */ + /** + * Extract a column (optionally re-index) + * @throws \InvalidArgumentException + */ public function pluck(string $column, ?string $indexBy = null): Collection { $this->working = ArrayMulti::pluck($this->working, $column, $indexBy); @@ -452,6 +462,7 @@ public function reject(mixed $callback = true): Collection * Rename keys using a map or callback. * * @param array|callable $mapper + * @throws \InvalidArgumentException */ public function rekey(array|callable $mapper): Collection { @@ -534,6 +545,7 @@ public function slice(int $offset, ?int $length = null): Collection /** * Sort by a column or callback in ascending/descending order. + * @throws \RuntimeException */ public function sortBy(string|callable $by, bool $desc = false, int $options = SORT_REGULAR): Collection { @@ -546,6 +558,7 @@ public function sortBy(string|callable $by, bool $desc = false, int $options = S * Sort rows by multiple column/callback criteria. * * @param array> $criteria + * @throws \RuntimeException */ public function sortByMany(array $criteria): Collection { @@ -556,6 +569,7 @@ public function sortByMany(array $criteria): Collection /** * Recursively sort the array by keys/values, using ArrayMulti::sortRecursive. + * @throws \RuntimeException */ public function sortRecursive(int $options = SORT_REGULAR, bool $descending = false): Collection { @@ -603,7 +617,10 @@ public function tap(callable $callback): Collection return $this->collection; } - /** Matrix transpose (rows ↔ columns) */ + /** + * Matrix transpose (rows ↔ columns) + * @throws \InvalidArgumentException + */ public function transpose(): Collection { $this->working = ArrayMulti::transpose($this->working); @@ -733,6 +750,7 @@ public function whereIn(string $key, array $values, bool $strict = false): Colle /** * Filter rows by SQL-like pattern matching. + * @throws \RuntimeException */ public function whereLike(string $key, string $pattern, bool $caseSensitive = false): Collection { diff --git a/src/Collection/RunwireLazyBinding.php b/src/Collection/RunwireLazyBinding.php index e1f7deb..813eebf 100644 --- a/src/Collection/RunwireLazyBinding.php +++ b/src/Collection/RunwireLazyBinding.php @@ -26,6 +26,10 @@ private bool $yieldEnabled; + /** + * @throws \InvalidArgumentException + * @throws \LogicException + */ public function __construct( public RuntimeContext $runtime, private ?RequestContext $request = null, @@ -55,6 +59,11 @@ public function __construct( && $runtime->supports(RuntimeCapability::RUNWIRE_COROUTINES); } + /** + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function checkpoint(): void { $this->assertActive(); @@ -70,6 +79,10 @@ public function checkpoint(): void $this->scopeCancellation?->throwIfCancelled(); } + /** + * @throws \LogicException + * @throws \Throwable + */ private function assertActive(): void { if ($this->request?->completed()) { @@ -77,7 +90,7 @@ private function assertActive(): void } if ($this->scope !== null && $this->scopeCheckKey !== null) { - // Runwire 3.0 guards this read without yielding or changing task-local state. + // Runwire guards this read without yielding or changing task-local state. $this->scope->hasLocal($this->scopeCheckKey); } } diff --git a/src/Config/Concerns/BaseConfigTrait.php b/src/Config/Concerns/BaseConfigTrait.php index d37fdbc..d2c4275 100644 --- a/src/Config/Concerns/BaseConfigTrait.php +++ b/src/Config/Concerns/BaseConfigTrait.php @@ -12,7 +12,6 @@ use OutOfBoundsException; use RuntimeException; use UnexpectedValueException; -use UnitEnum as TEnum; /** @internal */ trait BaseConfigTrait @@ -54,6 +53,8 @@ public function all(): array * @param string $key The dot-notation key referencing an array * @param mixed $value The value to append * @return bool True on success + * @throws \RuntimeException + * @throws \InvalidArgumentException */ public function append(string $key, mixed $value): bool { @@ -67,6 +68,7 @@ public function append(string $key, mixed $value): bool /** * Detect whether config changed compared to a named snapshot. + * @phpstan-impure */ public function changed(string $snapshot = 'default'): bool { @@ -77,6 +79,9 @@ public function changed(string $snapshot = 'default'): bool return $this->snapshots[$snapshot] !== $this->items; } + /** + * @throws \UnexpectedValueException + */ public function exportCache(string $path): bool { $directory = dirname($path); @@ -94,6 +99,8 @@ public function exportCache(string $path): bool * * @param string|array $key Dot-notation key or multiple [key => value] * @param mixed|null $value The value to set if missing + * @throws \RuntimeException + * @throws \InvalidArgumentException */ public function fill(string|array $key, mixed $value = null): bool { @@ -117,6 +124,7 @@ public function flushReadCache(): static */ /** * @param string|int|array $key + * @throws \RuntimeException */ public function forget(string|int|array $key): bool { @@ -180,9 +188,8 @@ public function getBool(string|int $key, ?bool $default = null): ?bool /** * Get an enum instance from a scalar stored config value. * - * @template TEnum of \UnitEnum - * - * @param class-string $enumClass + * @param class-string<\UnitEnum> $enumClass + * @throws \InvalidArgumentException */ public function getEnum(string|int $key, string $enumClass, ?\UnitEnum $default = null): ?\UnitEnum { @@ -196,15 +203,7 @@ public function getEnum(string|int $key, string $enumClass, ?\UnitEnum $default } if (is_subclass_of($enumClass, \BackedEnum::class)) { - if (!is_string($value) && !is_int($value)) { - return $default; - } - - if (get_debug_type($value) !== new \ReflectionEnum($enumClass)->getBackingType()?->getName()) { - return $default; - } - - return $enumClass::tryFrom($value) ?? $default; + return self::resolveBackedEnum($enumClass, $value) ?? $default; } if (!is_string($value)) { @@ -260,6 +259,7 @@ public function getList(string|int $key, ?array $default = null): ?array * Get a required configuration value or throw when missing. * * @param string|int|array $key + * @throws \OutOfBoundsException */ public function getOrFail(string|int|array $key): mixed { @@ -328,6 +328,7 @@ public function isReadonly(): bool * * @param array $resource The array containing config items * @return bool True if loaded successfully, false if already loaded + * @throws \RuntimeException */ public function loadArray(array $resource): bool { @@ -343,11 +344,19 @@ public function loadArray(array $resource): bool return false; } + /** + * @throws \UnexpectedValueException + * @throws \RuntimeException + */ public function loadCache(string $path): bool { return $this->loadFile($path); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ public function loadEnvFile(string $path): bool { $this->assertWritable(); @@ -364,6 +373,8 @@ public function loadEnvFile(string $path): bool * * @param string $path The file path to load * @return bool True if loaded successfully, false if already loaded or file missing + * @throws \UnexpectedValueException + * @throws \RuntimeException */ public function loadFile(string $path): bool { @@ -388,6 +399,7 @@ public function loadFile(string $path): bool * Merge a config array into current items. * * @param array $items + * @throws \RuntimeException */ public function merge(array $items): bool { @@ -398,6 +410,10 @@ public function merge(array $items): bool return true; } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ public function mergeEnvFile(string $path): bool { return $this->merge(EnvParser::parseFile($path)); @@ -407,6 +423,7 @@ public function mergeEnvFile(string $path): bool * Overlay another config array on top of current items. * * @param array $overlay + * @throws \RuntimeException */ public function overlay(array $overlay): bool { @@ -420,6 +437,8 @@ public function overlay(array $overlay): bool * @param string $key The dot-notation key referencing an array * @param mixed $value The value to prepend * @return bool True on success + * @throws \RuntimeException + * @throws \InvalidArgumentException */ public function prepend(string $key, mixed $value): bool { @@ -461,6 +480,8 @@ public function readonly(bool $enabled = true): static * Reload configuration from an array or file path, replacing existing data. * * @param array|string $source + * @throws \UnexpectedValueException + * @throws \RuntimeException */ public function reload(array|string $source): bool { @@ -486,6 +507,7 @@ public function reload(array|string $source): bool * Replace the entire configuration storage with a new array. * * @param array $items + * @throws \RuntimeException */ public function replace(array $items): bool { @@ -499,6 +521,7 @@ public function replace(array $items): bool /** * Restore configuration from a named snapshot. + * @throws \RuntimeException */ public function restore(string $name = 'default'): bool { @@ -525,6 +548,8 @@ public function restore(string $name = 'default'): bool * @param mixed|null $value The value to set * @param bool $overwrite Overwrite existing? Default true. * @return bool True on success + * @throws \RuntimeException + * @throws \InvalidArgumentException */ public function set(string|array|null $key = null, mixed $value = null, bool $overwrite = true): bool { @@ -537,6 +562,7 @@ public function set(string|array|null $key = null, mixed $value = null, bool $ov /** * Save a named snapshot of current configuration. + * @throws \UnexpectedValueException */ public function snapshot(string $name = 'default'): bool { @@ -546,6 +572,9 @@ public function snapshot(string $name = 'default'): bool return true; } + /** + * @throws \RuntimeException + */ protected function assertWritable(): void { if ($this->readOnly) { @@ -608,6 +637,9 @@ protected function isReadCacheSafePath(string $path): bool return $cursor === null || is_scalar($cursor); } + /** + * @throws \UnexpectedValueException + */ protected function materializeCacheValue(mixed $value): mixed { $activeReferences = []; @@ -663,6 +695,9 @@ protected function valueCacheKey(int|string $key): string return is_int($key) ? 'i:' . $key : 's:' . $key; } + /** + * @throws \UnexpectedValueException + */ protected function writeCacheFile(string $path, string $contents): bool { try { @@ -695,8 +730,24 @@ protected function writeCacheFile(string $path, string $contents): bool return false; } + /** @param class-string<\BackedEnum> $enumClass */ + private static function resolveBackedEnum(string $enumClass, mixed $value): ?\BackedEnum + { + $backingType = new \ReflectionEnum($enumClass)->getBackingType(); + if (!$backingType instanceof \ReflectionNamedType) { + return null; + } + + return match ($backingType->getName()) { + 'int' => is_int($value) ? $enumClass::tryFrom($value) : null, + 'string' => is_string($value) ? $enumClass::tryFrom($value) : null, + default => null, + }; + } + /** * @return array + * @throws \InvalidArgumentException */ private function arrayValueForMutation(string $key): array { @@ -718,6 +769,7 @@ private function arrayValueForMutation(string $key): array * @param array $activeReferences * @param array $activeObjects * @return array + * @throws \UnexpectedValueException */ private function materializeCacheArray(array $value, array &$activeReferences, array &$activeObjects): array { @@ -758,6 +810,7 @@ private function materializeCacheArray(array $value, array &$activeReferences, a /** * @param array $activeReferences * @param array $activeObjects + * @throws \UnexpectedValueException */ private function materializeCacheValueRecursive( mixed $value, diff --git a/src/Config/Concerns/LazyFileConfigCacheTrait.php b/src/Config/Concerns/LazyFileConfigCacheTrait.php index ea3cd13..2b2e5eb 100644 --- a/src/Config/Concerns/LazyFileConfigCacheTrait.php +++ b/src/Config/Concerns/LazyFileConfigCacheTrait.php @@ -35,6 +35,7 @@ trait LazyFileConfigCacheTrait /** * @param string|array|null $namespaces + * @throws \RuntimeException */ public function flushNamespaceCache(string|array|null $namespaces = null): static { @@ -85,6 +86,8 @@ public function namespaceCacheDirectory(): ?string /** * @param string|array|null $namespaces + * @throws \RuntimeException + * @throws \InvalidArgumentException */ public function warmNamespaceCache(string|array|null $namespaces = null): static { @@ -245,6 +248,7 @@ protected function loadFlatLeafIndex(): void /** * @return array + * @throws \UnexpectedValueException */ protected function namespaceCacheWarmValue(string $namespace): array { @@ -262,22 +266,12 @@ protected function namespaceCacheWarmValue(string $namespace): array $sourceFile = $this->resolveNamespaceFile($namespace); if ($sourceFile !== null) { - $value = include $sourceFile; - if (!is_array($value)) { - throw new UnexpectedValueException("Config file [{$sourceFile}] must return an array."); - } - - return $value; + return $this->readNamespaceFile($sourceFile); } $cachedFile = $this->warmNamespaceCacheFile($namespace); if ($cachedFile !== null) { - $value = include $cachedFile; - if (!is_array($value)) { - throw new UnexpectedValueException("Config file [{$cachedFile}] must return an array."); - } - - return $value; + return $this->readNamespaceFile($cachedFile); } if (array_key_exists($namespace, $this->items) && is_array($this->items[$namespace])) { @@ -290,6 +284,7 @@ protected function namespaceCacheWarmValue(string $namespace): array /** * @param string|array|null $namespaces * @return string[] + * @throws \InvalidArgumentException */ protected function resolveWarmNamespaces(string|array|null $namespaces): array { @@ -305,6 +300,10 @@ protected function resolveWarmNamespaces(string|array|null $namespaces): array return array_values(array_unique($resolved)); } + /** + * @throws \RuntimeException + * @throws \Throwable + */ private function activateGeneration(string $stage): void { $root = $this->namespaceCacheDirectory; @@ -357,14 +356,12 @@ private function buildFlatLeafIndexFromDirectory(string $directory): array foreach ($this->namespaceCacheEntries($directory, false) as [$namespace, $path]) { try { - $loaded = include $path; + $loaded = $this->readNamespaceFile($path); } catch (\Throwable) { continue; } - if (is_array($loaded)) { - $this->collectFlatLeafIndex($namespace, $loaded, $index); - } + $this->collectFlatLeafIndex($namespace, $loaded, $index); } return $index; @@ -372,6 +369,7 @@ private function buildFlatLeafIndexFromDirectory(string $directory): array /** * @param array $excluded + * @throws \RuntimeException */ private function copyActiveNamespaceCacheFiles(string $stage, array $excluded): void { @@ -394,6 +392,9 @@ private function copyActiveNamespaceCacheFiles(string $stage, array $excluded): } } + /** + * @throws \RuntimeException + */ private function createGenerationStage(): string { $root = $this->namespaceCacheDirectory; @@ -510,6 +511,7 @@ private function namespaceCachePath(string $namespace, ?string $directory): ?str /** * @param string[]|null $namespaces + * @throws \Throwable */ private function publishFlushGeneration(?array $namespaces): void { @@ -533,6 +535,7 @@ private function publishFlushGeneration(?array $namespaces): void /** * @param string[] $namespaces + * @throws \Throwable */ private function publishWarmGeneration(array $namespaces): void { @@ -577,7 +580,8 @@ private function readerNamespaceCacheDirectory(): ?string private function removeGenerationDirectory(string $directory): void { - foreach (scandir($directory) ?: [] as $entry) { + $entries = scandir($directory); + foreach ($entries === false ? [] : $entries as $entry) { if ($entry === '.' || $entry === '..') { continue; } @@ -598,6 +602,9 @@ private function warmNamespaceCacheFile(string $namespace): ?string return $path !== null && is_file($path) && is_readable($path) ? $path : null; } + /** + * @throws \RuntimeException + */ private function withNamespaceCacheLock(\Closure $operation): static { $directory = $this->namespaceCacheDirectory; @@ -624,6 +631,9 @@ private function withNamespaceCacheLock(\Closure $operation): static return $this; } + /** + * @throws \RuntimeException + */ private function writeGenerationFlatIndex(string $directory): void { $index = $this->buildFlatLeafIndexFromDirectory($directory); @@ -635,6 +645,9 @@ private function writeGenerationFlatIndex(string $directory): void } } + /** + * @throws \RuntimeException + */ private function writeGenerationPointer(string $generation): void { $path = $this->generationPointerPath(); diff --git a/src/Config/Config.php b/src/Config/Config.php index 8b86d36..b0382f7 100644 --- a/src/Config/Config.php +++ b/src/Config/Config.php @@ -25,6 +25,8 @@ class Config * Hook-aware variant of fill(). * * @param string|array $key + * @throws \RuntimeException + * @throws \InvalidArgumentException */ public function fillWithHooks(string|array $key, mixed $value = null): bool { @@ -74,6 +76,8 @@ public function getWithHooks(int|string|array|null $key = null, mixed $default = * Hook-aware variant of set(). * * @param string|array|null $key + * @throws \RuntimeException + * @throws \InvalidArgumentException */ public function setWithHooks(string|array|null $key = null, mixed $value = null, bool $overwrite = true): bool { diff --git a/src/Config/EnvParser.php b/src/Config/EnvParser.php index 6e0cf75..d3c383b 100644 --- a/src/Config/EnvParser.php +++ b/src/Config/EnvParser.php @@ -15,6 +15,7 @@ private function __construct() {} /** * @return array + * @throws \UnexpectedValueException */ public static function parse(string $contents): array { @@ -25,6 +26,8 @@ public static function parse(string $contents): array /** * @return array + * @throws \InvalidArgumentException + * @throws \UnexpectedValueException */ public static function parseFile(string $path): array { @@ -33,6 +36,8 @@ public static function parseFile(string $path): array /** * @return array + * @throws \InvalidArgumentException + * @throws \UnexpectedValueException */ public static function parseFileRaw(string $path): array { @@ -42,6 +47,7 @@ public static function parseFileRaw(string $path): array /** * @param iterable $lines * @return array + * @throws \UnexpectedValueException */ public static function parseLines(iterable $lines): array { @@ -51,6 +57,7 @@ public static function parseLines(iterable $lines): array /** * @param iterable $lines * @return array + * @throws \UnexpectedValueException */ public static function parseLinesRaw(iterable $lines): array { @@ -61,6 +68,7 @@ public static function parseLinesRaw(iterable $lines): array * Parse values without expanding variable references. * * @return array + * @throws \UnexpectedValueException */ public static function parseRaw(string $contents): array { @@ -69,6 +77,9 @@ public static function parseRaw(string $contents): array return EnvValueResolver::restoreLiteralDollars(EnvLineParser::parseContents($contents)); } + /** + * @throws \UnexpectedValueException + */ private static function assertSafeContents(string $contents, string $path): void { if (str_starts_with($contents, "\xEF\xBB\xBF")) { @@ -80,6 +91,10 @@ private static function assertSafeContents(string $contents, string $path): void } } + /** + * @throws \InvalidArgumentException + * @throws \UnexpectedValueException + */ private static function readFile(string $path): string { if (!is_file($path) || !is_readable($path)) { @@ -99,6 +114,7 @@ private static function readFile(string $path): string /** * @param iterable $lines * @return \Generator + * @throws \UnexpectedValueException */ private static function safeLines(iterable $lines): \Generator { diff --git a/src/Config/LayeredLazyFileConfig.php b/src/Config/LayeredLazyFileConfig.php index 8e5f772..7f571a3 100644 --- a/src/Config/LayeredLazyFileConfig.php +++ b/src/Config/LayeredLazyFileConfig.php @@ -11,6 +11,8 @@ * Namespace materialization is used deliberately so exact-path reads always * match reads against the fully merged configuration, including list/scalar * shadowing semantics. + * + * @api */ class LayeredLazyFileConfig extends Config { @@ -48,7 +50,11 @@ public function __construct( } } - /** @return array */ + /** + * @return array + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function all(): array { @@ -57,6 +63,10 @@ public function all(): array return parent::all(); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function changed(string $snapshot = 'default'): bool { @@ -65,6 +75,9 @@ public function changed(string $snapshot = 'default'): bool return parent::changed($snapshot); } + /** + * @throws \RuntimeException + */ public function clearNamespaceCache(): static { $this->source->flushNamespaceCache(); @@ -72,6 +85,10 @@ public function clearNamespaceCache(): static return $this; } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function exportCache(string $path): bool { @@ -80,6 +97,10 @@ public function exportCache(string $path): bool return parent::exportCache($path); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function fill(string|array $key, mixed $value = null): bool { @@ -88,6 +109,10 @@ public function fill(string|array $key, mixed $value = null): bool return parent::fill($key, $value); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function forget(string|int|array $key): bool { @@ -96,6 +121,10 @@ public function forget(string|int|array $key): bool return parent::forget($key); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function get(string|int|array|null $key = null, mixed $default = null): mixed { @@ -106,6 +135,10 @@ public function get(string|int|array|null $key = null, mixed $default = null): m return parent::get($key, $default); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function loadArray(array $resource): bool { @@ -114,6 +147,10 @@ public function loadArray(array $resource): bool return parent::loadArray($resource); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function loadFile(string $path): bool { @@ -122,6 +159,10 @@ public function loadFile(string $path): bool return parent::loadFile($path); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function merge(array $items): bool { @@ -135,6 +176,10 @@ public function namespaceCacheDirectory(): ?string return $this->source->namespaceCacheDirectory(); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function overlay(array $overlay): bool { @@ -177,6 +222,10 @@ public function restore(string $name = 'default'): bool return $restored; } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function set(string|array|null $key = null, mixed $value = null, bool $overwrite = true): bool { @@ -196,6 +245,10 @@ public function set(string|array|null $key = null, mixed $value = null, bool $ov return parent::set($key, $value, $overwrite); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] public function snapshot(string $name = 'default'): bool { @@ -206,6 +259,8 @@ public function snapshot(string $name = 'default'): bool /** * @param string|array|null $namespaces + * @throws \RuntimeException + * @throws \InvalidArgumentException */ public function warmNamespaceCache(string|array|null $namespaces = null): static { @@ -215,6 +270,10 @@ public function warmNamespaceCache(string|array|null $namespaces = null): static return $this; } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ #[\Override] protected function resolveRawValue(int|string $key): mixed { @@ -235,6 +294,10 @@ private function markAllKnownNamespacesMaterialized(): void } } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ private function materializeKnownNamespaces(): void { foreach (array_keys($this->knownNamespaces) as $namespace) { @@ -244,6 +307,8 @@ private function materializeKnownNamespaces(): void /** * @param string|int|array $targets + * @throws \RuntimeException + * @throws \InvalidArgumentException */ private function materializeMutationTargets(string|int|array $targets): void { @@ -261,6 +326,10 @@ private function materializeMutationTargets(string|int|array $targets): void $this->materializeNamespace($this->namespaceFromPath((string) $targets)); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ private function materializeNamespace(string $namespace): void { if ($namespace === '' || isset($this->materializedNamespaces[$namespace])) { diff --git a/src/Config/LazyFileConfig.php b/src/Config/LazyFileConfig.php index 99fcc33..43db059 100644 --- a/src/Config/LazyFileConfig.php +++ b/src/Config/LazyFileConfig.php @@ -42,19 +42,22 @@ public function __construct( $this->syncLoadedNamespacesFromItems(); } - #[\Override] /** * @return array + * @throws \RuntimeException */ + #[\Override] public function all(): array { throw new RuntimeException('LazyFileConfig does not support full config retrieval. At least one key is required.'); } - #[\Override] /** * @param string|array $key + * @throws \RuntimeException + * @throws \InvalidArgumentException */ + #[\Override] public function fill(string|array $key, mixed $value = null): bool { $this->assertWritable(); @@ -65,10 +68,12 @@ public function fill(string|array $key, mixed $value = null): bool return true; } - #[\Override] /** * @param string|int|array $key + * @throws \RuntimeException + * @throws \InvalidArgumentException */ + #[\Override] public function forget(string|int|array $key): bool { $this->assertWritable(); @@ -85,10 +90,12 @@ public function forget(string|int|array $key): bool return true; } - #[\Override] /** * @param string|int|array|null $key + * @throws \RuntimeException + * @throws \InvalidArgumentException */ + #[\Override] public function get(string|int|array|null $key = null, mixed $default = null): mixed { if ($key === null) { @@ -115,10 +122,10 @@ public function get(string|int|array|null $key = null, mixed $default = null): m return $this->getResolvedValue($key, $default); } - #[\Override] /** * @param string|array $keys */ + #[\Override] public function has(string|array $keys): bool { $keys = (array) $keys; @@ -129,10 +136,10 @@ public function has(string|array $keys): bool return array_all($keys, fn($path) => $this->hasResolvedValue($path)); } - #[\Override] /** * @param string|array $keys */ + #[\Override] public function hasAny(string|array $keys): bool { $keys = (array) $keys; @@ -145,16 +152,17 @@ public function hasAny(string|array $keys): bool /** * Returns true if the namespace has already been resolved (file found or missing). + * @throws \InvalidArgumentException */ public function isLoaded(string $namespace): bool { return isset($this->loadedNamespaces[$this->normalizeNamespace($namespace)]); } - #[\Override] /** * @param array $resource */ + #[\Override] public function loadArray(array $resource): bool { return $this->syncLoadedNamespacesAfter(parent::loadArray($resource)); @@ -162,6 +170,7 @@ public function loadArray(array $resource): bool /** * Alias of isLoaded(). + * @throws \InvalidArgumentException */ public function loaded(string $namespace): bool { @@ -182,10 +191,10 @@ public function loadFile(string $path): bool return $this->syncLoadedNamespacesAfter(parent::loadFile($path)); } - #[\Override] /** * @param array $items */ + #[\Override] public function merge(array $items): bool { $changed = parent::merge($items); @@ -204,6 +213,8 @@ public function merge(array $items): bool * Preload one or multiple top-level config namespaces. * * @param string|array $namespaces Namespace (e.g. "db") or list of namespaces. + * @throws \UnexpectedValueException + * @throws \InvalidArgumentException */ public function preload(string|array $namespaces): static { @@ -214,10 +225,11 @@ public function preload(string|array $namespaces): static return $this; } - #[\Override] /** * @param array|string $source + * @throws \RuntimeException */ + #[\Override] public function reload(array|string $source): bool { $this->assertWritable(); @@ -225,10 +237,11 @@ public function reload(array|string $source): bool return $this->syncLoadedNamespacesAfter(parent::reload($source)); } - #[\Override] /** * @param array $items + * @throws \RuntimeException */ + #[\Override] public function replace(array $items): bool { $this->assertWritable(); @@ -242,10 +255,12 @@ public function restore(string $name = 'default'): bool return $this->syncLoadedNamespacesAfter(parent::restore($name)); } - #[\Override] /** * @param string|array|null $key + * @throws \RuntimeException + * @throws \InvalidArgumentException */ + #[\Override] public function set(string|array|null $key = null, mixed $value = null, bool $overwrite = true): bool { $this->assertWritable(); @@ -260,6 +275,10 @@ public function set(string|array|null $key = null, mixed $value = null, bool $ov return true; } + /** + * @throws \InvalidArgumentException + * @throws \UnexpectedValueException + */ protected function forgetPath(string $path): void { [$namespace, $rest] = $this->splitPath($path); @@ -286,6 +305,10 @@ protected function forgetPath(string $path): void $this->markNamespaceRuntime($namespace); } + /** + * @throws \InvalidArgumentException + * @throws \UnexpectedValueException + */ protected function getPath(string $path, mixed $default): mixed { [$namespace, $rest] = $this->splitPath($path); @@ -294,6 +317,10 @@ protected function getPath(string $path, mixed $default): mixed return $this->resolveLoadedNamespaceValue($namespace, $rest, $default); } + /** + * @throws \InvalidArgumentException + * @throws \UnexpectedValueException + */ protected function hasPath(string $path): bool { [$namespace, $rest] = $this->splitPath($path); @@ -314,6 +341,9 @@ protected function hasPath(string $path): bool return DotNotation::has($this->items[$namespace], $rest); } + /** + * @throws \UnexpectedValueException + */ protected function loadNamespace(string $namespace): void { if (isset($this->loadedNamespaces[$namespace])) { @@ -331,10 +361,7 @@ protected function loadNamespace(string $namespace): void return; } - $loaded = include $file; - if (!is_array($loaded)) { - throw new UnexpectedValueException("Config file [{$file}] must return an array."); - } + $loaded = $this->readNamespaceFile($file); $this->loadedNamespaces[$namespace] = true; $this->loadedNamespaceOrigins[$namespace] = $cachedFile !== null ? 'cache' : 'source'; @@ -352,6 +379,9 @@ protected function loadNamespace(string $namespace): void } } + /** + * @throws \InvalidArgumentException + */ protected function normalizeNamespace(string $namespace): string { $trimmed = trim($namespace); @@ -362,6 +392,24 @@ protected function normalizeNamespace(string $namespace): string return $trimmed; } + /** + * @return array + * @throws UnexpectedValueException + */ + protected function readNamespaceFile(string $file): array + { + if (!is_file($file) || !is_readable($file)) { + throw new UnexpectedValueException("Config file [{$file}] is no longer readable."); + } + + $loaded = include $file; + if (!is_array($loaded)) { + throw new UnexpectedValueException("Config file [{$file}] must return an array."); + } + + return $loaded; + } + protected function resolveCachedNamespaceFile(string $namespace): ?string { $path = $this->cachedNamespacePath($namespace); @@ -373,6 +421,10 @@ protected function resolveCachedNamespaceFile(string $namespace): ?string return $path; } + /** + * @throws \InvalidArgumentException + * @throws \UnexpectedValueException + */ protected function resolveLazyRawValue(string $path): mixed { [$namespace, $rest] = $this->splitPath($path); @@ -408,6 +460,10 @@ protected function resolveNamespaceFile(string $namespace): ?string return $file; } + /** + * @throws \InvalidArgumentException + * @throws \UnexpectedValueException + */ #[\Override] protected function resolveRawValue(int|string $key): mixed { @@ -427,6 +483,10 @@ protected function resolveRawValue(int|string $key): mixed return $this->cacheResolvedValue($cacheKey, $this->resolveLazyRawValue($key)); } + /** + * @throws \InvalidArgumentException + * @throws \UnexpectedValueException + */ protected function setPath(string $path, mixed $value, bool $overwrite): void { [$namespace, $rest] = $this->splitPath($path); @@ -453,6 +513,7 @@ protected function setPath(string $path, mixed $value, bool $overwrite): void /** * @return array{0: string, 1: string|null} + * @throws \InvalidArgumentException */ protected function splitPath(string $path): array { @@ -522,7 +583,11 @@ private function syncLoadedNamespacesAfter(bool $changed): bool return $changed; } - /** @param string|array $key */ + /** + * @param string|array $key + * @throws \InvalidArgumentException + * @throws \UnexpectedValueException + */ private function writePaths(string|array $key, mixed $value, bool $overwrite, string $operation): void { if (is_string($key)) { diff --git a/src/Config/ResilientLazyFileConfig.php b/src/Config/ResilientLazyFileConfig.php index 02945f5..830ad60 100644 --- a/src/Config/ResilientLazyFileConfig.php +++ b/src/Config/ResilientLazyFileConfig.php @@ -4,14 +4,17 @@ namespace Infocyph\ArrayKit\Config; -use UnexpectedValueException; - /** * Lazy file configuration that treats generated namespace-cache corruption as * a cache miss while keeping source configuration failures visible. + * + * @api */ class ResilientLazyFileConfig extends LazyFileConfig { + /** + * @throws \UnexpectedValueException + */ #[\Override] protected function loadNamespace(string $namespace): void { @@ -32,10 +35,7 @@ protected function loadNamespace(string $namespace): void return; } - $loaded = include $source; - if (!is_array($loaded)) { - throw new UnexpectedValueException("Config file [{$source}] must return an array."); - } + $loaded = $this->readNamespaceFile($source); } $this->loadedNamespaces[$namespace] = true; @@ -60,11 +60,9 @@ protected function loadNamespace(string $namespace): void private function loadCachedNamespace(string $cache): ?array { try { - $loaded = include $cache; + return $this->readNamespaceFile($cache); } catch (\Throwable) { return null; } - - return is_array($loaded) ? $loaded : null; } } diff --git a/src/Config/Support/ConfigSnapshot.php b/src/Config/Support/ConfigSnapshot.php index 3eedd7a..98e2f09 100644 --- a/src/Config/Support/ConfigSnapshot.php +++ b/src/Config/Support/ConfigSnapshot.php @@ -21,6 +21,7 @@ final class ConfigSnapshot * * @param array $items * @return array + * @throws \UnexpectedValueException */ public static function detach(array $items): array { @@ -36,6 +37,7 @@ public static function detach(array $items): array * @param array $active * @param array $copies * @return array + * @throws \UnexpectedValueException */ private static function copy(array $items, array &$active, array &$copies, int &$visited, int $depth = 1): array { @@ -64,6 +66,7 @@ private static function copy(array $items, array &$active, array &$copies, int & /** * @param array $active * @param array $copies + * @throws \UnexpectedValueException */ private static function copyReference( mixed $value, diff --git a/src/Config/Support/EnvLineParser.php b/src/Config/Support/EnvLineParser.php index 332d4fe..524f690 100644 --- a/src/Config/Support/EnvLineParser.php +++ b/src/Config/Support/EnvLineParser.php @@ -15,6 +15,7 @@ private function __construct() {} /** * @return array + * @throws \UnexpectedValueException */ public static function parseContents(string $contents): array { @@ -24,6 +25,7 @@ public static function parseContents(string $contents): array /** * @param iterable $lines * @return array + * @throws \UnexpectedValueException */ public static function parseLines(iterable $lines): array { @@ -52,6 +54,9 @@ public static function parseLines(iterable $lines): array return $items; } + /** + * @throws \UnexpectedValueException + */ private static function assertQuotedValueRemainder(string $remainder): void { $remainder = trim($remainder); @@ -129,6 +134,9 @@ private static function openValueQuote(string $line): ?string return $value !== '' && ($value[0] === '"' || $value[0] === '\'') ? $value[0] : null; } + /** + * @throws \UnexpectedValueException + */ private static function parseQuotedValue(string $value, string $quote): string { $length = strlen($value); @@ -156,6 +164,9 @@ private static function parseQuotedValue(string $value, string $quote): string throw new UnexpectedValueException('Unclosed quoted environment value.'); } + /** + * @throws \UnexpectedValueException + */ private static function parseValue(string $value): string { if ($value === '') { @@ -210,7 +221,7 @@ private static function stripInlineComment(string $value): string { $length = strlen($value); for ($index = 0; $index < $length; $index++) { - if ($value[$index] === '#' && $index > 0 && str_contains(" \t\n\r\0\x0B", $value[$index - 1])) { + if ($value[$index] === '#' && $index > 0 && in_array($value[$index - 1], [' ', "\t", "\n", "\r", "\0", "\x0B"], true)) { return substr($value, 0, $index); } } diff --git a/src/Config/Support/EnvValueResolver.php b/src/Config/Support/EnvValueResolver.php index 3094fcb..9db1aa9 100644 --- a/src/Config/Support/EnvValueResolver.php +++ b/src/Config/Support/EnvValueResolver.php @@ -31,6 +31,7 @@ public static function protectEscapedDollars(string $value): string /** * @param array $items * @return array + * @throws \UnexpectedValueException */ public static function resolve(array $items): array { @@ -57,6 +58,9 @@ public static function restoreLiteralDollars(array $items): array return $items; } + /** + * @throws \UnexpectedValueException + */ private static function assertClosedVariableExpansions(string $value): void { $length = strlen($value); @@ -111,6 +115,7 @@ private static function lookupExternalVariable(string $name): ?string * @param array $items * @param array $resolved * @param array $resolving + * @throws \UnexpectedValueException */ private static function lookupVariable(string $name, array $items, array &$resolved, array $resolving): ?string { @@ -134,6 +139,7 @@ private static function lookupVariable(string $name, array $items, array &$resol * @param array $items * @param array $resolved * @param array $resolving + * @throws \UnexpectedValueException */ private static function resolveMatch(array $matches, array $items, array &$resolved, array $resolving): string { @@ -160,6 +166,7 @@ private static function resolveMatch(array $matches, array $items, array &$resol * @param array $items * @param array $resolved * @param array $resolving + * @throws \UnexpectedValueException */ private static function resolveName(string $name, array $items, array &$resolved, array $resolving): ?string { @@ -185,6 +192,7 @@ private static function resolveName(string $name, array $items, array &$resolved * @param array $items * @param array $resolved * @param array $resolving + * @throws \UnexpectedValueException */ private static function resolveVariables(string $value, array $items, array &$resolved, array $resolving): string { diff --git a/src/DTO/Concerns/DTOTrait.php b/src/DTO/Concerns/DTOTrait.php index 33c7c09..f81b0c2 100644 --- a/src/DTO/Concerns/DTOTrait.php +++ b/src/DTO/Concerns/DTOTrait.php @@ -86,6 +86,8 @@ public function hydrateNested(array $values, array $mapping = [], bool $coerce = * * @param array $values * @param array $mapping + * @throws \InvalidArgumentException + * @throws \RuntimeException */ public function hydrateNestedGuarded( array $values, @@ -145,6 +147,8 @@ public function toArrayDeep(): array * configured cycle, depth and node limits. * * @return array + * @throws \InvalidArgumentException + * @throws \RuntimeException */ public function toArrayDeepGuarded(int $maxDepth = 64, int $maxNodes = 100000): array { @@ -235,7 +239,7 @@ private function resolveNestedValue(string $property, mixed $value): mixed } $className = $type->getName(); - if (is_callable([$className, 'create'])) { + if (class_exists($className) && is_callable([$className, 'create'])) { return $className::create($value); } diff --git a/src/DTO/DTO.php b/src/DTO/DTO.php index b8b6a19..eaea788 100644 --- a/src/DTO/DTO.php +++ b/src/DTO/DTO.php @@ -10,6 +10,7 @@ * Optional abstract base for DTOs that expose their own public value properties. * * @phpstan-consistent-constructor + * @psalm-consistent-constructor */ abstract class DTO { diff --git a/src/DTO/DTOGraphGuard.php b/src/DTO/DTOGraphGuard.php index ad33e87..0f07251 100644 --- a/src/DTO/DTOGraphGuard.php +++ b/src/DTO/DTOGraphGuard.php @@ -16,12 +16,20 @@ /** @internal */ final class DTOGraphGuard { + /** + * @throws \InvalidArgumentException + * @throws \RuntimeException + */ public static function assertWithinLimits(mixed $value, int $maxDepth, int $maxNodes): void { self::traverse($value, $maxDepth, $maxNodes, false); } - /** @return array */ + /** + * @return array + * @throws \InvalidArgumentException + * @throws \RuntimeException + */ public static function export(object $value, int $maxDepth, int $maxNodes): array { $result = self::traverse($value, $maxDepth, $maxNodes, true); @@ -32,6 +40,9 @@ public static function export(object $value, int $maxDepth, int $maxNodes): arra return $result; } + /** + * @throws \RuntimeException + */ private static function assertNodeWithinLimits( int $depth, int &$visitedNodes, @@ -48,6 +59,9 @@ private static function assertNodeWithinLimits( } } + /** + * @throws \InvalidArgumentException + */ private static function isStandardExporter(object $value): bool { if (!is_callable([$value, 'toArrayDeep']) && !is_callable([$value, 'toArray'])) { @@ -67,6 +81,10 @@ private static function isStandardExporter(object $value): bool return true; } + /** + * @throws \InvalidArgumentException + * @throws \RuntimeException + */ private static function traverse(mixed $value, int $maxDepth, int $maxNodes, bool $export): mixed { if ($maxDepth < 1) { @@ -96,6 +114,7 @@ private static function traverse(mixed $value, int $maxDepth, int $maxNodes, boo /** * @param array $activeObjects * @param array $activeReferences + * @throws \RuntimeException */ private static function walk( mixed $value, @@ -142,6 +161,7 @@ private static function walk( * @param array $value * @param array $activeObjects * @param array $activeReferences + * @throws \RuntimeException */ private static function walkArray( array $value, @@ -206,6 +226,7 @@ private static function walkArray( /** * @param array $activeObjects * @param array $activeReferences + * @throws \RuntimeException */ private static function walkObject( object $value, diff --git a/src/Facade/ModuleProxy.php b/src/Facade/ModuleProxy.php index 01ffec4..517d170 100644 --- a/src/Facade/ModuleProxy.php +++ b/src/Facade/ModuleProxy.php @@ -8,10 +8,14 @@ use Infocyph\ArrayKit\Array\DotNotation; use UnexpectedValueException; +/** + * @template-covariant T of object + * @mixin T + */ final readonly class ModuleProxy { /** - * @param class-string $targetClass + * @param class-string $targetClass */ public function __construct( private string $targetClass, @@ -19,6 +23,7 @@ public function __construct( /** * @param array $arguments + * @throws \BadMethodCallException */ public function __call(string $method, array $arguments): mixed { @@ -28,6 +33,7 @@ public function __call(string $method, array $arguments): mixed /** * @param array $array * @param array|string $keys + * @throws \BadMethodCallException */ public function fill(array &$array, array|string $keys, mixed $value = null): void { @@ -39,6 +45,9 @@ public function fill(array &$array, array|string $keys, mixed $value = null): vo * @param-out array $array * @param array|int|string|null $keys * @param array|null $target Native dot-module named argument + * @throws \InvalidArgumentException + * @throws \ArgumentCountError + * @throws \BadMethodCallException */ public function forget(?array &$array = null, array|string|int|null $keys = null, ?array &$target = null): void { @@ -59,6 +68,8 @@ public function forget(?array &$array = null, array|string|int|null $keys = null /** * @param array $array + * @throws \UnexpectedValueException + * @throws \BadMethodCallException */ public function move(array &$array, string $from, string $to, bool $overwrite = true): bool { @@ -67,6 +78,7 @@ public function move(array &$array, string $from, string $to, bool $overwrite = /** * @param array $array + * @throws \BadMethodCallException */ public function offsetSet(array &$array, string $key, mixed $value): void { @@ -75,6 +87,7 @@ public function offsetSet(array &$array, string $key, mixed $value): void /** * @param array $array + * @throws \BadMethodCallException */ public function offsetUnset(array &$array, string $key): void { @@ -83,6 +96,8 @@ public function offsetUnset(array &$array, string $key): void /** * @param array $array + * @throws \UnexpectedValueException + * @throws \BadMethodCallException */ public function rename(array &$array, string $from, string $to, bool $overwrite = true): bool { @@ -92,6 +107,8 @@ public function rename(array &$array, string $from, string $to, bool $overwrite /** * @param array $array * @param array|string|null $keys + * @throws \UnexpectedValueException + * @throws \BadMethodCallException */ public function set(array &$array, array|string|null $keys = null, mixed $value = null, bool $overwrite = true): bool { @@ -100,6 +117,7 @@ public function set(array &$array, array|string|null $keys = null, mixed $value /** * @param array $arguments + * @throws \BadMethodCallException */ private function invoke(string $method, array $arguments): mixed { @@ -112,6 +130,8 @@ private function invoke(string $method, array $arguments): mixed /** * @param array $arguments + * @throws \UnexpectedValueException + * @throws \BadMethodCallException */ private function invokeBool(string $method, array $arguments): bool { diff --git a/src/functions.php b/src/functions.php index ed6ab07..685890e 100644 --- a/src/functions.php +++ b/src/functions.php @@ -68,6 +68,7 @@ function array_get(array $array, int|string|array|null $key = null, mixed $defau * @param mixed $value The value to set. * @param bool $overwrite If true, overwrite existing values. If false, existing values are preserved. * @return bool True on success + * @throws \InvalidArgumentException */ function array_set(array &$array, string|array|null $key, mixed $value = null, bool $overwrite = true): bool { @@ -110,6 +111,7 @@ function env(?string $key = null, mixed $default = null): mixed if (!function_exists('dotenv')) { /** * Access the ArrayKit .env file parser facade. + * @return ModuleProxy<\Infocyph\ArrayKit\Config\EnvParser> */ function dotenv(): ModuleProxy { diff --git a/src/namespaced-functions.php b/src/namespaced-functions.php index 62cbe4b..fee41b5 100644 --- a/src/namespaced-functions.php +++ b/src/namespaced-functions.php @@ -41,6 +41,7 @@ function array_get(array $array, int|string|array|null $key = null, mixed $defau /** * @param array $array * @param string|array|null $key + * @throws \InvalidArgumentException */ function array_set(array &$array, string|array|null $key, mixed $value = null, bool $overwrite = true): bool { @@ -70,6 +71,7 @@ function env(?string $key = null, mixed $default = null): mixed } if (!function_exists(__NAMESPACE__ . '\\dotenv')) { + /** @return ModuleProxy<\Infocyph\ArrayKit\Config\EnvParser> */ function dotenv(): ModuleProxy { return ArrayKit::dotenv(); diff --git a/tests/Feature/ApiSignatureTest.php b/tests/Feature/ApiSignatureTest.php index eaba9ea..988915a 100644 --- a/tests/Feature/ApiSignatureTest.php +++ b/tests/Feature/ApiSignatureTest.php @@ -75,18 +75,21 @@ } if ($type instanceof ReflectionUnionType) { - $parts = array_map(static fn(ReflectionNamedType $part): string => $part->getName(), $type->getTypes()); + $parts = array_map(static fn(ReflectionNamedType|ReflectionIntersectionType $part): string => (string) $part, $type->getTypes()); return $normalizeType(implode('|', $parts), $selfType); } if ($type instanceof ReflectionIntersectionType) { - $parts = array_map(static fn(ReflectionNamedType $part): string => $part->getName(), $type->getTypes()); + $parts = array_map(static fn(ReflectionType $part): string => (string) $part, $type->getTypes()); sort($parts); return $parts; } + if (!$type instanceof ReflectionNamedType) { + throw new RuntimeException('Unsupported reflection type: ' . get_debug_type($type)); + } $name = $type->getName(); if ($type->allowsNull() && $name !== 'mixed' && $name !== 'null') { $name .= '|null'; @@ -108,15 +111,19 @@ 'type' => $normalizeType($matches['type'] ?? null), 'reference' => ($matches['reference'] ?? '') === '&', 'variadic' => ($matches['variadic'] ?? '') === '...', - 'hasDefault' => array_key_exists('default', $matches) && $matches['default'] !== '', + 'hasDefault' => array_key_exists('default', $matches), 'default' => isset($matches['default']) ? ltrim(trim($matches['default']), '\\') : null, ]; }; $document = file_get_contents(__DIR__ . '/../../docs/rule-reference.rst'); - expect($document)->not->toBeFalse(); - $lines = preg_split('/\R/', (string) $document); - expect($lines)->toBeArray(); + if ($document === false) { + throw new RuntimeException('Unable to read API reference.'); + } + $lines = preg_split('/\R/', $document); + if ($lines === false) { + throw new RuntimeException('Unable to split API reference into lines.'); + } $activeClass = null; $documentedMethods = []; @@ -131,11 +138,14 @@ if (preg_match('/^\s+function Infocyph\\\\ArrayKit\\\\(?[A-Za-z_][A-Za-z0-9_]*)\((?.*)\)(?:: (?[^\/]+))?/', $line, $functionMatches) === 1) { $functionName = 'Infocyph\\ArrayKit\\' . $functionMatches['name']; + if (!function_exists($functionName)) { + throw new RuntimeException('Documented function does not exist: ' . $functionName); + } $function = new ReflectionFunction($functionName); $documentedFunctions[$functionName] = true; $documentedParameters = trim($functionMatches['parameters']) === '' ? [] - : array_map($parseParameter, preg_split('/,\s*/', $functionMatches['parameters'])); + : array_map($parseParameter, explode(',', $functionMatches['parameters'])); expect($documentedParameters)->toHaveCount(count($function->getParameters()), $functionName) ->and($reflectionType($function->getReturnType()))->toBe( @@ -164,11 +174,11 @@ $declaringType = $method->getDeclaringClass()->getShortName(); $documentedParameters = trim($matches['parameters']) === '' ? [] - : array_map($parseParameter, preg_split('/,\s*/', $matches['parameters'])); + : array_map($parseParameter, explode(',', $matches['parameters'])); $actualParameters = $method->getParameters(); expect($method->isPublic())->toBeTrue($activeClass . '::' . $method->getName()) - ->and($method->isStatic())->toBe(($matches['static'] ?? '') !== '', $activeClass . '::' . $method->getName()) + ->and($method->isStatic())->toBe($matches['static'] !== '', $activeClass . '::' . $method->getName()) ->and($documentedParameters)->toHaveCount(count($actualParameters), $activeClass . '::' . $method->getName()) ->and($reflectionType($method->getReturnType(), $declaringType))->toBe( $normalizeType(isset($matches['return']) ? trim($matches['return']) : null, $declaringType), @@ -179,8 +189,8 @@ $documented = $documentedParameters[$parameterIndex]; $actualDefault = null; if ($actual->isDefaultValueAvailable()) { - if ($actual->isDefaultValueConstant()) { - $constantName = ltrim((string) $actual->getDefaultValueConstantName(), '\\'); + if (($constant = $actual->getDefaultValueConstantName()) !== null) { + $constantName = ltrim($constant, '\\'); $actualDefault = basename(str_replace('\\', '/', $constantName)); } elseif ($actual->getDefaultValue() === null) { $actualDefault = 'null'; diff --git a/tests/Feature/ArrayKitFacadeTest.php b/tests/Feature/ArrayKitFacadeTest.php index 06a8cf6..4348254 100644 --- a/tests/Feature/ArrayKitFacadeTest.php +++ b/tests/Feature/ArrayKitFacadeTest.php @@ -10,6 +10,7 @@ use Infocyph\ArrayKit\Config\LazyFileConfig; use Infocyph\ArrayKit\Facade\ModuleProxy; +/** @param array $contents */ function arrayKitWriteArrayFile(string $directory, string $name, array $contents): void { $export = var_export($contents, true); @@ -65,7 +66,7 @@ function arrayKitDeleteDirectory(string $directory): void it('exposes array modules through one facade', function () { $single = ArrayKit::single(); - expect($single)->toBeInstanceOf(ModuleProxy::class) + expect(get_class($single))->toBe(ModuleProxy::class) ->and(ArrayKit::single())->toBe($single) ->and($single->isList([1, 2, 3]))->toBeTrue() ->and(ArrayKit::multi()->flatten([[1], [2, [3]]]))->toBe([1, 2, 3]) @@ -74,14 +75,14 @@ function arrayKitDeleteDirectory(string $directory): void }); it('does not expose private module methods through the facade', function () { - expect(fn () => ArrayKit::single()->toNumericOrNull(1)) + expect(static fn(): mixed => ArrayKit::single()->__call('toNumericOrNull', [1])) ->toThrow(BadMethodCallException::class); }); it('creates config instances from the facade', function () { $config = ArrayKit::config(['app' => ['name' => 'ArrayKit']]); - expect($config)->toBeInstanceOf(Config::class) + expect(get_class($config))->toBe(Config::class) ->and($config->get('app.name'))->toBe('ArrayKit'); }); @@ -90,7 +91,7 @@ function arrayKitDeleteDirectory(string $directory): void $config = ArrayKit::lazyConfig($this->configPath, namespaceCacheDirectory: $this->configPath.DIRECTORY_SEPARATOR.'cache'); - expect($config)->toBeInstanceOf(LazyFileConfig::class) + expect(get_class($config))->toBe(LazyFileConfig::class) ->and($config->get('db.host'))->toBe('localhost') ->and($config->namespaceCacheDirectory())->toBe($this->configPath.DIRECTORY_SEPARATOR.'cache'); }); @@ -101,9 +102,9 @@ function arrayKitDeleteDirectory(string $directory): void $lazy = ArrayKit::lazyCollection([1, 2, 3]); $sum = ArrayKit::pipeline([1, 2, 3])->sum(); - expect($collection)->toBeInstanceOf(Collection::class) - ->and($hooked)->toBeInstanceOf(HookedCollection::class) - ->and($lazy)->toBeInstanceOf(LazyCollection::class) - ->and($lazy->mapLazy(fn (int $v) => $v * 2)->all())->toBe([2, 4, 6]) + expect(get_class($collection))->toBe(Collection::class) + ->and(get_class($hooked))->toBe(HookedCollection::class) + ->and(get_class($lazy))->toBe(LazyCollection::class) + ->and($lazy->mapLazy(static fn(mixed $v): int => is_int($v) ? $v * 2 : throw new UnexpectedValueException('Expected an integer.'))->all())->toBe([2, 4, 6]) ->and($sum)->toBe(6); }); diff --git a/tests/Feature/ArrayMultiTest.php b/tests/Feature/ArrayMultiTest.php index f8ed7fe..4a09f65 100644 --- a/tests/Feature/ArrayMultiTest.php +++ b/tests/Feature/ArrayMultiTest.php @@ -4,6 +4,34 @@ use Infocyph\ArrayKit\Array\ArrayMulti; +/** + * @param array $row + * @throws UnexpectedValueException + */ +function arrayMultiFixtureInt(array $row, string $key): int +{ + $value = $row[$key] ?? null; + if (!is_int($value)) { + throw new UnexpectedValueException('Expected integer fixture field: ' . $key); + } + + return $value; +} + +/** + * @param array $row + * @throws UnexpectedValueException + */ +function arrayMultiFixtureText(array $row, string $key): string +{ + $value = $row[$key] ?? null; + if (!is_string($value)) { + throw new UnexpectedValueException('Expected string fixture field: ' . $key); + } + + return $value; +} + it('can collapse a multi-dimensional array', function () { $source = [[1, 2], [3, 4], [5]]; $result = ArrayMulti::collapse($source); @@ -134,7 +162,7 @@ $sorted = ArrayMulti::sortBy($data, 'score', false, SORT_NUMERIC); - expect(array_values(array_column($sorted, 'score')))->toBe(['1', '2', '10']); + expect(array_column($sorted, 'score'))->toBe(['1', '2', '10']); }); // sortRecursive() descending @@ -168,8 +196,7 @@ ['a' => 2], ['a' => 3], ]; - $result = ArrayMulti::first($data, fn ($row) => $row['a'] > 1, 'default'); - expect($result)->toBe(['a' => 2]); + expect(ArrayMulti::first($data, static fn(array $row): bool => arrayMultiFixtureInt($row, 'a') > 1, 'default'))->toBe(['a' => 2]); }); // last() @@ -188,8 +215,7 @@ ['a' => 2], ['a' => 3], ]; - $result = ArrayMulti::last($data, fn ($row) => $row['a'] < 3, 'default'); - expect($result)->toBe(['a' => 2]); + expect(ArrayMulti::last($data, static fn(array $row): bool => arrayMultiFixtureInt($row, 'a') < 3, 'default'))->toBe(['a' => 2]); }); // between() @@ -214,8 +240,7 @@ ['a' => 2], ['a' => 3], ]; - $result = ArrayMulti::whereCallback($data, fn ($row) => $row['a'] > 1); - expect($result)->toBe([ + expect(ArrayMulti::whereCallback($data, static fn(array $row): bool => arrayMultiFixtureInt($row, 'a') > 1))->toBe([ 1 => ['a' => 2], 2 => ['a' => 3], ]); @@ -259,7 +284,7 @@ ['num' => 2], ['num' => 3], ]; - $result = ArrayMulti::map($data, fn ($row) => $row['num'] * 10); + $result = ArrayMulti::map($data, static fn(array $row): int => arrayMultiFixtureInt($row, 'num') * 10); expect($result)->toBe([ 0 => 10, 1 => 20, @@ -275,8 +300,8 @@ ['a' => 3], ]; $sum = 0; - ArrayMulti::each($data, function ($row) use (&$sum) { - $sum += $row['a']; + ArrayMulti::each($data, static function (array $row) use (&$sum): void { + $sum += arrayMultiFixtureInt($row, 'a'); }); expect($sum)->toBe(6); }); @@ -288,8 +313,7 @@ ['num' => 3], ['num' => 4], ]; - $result = ArrayMulti::reduce($data, fn ($carry, $row) => $carry + $row['num'], 0); - expect($result)->toBe(9); + expect(ArrayMulti::reduce($data, static fn(int $carry, array $row): int => $carry + arrayMultiFixtureInt($row, 'num'), 0))->toBe(9); }); // some() @@ -299,7 +323,7 @@ ['flag' => false], ['flag' => true], ]; - expect(ArrayMulti::some($data, fn ($row) => $row['flag']))->toBeTrue(); + expect(ArrayMulti::some($data, static fn(array $row): bool => ($row['flag'] ?? null) === true))->toBeTrue(); }); // every() @@ -308,9 +332,9 @@ ['pass' => true], ['pass' => true], ]; - expect(ArrayMulti::every($data, fn ($row) => $row['pass']))->toBeTrue(); + expect(ArrayMulti::every($data, static fn(array $row): bool => ($row['pass'] ?? null) === true))->toBeTrue(); $data[1]['pass'] = false; - expect(ArrayMulti::every($data, fn ($row) => $row['pass']))->toBeFalse(); + expect(ArrayMulti::every($data, static fn(array $row): bool => ($row['pass'] ?? null) === true))->toBeFalse(); }); // contains() @@ -341,7 +365,7 @@ 4 => ['val' => 2], ]; - expect(ArrayMulti::sum($data, fn (array $row, int $key) => $row['val'] + $key))->toBe(9); + expect(ArrayMulti::sum($data, static fn(array $row, int $key): int => arrayMultiFixtureInt($row, 'val') + $key))->toBe(9); }); // partition() @@ -351,7 +375,7 @@ ['score' => 50], ['score' => 90], ]; - [$pass, $fail] = ArrayMulti::partition($data, fn ($row) => $row['score'] >= 60); + [$pass, $fail] = ArrayMulti::partition($data, static fn(array $row): bool => arrayMultiFixtureInt($row, 'score') >= 60); expect($pass)->toBe([ 0 => ['score' => 80], 2 => ['score' => 90], @@ -539,14 +563,14 @@ 11 => ['id' => 11, 'team' => 'B', 'score' => 70], 12 => ['id' => 12, 'team' => 'A', 'score' => 55], ]) - ->and(ArrayMulti::indexBy($rows, fn (array $row) => 'row_'.$row['id']))->toBe([ + ->and(ArrayMulti::indexBy($rows, static fn(array $row): string => 'row_' . arrayMultiFixtureInt($row, 'id')))->toBe([ 'row_10' => ['id' => 10, 'team' => 'A', 'score' => 40], 'row_11' => ['id' => 11, 'team' => 'B', 'score' => 70], 'row_12' => ['id' => 12, 'team' => 'A', 'score' => 55], ]) ->and(ArrayMulti::countBy($rows, 'team'))->toBe(['A' => 2, 'B' => 1]) ->and(ArrayMulti::firstWhere($rows, 'score', '>=', 50))->toBe(['id' => 11, 'team' => 'B', 'score' => 70]) - ->and(ArrayMulti::mapWithKeys($rows, fn (array $row) => [$row['id'] => $row['team']]))->toBe([10 => 'A', 11 => 'B', 12 => 'A']); + ->and(ArrayMulti::mapWithKeys($rows, static fn(array $row): array => [arrayMultiFixtureInt($row, 'id') => arrayMultiFixtureText($row, 'team')]))->toBe([10 => 'A', 11 => 'B', 12 => 'A']); }); it('supports min/max/minBy/maxBy helpers', function () { @@ -570,15 +594,15 @@ $sorted = ArrayMulti::sortBy( $rows, - fn (array $row, string $key) => $key.':'.$row['id'], + static fn(array $row, string $key): string => $key . ':' . arrayMultiFixtureInt($row, 'id'), false, SORT_STRING, ); expect(array_keys($sorted))->toBe(['a', 'z']) - ->and(ArrayMulti::maxBy($rows, fn (array $row, string $key) => $row['score'] + ($key === 'z' ? 100 : 0))) + ->and(ArrayMulti::maxBy($rows, static fn(array $row, string $key): int => arrayMultiFixtureInt($row, 'score') + ($key === 'z' ? 100 : 0))) ->toBe(['id' => 1, 'score' => 10]) - ->and(ArrayMulti::minBy($rows, fn (array $row, string $key) => $row['score'] + ($key === 'z' ? 100 : 0))) + ->and(ArrayMulti::minBy($rows, static fn(array $row, string $key): int => arrayMultiFixtureInt($row, 'score') + ($key === 'z' ? 100 : 0))) ->toBe(['id' => 2, 'score' => 20]); }); @@ -637,10 +661,10 @@ ['id' => 3, 'email' => 'b@example.com'], ]; - expect(ArrayMulti::uniqueBy($rows, fn (array $row) => strtolower($row['email'])))->toBe([ + expect(ArrayMulti::uniqueBy($rows, static fn(array $row): string => strtolower(arrayMultiFixtureText($row, 'email'))))->toBe([ 0 => ['id' => 1, 'email' => 'A@example.com'], 2 => ['id' => 3, 'email' => 'b@example.com'], - ])->and(ArrayMulti::duplicatesBy($rows, fn (array $row) => strtolower($row['email'])))->toBe([ + ])->and(ArrayMulti::duplicatesBy($rows, static fn(array $row): string => strtolower(arrayMultiFixtureText($row, 'email'))))->toBe([ 1 => ['id' => 2, 'email' => 'a@example.com'], ]); }); @@ -649,6 +673,9 @@ $firstObject = new stdClass(); $secondObject = new stdClass(); $resource = fopen('php://memory', 'rb'); + if ($resource === false) { + throw new RuntimeException('Failed to open fixture stream.'); + } $rows = [ ['value' => 0], @@ -719,7 +746,7 @@ function (array $row, string $key) use (&$calls): int { $calls[] = $key; - return $row['score']; + return arrayMultiFixtureInt($row, 'score'); }, 'asc', ]]); @@ -786,6 +813,9 @@ function (array $row, string $key) use (&$calls): int { it('handles closed resources through strict scan fallback', function () { $resource = fopen('php://memory', 'rb'); + if ($resource === false) { + throw new RuntimeException('Failed to open fixture stream.'); + } fclose($resource); expect(ArrayMulti::uniqueBy([ @@ -793,3 +823,23 @@ function (array $row, string $key) use (&$calls): int { ['value' => $resource], ], 'value', true))->toHaveCount(1); }); + +it('sorts with the legacy locale option without deprecated PHP APIs', function () { + $previous = setlocale(LC_COLLATE, '0'); + if ($previous === false || setlocale(LC_COLLATE, 'C') === false) { + throw new RuntimeException('The C collation locale must be available.'); + } + + try { + $rows = ['z' => ['name' => 'z'], 'a' => ['name' => 'A'], 'b' => ['name' => 'a']]; + expect(array_keys(ArrayMulti::sortBy($rows, 'name', options: ArrayMulti::SORT_LOCALE))) + ->toBe(['a', 'b', 'z']) + ->and(array_keys(ArrayMulti::sortByMany($rows, [['name', 'desc', ArrayMulti::SORT_LOCALE]]))) + ->toBe(['z', 'b', 'a']) + ->and(ArrayMulti::sortRecursive(['z', 'A', 'a'], ArrayMulti::SORT_LOCALE))->toBe(['A', 'a', 'z']) + ->and(array_keys(ArrayMulti::sortRecursiveGuarded(['z' => 1, 'A' => 2, 'a' => 3], ArrayMulti::SORT_LOCALE))) + ->toBe(['A', 'a', 'z']); + } finally { + setlocale(LC_COLLATE, $previous); + } +}); diff --git a/tests/Feature/ArraySharedOpsTest.php b/tests/Feature/ArraySharedOpsTest.php index 8916068..2b3f402 100644 --- a/tests/Feature/ArraySharedOpsTest.php +++ b/tests/Feature/ArraySharedOpsTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Infocyph\ArrayKit\Tests\Feature; + use Infocyph\ArrayKit\Array\ArraySharedOps; it('iterates with each and stops when callback returns false', function () { diff --git a/tests/Feature/ArraySingleTest.php b/tests/Feature/ArraySingleTest.php index ba9ed9b..b0bd17d 100644 --- a/tests/Feature/ArraySingleTest.php +++ b/tests/Feature/ArraySingleTest.php @@ -4,6 +4,34 @@ use Infocyph\ArrayKit\Array\ArraySingle; +/** + * @param array $row + * @throws UnexpectedValueException + */ +function arraySingleFixtureInt(array $row, string $key): int +{ + $value = $row[$key] ?? null; + if (!is_int($value)) { + throw new UnexpectedValueException('Expected integer fixture field: ' . $key); + } + + return $value; +} + +/** + * @param array $row + * @throws UnexpectedValueException + */ +function arraySingleFixtureText(array $row, string $key): string +{ + $value = $row[$key] ?? null; + if (!is_string($value)) { + throw new UnexpectedValueException('Expected string fixture field: ' . $key); + } + + return $value; +} + it('checks if a key exists in a single-dimensional array', function () { $data = ['one' => 1, 'two' => 2]; expect(ArraySingle::exists($data, 'two')) @@ -51,7 +79,7 @@ it('searches an array for a callback condition', function () { $data = [1, 2, 3, 4]; - $key = ArraySingle::search($data, fn ($value) => $value === 3); + $key = ArraySingle::search($data, static fn(int $value): bool => $value === 3); expect($key)->toBe(2); }); @@ -93,21 +121,20 @@ ->and(ArraySingle::containsAny([INF], [-INF], true))->toBeFalse(); }); -it('isolates deterministic shuffle state from the global Mersenne Twister', function () { +it('shuffles without shared random state and preserves full-width deterministic seeds', function () { $values = range(1, 20); + $seeded = ArraySingle::shuffle($values, 12345); - expect(ArraySingle::shuffle($values, 12345)) - ->toBe(ArraySingle::shuffle($values, 12345)) - ->not->toBe(ArraySingle::shuffle($values, 54321)); + expect(ArraySingle::shuffle($values, 54321))->not->toBe($seeded) + ->and(ArraySingle::shuffle($values, 0))->not->toBe(ArraySingle::shuffle($values, PHP_INT_MIN)); - mt_srand(9876); - $first = mt_rand(); - $second = mt_rand(); + $unseeded = ArraySingle::shuffle($values); + sort($unseeded); + expect($unseeded)->toBe($values) + ->and(ArraySingle::shuffle($values, 12345))->toBe($seeded); - mt_srand(9876); - expect(mt_rand())->toBe($first); - ArraySingle::shuffle($values, 12345); - expect(mt_rand())->toBe($second); + sort($seeded); + expect($seeded)->toBe($values); }); it('does not retry callbacks that throw argument count errors internally', function () { @@ -133,7 +160,7 @@ $arr = [1, 2, 3]; expect(ArraySingle::sum($arr)) ->toBe(6) - ->and(ArraySingle::sum($arr, fn ($v) => $v * 2)) + ->and(ArraySingle::sum($arr, static fn(int $v): int => $v * 2)) ->toBe(12); }); @@ -141,7 +168,7 @@ $arr = [2 => 1, 4 => '2', 8 => 'x']; expect(ArraySingle::sum($arr))->toBe(3) - ->and(ArraySingle::sum($arr, fn ($value, $key) => is_numeric($value) ? ((float) $value + $key) : null)) + ->and(ArraySingle::sum($arr, static fn(mixed $value, int $key): ?float => is_numeric($value) ? (float) $value + (float) $key : null)) ->toBe(9.0); }); @@ -183,7 +210,7 @@ ->and(ArraySingle::sum([$high, -$low]))->toBe(1) ->and(ArraySingle::maxBy( [['score' => $low], ['score' => $high]], - static fn(array $row): int => $row['score'], + static fn(array $row): int => arraySingleFixtureInt($row, 'score'), ))->toBe(['score' => $high]); }); @@ -220,7 +247,7 @@ }); it('partitions the array based on a callback using partition()', function () { $arr = [1, 2, 3, 4, 5]; - $result = ArraySingle::partition($arr, fn ($v) => $v % 2 === 0); + $result = ArraySingle::partition($arr, static fn(int $v): bool => $v % 2 === 0); expect($result)->toBe([ [1 => 2, 3 => 4], // passed 'even' numbers [0 => 1, 2 => 3, 4 => 5], // failed 'odd' numbers @@ -228,7 +255,7 @@ }); it('rejects unwanted values using reject()', function () { $arr = [1, 2, 3, 4, 5, 'a', 'b', 'c']; - $result = ArraySingle::reject($arr, fn ($val) => is_numeric($val) && $val > 3); + $result = ArraySingle::reject($arr, static fn(mixed $val): bool => is_numeric($val) && $val > 3); expect(array_values($result))->toBe([1, 2, 3, 'a', 'b', 'c']); }); @@ -238,11 +265,11 @@ }); it('skips items while the callback returns true using skipWhile()', function () { $arr = [1, 2, 3, 4, 5]; - expect(array_values(ArraySingle::skipWhile($arr, fn ($v) => $v < 3)))->toBe([3, 4, 5]); + expect(array_values(ArraySingle::skipWhile($arr, static fn(int $v): bool => $v < 3)))->toBe([3, 4, 5]); }); it('skips items until the callback returns true using skipUntil()', function () { $arr = [1, 2, 3, 4, 5]; - expect(array_values(ArraySingle::skipUntil($arr, fn ($v) => $v === 3)))->toBe([3, 4, 5]); + expect(array_values(ArraySingle::skipUntil($arr, static fn(int $v): bool => $v === 3)))->toBe([3, 4, 5]); }); it('throws for invalid nth step values', function () { @@ -270,12 +297,12 @@ ]; expect(ArraySingle::countBy([1, 2, 2, 3, 3, 3]))->toBe([1 => 1, 2 => 2, 3 => 3]) - ->and(ArraySingle::countBy($rows, fn (array $row) => $row['group']))->toBe(['a' => 2, 'b' => 1]) + ->and(ArraySingle::countBy($rows, static fn(array $row): string => arraySingleFixtureText($row, 'group')))->toBe(['a' => 2, 'b' => 1]) ->and(ArraySingle::min([9, 2, 4]))->toBe(2) ->and(ArraySingle::max([9, 2, 4]))->toBe(9) - ->and(ArraySingle::minBy($rows, fn (array $row) => $row['score']))->toBe(['id' => 1, 'group' => 'a', 'score' => 10]) - ->and(ArraySingle::maxBy($rows, fn (array $row) => $row['score']))->toBe(['id' => 2, 'group' => 'a', 'score' => 30]) - ->and(ArraySingle::mapWithKeys($rows, fn (array $row) => [$row['id'] => $row['score']]))->toBe([1 => 10, 2 => 30, 3 => 20]) + ->and(ArraySingle::minBy($rows, static fn(array $row): int => arraySingleFixtureInt($row, 'score')))->toBe(['id' => 1, 'group' => 'a', 'score' => 10]) + ->and(ArraySingle::maxBy($rows, static fn(array $row): int => arraySingleFixtureInt($row, 'score')))->toBe(['id' => 2, 'group' => 'a', 'score' => 30]) + ->and(ArraySingle::mapWithKeys($rows, static fn(array $row): array => [arraySingleFixtureInt($row, 'id') => arraySingleFixtureInt($row, 'score')]))->toBe([1 => 10, 2 => 30, 3 => 20]) ->and(ArraySingle::values(['x' => 1, 'y' => 2]))->toBe([1, 2]) ->and(ArraySingle::rekey(['first_name' => 'Ada'], ['first_name' => 'firstName']))->toBe(['firstName' => 'Ada']); }); @@ -325,3 +352,10 @@ ->and(ArraySingle::same([1, 2, 2], [2, 1, 2]))->toBeTrue() ->and(ArraySingle::same([1, 2], ['1', 2], true))->toBeFalse(); }); + +it('detects repeated nulls without conflating strictly distinct values', function () { + expect(ArraySingle::duplicates([null, false, 0, '', null, false, 0, '', null], true)) + ->toBe([null, false, 0, '']) + ->and(ArraySingle::duplicates([null, [null], [null], null], true)) + ->toBe([[null], null]); +}); diff --git a/tests/Feature/BaseArrayHelperTest.php b/tests/Feature/BaseArrayHelperTest.php index a76578d..0c2645c 100644 --- a/tests/Feature/BaseArrayHelperTest.php +++ b/tests/Feature/BaseArrayHelperTest.php @@ -30,13 +30,13 @@ it('checks if at least one item meets a condition', function () { $data = [1, 2, 3]; - $res = BaseArrayHelper::haveAny($data, fn ($val) => $val > 2); + $res = BaseArrayHelper::haveAny($data, static fn(int $val): bool => $val > 2); expect($res)->toBeTrue(); }); it('checks if all items meet a condition', function () { $data = [2, 4, 6]; - $res = BaseArrayHelper::isAll($data, fn ($val) => $val % 2 === 0); + $res = BaseArrayHelper::isAll($data, static fn(int $val): bool => $val % 2 === 0); expect($res)->toBeTrue(); }); @@ -49,7 +49,7 @@ it('finds the first key matching a callback', function () { $data = ['a' => 10, 'b' => 15, 'c' => 20]; - $key = BaseArrayHelper::findKey($data, fn ($val) => $val > 10); + $key = BaseArrayHelper::findKey($data, static fn(int $val): bool => $val > 10); expect($key)->toBe('b') ->and(BaseArrayHelper::findKey([0, 2], fn (int $value): int => $value))->toBe(1); }); diff --git a/tests/Feature/BucketCollectionTest.php b/tests/Feature/BucketCollectionTest.php index e3e4a40..744ad1a 100644 --- a/tests/Feature/BucketCollectionTest.php +++ b/tests/Feature/BucketCollectionTest.php @@ -13,6 +13,7 @@ $source = new class implements JsonSerializable { public int $calls = 0; + #[Override] public function jsonSerialize(): mixed { $this->calls++; @@ -33,11 +34,14 @@ public function jsonSerialize(): mixed it('supports iteration', function () { $collection = new Collection(['a' => 1, 'b' => 2]); - $keys = []; + $items = []; foreach ($collection as $key => $val) { - $keys[] = $key; + if (!is_int($val)) { + throw new UnexpectedValueException('Expected integer fixture value.'); + } + $items[$key] = $val; } - expect($keys)->toBe(['a', 'b']); + expect($items)->toBe(['a' => 1, 'b' => 2]); }); it('supports nested iteration without pointer side effects', function () { @@ -46,6 +50,9 @@ public function jsonSerialize(): mixed foreach ($collection as $outerKey => $outerValue) { foreach ($collection as $innerKey => $innerValue) { + if (!is_int($outerValue) || !is_int($innerValue)) { + throw new UnexpectedValueException('Expected integer collection values.'); + } $pairs[] = [$outerKey, $innerKey, $outerValue + $innerValue]; } } @@ -65,7 +72,7 @@ public function jsonSerialize(): mixed it('can filter and return a new collection', function () { $collection = new Collection([1, 2, 3, 4]); - $even = $collection->filter(fn ($val) => $val % 2 === 0); + $even = $collection->filter(static fn(int $val): bool => $val % 2 === 0); expect($even->all())->toBe([1 => 2, 3 => 4]); }); diff --git a/tests/Feature/ConfigHooksTest.php b/tests/Feature/ConfigHooksTest.php index 94473c5..e6b7e5c 100644 --- a/tests/Feature/ConfigHooksTest.php +++ b/tests/Feature/ConfigHooksTest.php @@ -10,14 +10,14 @@ it('applies get hooks only when getWithHooks is used', function () { $this->config->set('site.title', 'ArRayKit'); - $this->config->onGet('site.title', fn ($value) => strtolower((string) $value)); + $this->config->onGet('site.title', static fn(string $value): string => strtolower($value)); expect($this->config->get('site.title'))->toBe('ArRayKit') ->and($this->config->getWithHooks('site.title'))->toBe('arraykit'); }); it('applies set hooks only when setWithHooks is used', function () { - $this->config->onSet('user.name', fn ($value) => strtoupper((string) $value)); + $this->config->onSet('user.name', static fn(string $value): string => strtoupper($value)); $this->config->set('user.name', 'john'); expect($this->config->get('user.name'))->toBe('john'); @@ -27,8 +27,8 @@ }); it('supports hook-aware bulk set and bulk get operations', function () { - $this->config->onSet('user.name', fn ($value) => strtoupper((string) $value)); - $this->config->onGet('user.name', fn ($value) => strtolower((string) $value)); + $this->config->onSet('user.name', static fn(string $value): string => strtoupper($value)); + $this->config->onGet('user.name', static fn(string $value): string => strtolower($value)); $this->config->setWithHooks([ 'user.name' => 'ALICE', @@ -43,8 +43,8 @@ it('supports hook-aware fill without overwriting existing keys', function () { $this->config->set('app.name', 'ArrayKit'); - $this->config->onSet('app.name', fn ($value) => strtoupper((string) $value)); - $this->config->onSet('app.env', fn ($value) => strtoupper((string) $value)); + $this->config->onSet('app.name', static fn(string $value): string => strtoupper($value)); + $this->config->onSet('app.env', static fn(string $value): string => strtoupper($value)); $this->config->fillWithHooks([ 'app.name' => 'should-not-replace', diff --git a/tests/Feature/ConfigLayeringTest.php b/tests/Feature/ConfigLayeringTest.php index 056a5da..500f6fe 100644 --- a/tests/Feature/ConfigLayeringTest.php +++ b/tests/Feature/ConfigLayeringTest.php @@ -6,6 +6,7 @@ use Infocyph\ArrayKit\Config\LayeredLazyFileConfig; use Infocyph\ArrayKit\Config\ResilientLazyFileConfig; +/** @param array $values */ function configLayeringWrite(string $directory, string $namespace, array $values): void { if (!is_dir($directory)) { @@ -30,7 +31,9 @@ function configLayeringRemove(string $path): void return; } - foreach (scandir($path) ?: [] as $entry) { + $entries = scandir($path); + + foreach ($entries === false ? [] : $entries as $entry) { if ($entry === '.' || $entry === '..') { continue; } @@ -177,5 +180,5 @@ function configLayeringRemove(string $path): void namespaceCacheDirectory: $this->layerCachePath, ); - expect(fn () => $config->get('db.host'))->toThrow(UnexpectedValueException::class); + expect(static fn(): mixed => $config->get('db.host'))->toThrow(UnexpectedValueException::class); }); diff --git a/tests/Feature/ConfigNumericReadCacheRegressionTest.php b/tests/Feature/ConfigNumericReadCacheRegressionTest.php index 0e93f39..656ec82 100644 --- a/tests/Feature/ConfigNumericReadCacheRegressionTest.php +++ b/tests/Feature/ConfigNumericReadCacheRegressionTest.php @@ -14,7 +14,7 @@ ], ]); - foreach (range(1, 3) as $read) { + for ($read = 0; $read < 3; $read++) { expect($config->get('app.servers.0'))->toBe('first') ->and($config->get('app.servers.1'))->toBe('second') ->and($config->get('app.negative.-1'))->toBe('minus one') @@ -61,7 +61,8 @@ $value = 'after'; - expect($config->get('app.servers.0'))->toBe('after'); + expect($value)->toBe('after') + ->and($config->get('app.servers.0'))->toBe('after'); }); it('returns identical numeric-path values with and without read caching', function (): void { diff --git a/tests/Feature/ConfigTest.php b/tests/Feature/ConfigTest.php index b076b3b..3854714 100644 --- a/tests/Feature/ConfigTest.php +++ b/tests/Feature/ConfigTest.php @@ -2,9 +2,15 @@ declare(strict_types=1); +namespace Infocyph\ArrayKit\Tests\Feature; + use Infocyph\ArrayKit\Config\Config; use Infocyph\ArrayKit\Config\Support\Environment; use Infocyph\ArrayKit\Tests\Fixtures\ConfigMode; +use InvalidArgumentException; +use OutOfBoundsException; +use ReflectionProperty; +use RuntimeException; $config = new Config; @@ -48,7 +54,7 @@ $cfg->loadArray(['app' => ['name' => 'ArrayKit']]); expect($cfg->getOrFail('app.name'))->toBe('ArrayKit') - ->and(fn () => $cfg->getOrFail('app.missing'))->toThrow(\OutOfBoundsException::class); + ->and(static fn(): mixed => $cfg->getOrFail('app.missing'))->toThrow(\OutOfBoundsException::class); }); it('validates every required key in bulk getOrFail calls', function () { @@ -58,7 +64,7 @@ expect($cfg->getOrFail(['app.name', 'app.nullable']))->toBe([ 'app.name' => 'ArrayKit', 'app.nullable' => null, - ])->and(fn () => $cfg->getOrFail(['app.name', 'app.missing'])) + ])->and(static fn(): mixed => $cfg->getOrFail(['app.name', 'app.missing'])) ->toThrow(OutOfBoundsException::class); }); @@ -211,7 +217,11 @@ ->and($cfg->get('missing', 'fallback'))->toBe('fallback'); } - $cacheSize = (fn (): int => count($this->resolvedValueCache))->call($cfg); + $cache = new ReflectionProperty($cfg, 'resolvedValueCache')->getValue($cfg); + if (!is_array($cache)) { + throw new RuntimeException('Expected an array cache.'); + } + $cacheSize = count($cache); expect($cacheSize)->toBe(0); }); @@ -259,7 +269,11 @@ $cfg->get('missing.'.$index); } - $cacheSize = (fn (): int => count($this->resolvedValueCache))->call($cfg); + $cache = new ReflectionProperty($cfg, 'resolvedValueCache')->getValue($cfg); + if (!is_array($cache)) { + throw new RuntimeException('Expected an array cache.'); + } + $cacheSize = count($cache); expect($cacheSize)->toBeLessThanOrEqual(1024); }); diff --git a/tests/Feature/DTOTraitTest.php b/tests/Feature/DTOTraitTest.php index 5fa616c..aed9304 100644 --- a/tests/Feature/DTOTraitTest.php +++ b/tests/Feature/DTOTraitTest.php @@ -2,39 +2,26 @@ declare(strict_types=1); -use Infocyph\ArrayKit\DTO\Concerns\DTOTrait; +namespace Infocyph\ArrayKit\Tests\Feature; + use Infocyph\ArrayKit\Tests\Fixtures\DTOTraitUser; +use Infocyph\ArrayKit\Tests\Fixtures\TestPersonDto; +use Infocyph\ArrayKit\Tests\Fixtures\TestVisibilityDto; it('can create a DTO from an array', function () { - // Define a quick test class inline - $dtoClass = new class - { - use DTOTrait; - - public string $name; - - public int $age; - }; - - $dto = $dtoClass::create(['name' => 'Alice', 'age' => 30, 'extra' => 'ignored']); + $dto = TestPersonDto::create(['name' => 'Alice', 'age' => 30, 'extra' => 'ignored']); // Cast to array using ->toArray() $data = $dto->toArray(); expect($data)->toBe([ 'name' => 'Alice', 'age' => 30, - ]); + ])->and($dto->name)->toBe('Alice') + ->and($dto->age)->toBe(30); }); it('can hydrate an existing DTO instance from an array', function () { - $dto = new class - { - use DTOTrait; - - public string $name = ''; - - public int $age = 0; - }; + $dto = new TestPersonDto(); $dto->fromArray(['name' => 'Bob', 'age' => 28, 'ignored' => true]); @@ -45,14 +32,7 @@ }); it('supports hydrate mapping and scalar coercion', function () { - $dto = new class - { - use DTOTrait; - - public string $name = ''; - - public int $age = 0; - }; + $dto = new TestPersonDto(); $dto->hydrate(['full_name' => 'Carol', 'age' => '33'], ['full_name' => 'name'], true); @@ -72,18 +52,7 @@ }); it('hydrates and exports only public instance properties', function () { - $dto = new class - { - use DTOTrait; - - public static string $shared = 'original'; - - public ?string $nickname = 'before'; - - protected string $protectedValue = 'protected'; - - private string $privateValue = 'private'; - }; + $dto = new TestVisibilityDto(); $dto->hydrate([ 'shared' => 'changed', @@ -93,5 +62,7 @@ ], coerce: true); expect($dto->toArray())->toBe(['nickname' => null]) - ->and($dto::$shared)->toBe('original'); + ->and($dto->nickname)->toBeNull() + ->and($dto::$shared)->toBe('original') + ->and($dto->nonPublicValues())->toBe(['protected', 'private']); }); diff --git a/tests/Feature/DotNotationTest.php b/tests/Feature/DotNotationTest.php index ed35354..cac22da 100644 --- a/tests/Feature/DotNotationTest.php +++ b/tests/Feature/DotNotationTest.php @@ -46,6 +46,7 @@ it('writes only to supported object properties', function () { $object = new class { + /** @var array */ public array $profile = []; public readonly string $identifier; @@ -56,20 +57,30 @@ public function __construct() { $this->identifier = 'fixed'; } + + public function secret(): string + { + return $this->secret; + } }; $target = ['object' => $object, 'dynamic' => new stdClass]; DotNotation::set($target, 'object.profile.name', 'Ada'); DotNotation::set($target, 'dynamic.created', true); + $dynamic = $target['dynamic'] ?? null; + if (!$dynamic instanceof stdClass) { + throw new RuntimeException('Expected dynamic object to be retained.'); + } expect($object->profile)->toBe(['name' => 'Ada']) - ->and($target['dynamic']->created)->toBeTrue() + ->and($dynamic->created)->toBeTrue() ->and(fn () => DotNotation::set($target, 'object.secret', 'visible')) ->toThrow(InvalidArgumentException::class) ->and(fn () => DotNotation::set($target, 'object.missing', 'value')) ->toThrow(InvalidArgumentException::class) ->and(fn () => DotNotation::set($target, 'object.identifier', 'changed')) - ->toThrow(InvalidArgumentException::class); + ->toThrow(InvalidArgumentException::class) + ->and($object->secret())->toBe('hidden'); }); it('renames overlapping parent and child paths without losing the captured value', function () { @@ -368,7 +379,7 @@ public function __construct() it('does not overwrite existing keys when fill() is used', function () { $data = ['user' => ['name' => 'Frank']]; DotNotation::fill($data, 'user.name', 'George'); - expect($data['user']['name'])->toBe('Frank'); + expect($data)->toBe(['user' => ['name' => 'Frank']]); }); it('does not overwrite existing null object properties when fill() is used', function () { @@ -376,13 +387,17 @@ public function __construct() DotNotation::fill($data, 'user.middle_name', 'George'); - expect($data['user']->middle_name)->toBeNull(); + $user = $data['user'] ?? null; + if (!$user instanceof stdClass) { + throw new RuntimeException('Expected user object.'); + } + expect($user->middle_name)->toBeNull(); }); it('fills missing keys when fill() is used', function () { $data = ['user' => []]; DotNotation::fill($data, 'user.email', 'frank@example.com'); - expect($data['user']['email'])->toBe('frank@example.com'); + expect($data)->toBe(['user' => ['email' => 'frank@example.com']]); }); it('supports escaped dot paths for set and forget', function () { @@ -544,7 +559,7 @@ public function __construct() it('taps into an array and returns it unchanged', function () { $data = ['x' => 10, 'y' => 20]; $called = false; - $result = DotNotation::tap($data, function ($arr) use (&$called, $data) { + $result = DotNotation::tap($data, static function (array $arr) use (&$called, $data): void { $called = true; expect($arr)->toBe($data); }); @@ -601,7 +616,7 @@ public function __construct() ], ]; - expect(fn () => DotNotation::getSafe($data, 'users.*.name', 'missing', maxDepth: 1, throwOnTooDeep: true)) + expect(static fn(): mixed => DotNotation::getSafe($data, 'users.*.name', 'missing', maxDepth: 1, throwOnTooDeep: true)) ->toThrow(RuntimeException::class); }); @@ -610,7 +625,7 @@ public function __construct() expect(DotNotation::getSafe($data, 'one.two.three', 'missing', maxDepth: 2))->toBe('missing') ->and(DotNotation::getSafe($data, 'one.two.three', 'missing', maxNodes: 2))->toBe('missing') - ->and(fn () => DotNotation::getSafe( + ->and(static fn(): mixed => DotNotation::getSafe( $data, 'one.two.three', 'missing', diff --git a/tests/Feature/GlobalHelpersTest.php b/tests/Feature/GlobalHelpersTest.php index 839eaf0..c026c83 100644 --- a/tests/Feature/GlobalHelpersTest.php +++ b/tests/Feature/GlobalHelpersTest.php @@ -14,7 +14,10 @@ it('autoloads only namespaced helper functions by default', function () { $composer = json_decode((string) file_get_contents(__DIR__.'/../../composer.json'), true, 512, JSON_THROW_ON_ERROR); - expect($composer['autoload']['files'])->toBe(['src/namespaced-functions.php']); + if (!is_array($composer) || !is_array($composer['autoload'] ?? null)) { + throw new RuntimeException('Invalid Composer autoload metadata.'); + } + expect($composer['autoload']['files'] ?? null)->toBe(['src/namespaced-functions.php']); }); it('keeps global helper declarations guarded in optional file', function () { @@ -35,6 +38,6 @@ expect(ns_array_get($data, 'app.name'))->toBe('ArrayKit') ->and(ns_array_get($data, 'app.env'))->toBe('local') ->and(ns_compare(10, 5, '>'))->toBeTrue() - ->and(ns_collect([1, 2]))->toBeInstanceOf(Collection::class) - ->and(ns_chain([1, 2, 3]))->toBeInstanceOf(Pipeline::class); + ->and(get_class(ns_collect([1, 2])))->toBe(Collection::class) + ->and(get_class(ns_chain([1, 2, 3])))->toBe(Pipeline::class); }); diff --git a/tests/Feature/HookedCollectionTest.php b/tests/Feature/HookedCollectionTest.php index 330c9f8..ccc79d0 100644 --- a/tests/Feature/HookedCollectionTest.php +++ b/tests/Feature/HookedCollectionTest.php @@ -8,7 +8,7 @@ $collection = new HookedCollection(['title' => 'Hello']); // Hook to transform the title to uppercase on get - $collection->onGet('title', fn ($value) => strtoupper($value)); + $collection->onGet('title', static fn(string $value): string => strtoupper($value)); // Normal offsetGet triggers the hook: expect($collection['title'])->toBe('HELLO'); @@ -18,7 +18,7 @@ $collection = new HookedCollection; // Hook to append "!!!" to any new value set for offset "shout" - $collection->onSet('shout', fn ($value) => $value.'!!!'); + $collection->onSet('shout', static fn(string $value): string => $value . '!!!'); $collection['shout'] = 'Hey'; expect($collection['shout'])->toBe('Hey!!!'); @@ -32,8 +32,8 @@ it('supports hooks for dot-notation keys', function () { $collection = new HookedCollection(['user' => ['name' => 'alice']]); - $collection->onGet('user.name', fn ($value) => strtoupper((string) $value)); - $collection->onSet('user.role', fn ($value) => "Role: $value"); + $collection->onGet('user.name', static fn(string $value): string => strtoupper($value)); + $collection->onSet('user.role', static fn(string $value): string => "Role: $value"); $collection['user.role'] = 'admin'; @@ -44,7 +44,7 @@ it('can run pipeline operations without type errors', function () { $collection = new HookedCollection([1, 2, 3, 4]); - $filtered = $collection->filter(fn ($value) => $value % 2 === 0); + $filtered = $collection->filter(static fn(int $value): bool => $value % 2 === 0); expect($filtered) ->toBeInstanceOf(HookedCollection::class) diff --git a/tests/Feature/LazyCollectionTest.php b/tests/Feature/LazyCollectionTest.php index 1852bd2..334b89f 100644 --- a/tests/Feature/LazyCollectionTest.php +++ b/tests/Feature/LazyCollectionTest.php @@ -5,7 +5,7 @@ use Infocyph\ArrayKit\Collection\LazyCollection; it('supports mapLazy/filterLazy/take/takeUntil/chunkLazy/cursor', function () { - $lazy = LazyCollection::make([1, 2, 3, 4, 5, 6]); + $lazy = LazyCollection::from([1, 2, 3, 4, 5, 6]); $mapped = $lazy ->mapLazy(fn (int $value): int => $value * 2) @@ -106,7 +106,7 @@ foreach ([$left, $right] as $cursor) { try { $cursor->next(); - test()->fail('The source failure was lost.'); + \PHPUnit\Framework\Assert::fail('The source failure was lost.'); } catch (RuntimeException $error) { expect($error)->toBe($failure); } diff --git a/tests/Feature/LazyFileConfigTest.php b/tests/Feature/LazyFileConfigTest.php index 990c33e..8c506e2 100644 --- a/tests/Feature/LazyFileConfigTest.php +++ b/tests/Feature/LazyFileConfigTest.php @@ -5,6 +5,7 @@ use Infocyph\ArrayKit\Config\LazyFileConfig; use Infocyph\ArrayKit\Config\Support\Environment; +/** @param array $contents */ function lazyConfigWriteArrayFile(string $directory, string $name, array $contents): void { $export = var_export($contents, true); @@ -45,11 +46,17 @@ function lazyConfigDeleteDirectory(string $directory): void } /** - * @return array + * @return array + * @throws UnexpectedValueException */ function lazyConfigItems(LazyFileConfig $config): array { - return (fn (): array => $this->items)->call($config); + $items = new ReflectionProperty($config, 'items')->getValue($config); + if (!is_array($items)) { + throw new UnexpectedValueException('Expected array configuration items.'); + } + + return $items; } function lazyConfigActiveCacheDirectory(string $directory): string @@ -107,6 +114,10 @@ function lazyConfigFlatIndex(string $directory): array it('preserves per-match default callbacks through the protected namespace reader', function () { lazyConfigWriteArrayFile($this->configPath, 'app', ['rows' => [[], []]]); $config = new class($this->configPath) extends LazyFileConfig { + /** + * @throws InvalidArgumentException + * @throws UnexpectedValueException + */ public function readPath(string $path, mixed $default): mixed { return $this->getPath($path, $default); @@ -219,7 +230,7 @@ public function readPath(string $path, mixed $default): mixed $config = new LazyFileConfig($this->configPath); - expect(fn () => $config->get())->toThrow(RuntimeException::class) + expect(static fn(): mixed => $config->get())->toThrow(RuntimeException::class) ->and(fn () => $config->all())->toThrow(RuntimeException::class); }); @@ -247,7 +258,7 @@ public function readPath(string $path, mixed $default): mixed $config = new LazyFileConfig($this->configPath); - expect(fn () => $config->get('db.host'))->toThrow(UnexpectedValueException::class); + expect(static fn(): mixed => $config->get('db.host'))->toThrow(UnexpectedValueException::class); }); it('can retry a namespace after its invalid file is corrected', function () { @@ -258,7 +269,7 @@ public function readPath(string $path, mixed $default): mixed $config = new LazyFileConfig($this->configPath); - expect(fn () => $config->get('db.host'))->toThrow(UnexpectedValueException::class); + expect(static fn(): mixed => $config->get('db.host'))->toThrow(UnexpectedValueException::class); lazyConfigWriteArrayFile($this->configPath, 'db', ['host' => 'localhost']); @@ -275,8 +286,8 @@ public function readPath(string $path, mixed $default): mixed lazyConfigWriteArrayFile($this->configPath, 'db', ['host' => 'localhost']); $config = new LazyFileConfig($this->configPath); - $config->onSet('db.host', fn ($value) => strtoupper((string) $value)); - $config->onGet('db.host', fn ($value) => strtolower((string) $value)); + $config->onSet('db.host', static fn(string $value): string => strtoupper($value)); + $config->onGet('db.host', static fn(string $value): string => strtolower($value)); $config->setWithHooks('db.host', 'INTERNAL'); @@ -288,8 +299,8 @@ public function readPath(string $path, mixed $default): mixed lazyConfigWriteArrayFile($this->configPath, 'db', ['host' => 'localhost', 'port' => 3306]); $config = new LazyFileConfig($this->configPath); - $config->onSet('db.host', fn ($value) => strtoupper((string) $value)); - $config->onGet('db.host', fn ($value) => strtolower((string) $value)); + $config->onSet('db.host', static fn(string $value): string => strtoupper($value)); + $config->onGet('db.host', static fn(string $value): string => strtolower($value)); $config->setWithHooks([ 'db.host' => 'INTERNAL', @@ -311,7 +322,7 @@ public function readPath(string $path, mixed $default): mixed $config->replace(['app' => ['name' => 'ArrayKit']]); expect($config->get('app.name'))->toBe('ArrayKit') ->and($config->getOrFail('app.name'))->toBe('ArrayKit') - ->and(fn () => $config->getOrFail('queue.driver'))->toThrow(OutOfBoundsException::class); + ->and(static fn(): mixed => $config->getOrFail('queue.driver'))->toThrow(OutOfBoundsException::class); $config->reload(['cache' => ['driver' => 'file']]); expect($config->get('cache.driver'))->toBe('file'); @@ -500,9 +511,15 @@ public function readPath(string $path, mixed $default): mixed $warm = proc_open([PHP_BINARY, '-r', $warmCode], $descriptors, $warmPipes); $flush = proc_open([PHP_BINARY, '-r', $flushCode], $descriptors, $flushPipes); - - expect(is_resource($warm))->toBeTrue() - ->and(is_resource($flush))->toBeTrue(); + if ($warm === false || $flush === false) { + foreach ([$warm, $flush] as $process) { + if (is_resource($process)) { + proc_terminate($process); + proc_close($process); + } + } + throw new RuntimeException('Failed to start cache fixture workers.'); + } $warmError = stream_get_contents($warmPipes[2]); $flushError = stream_get_contents($flushPipes[2]); @@ -510,8 +527,8 @@ public function readPath(string $path, mixed $default): mixed fclose($pipe); } - expect(proc_close($warm))->toBe(0, $warmError) - ->and(proc_close($flush))->toBe(0, $flushError); + expect(proc_close($warm))->toBe(0, $warmError === false ? 'Failed to read warm worker stderr' : $warmError) + ->and(proc_close($flush))->toBe(0, $flushError === false ? 'Failed to read flush worker stderr' : $flushError); $fresh = new LazyFileConfig($this->configPath, namespaceCacheDirectory: $this->cachePath); expect($fresh->get('app.version'))->toBe(1) @@ -541,3 +558,22 @@ public function readPath(string $path, mixed $default): mixed ->and($fresh->get('db.options', 'missing'))->toBe('missing') ->and($fresh->get('db', 'missing'))->toBe('missing'); }); + +it('reports a namespace disappearing after resolution without marking it loaded', function () { + lazyConfigWriteArrayFile($this->configPath, 'app', ['value' => 1]); + $config = new class($this->configPath) extends LazyFileConfig { + #[Override] + protected function resolveNamespaceFile(string $namespace): ?string + { + $file = parent::resolveNamespaceFile($namespace); + if ($file !== null) { + unlink($file); + } + + return $file; + } + }; + + expect(static fn(): mixed => $config->get('app.value'))->toThrow(UnexpectedValueException::class, 'no longer readable'); + expect($config->isLoaded('app'))->toBeFalse(); +}); diff --git a/tests/Feature/PipelineTest.php b/tests/Feature/PipelineTest.php index b6ed91b..1c1f6fe 100644 --- a/tests/Feature/PipelineTest.php +++ b/tests/Feature/PipelineTest.php @@ -17,12 +17,27 @@ 2 => ['id' => 2, 'team' => 'B', 'score' => 50], 3 => ['id' => 3, 'team' => 'A', 'score' => 40], ]) - ->and($rows->copy()->indexBy(fn (array $row) => 'r'.$row['id'])->all())->toBe([ + ->and($rows->copy()->indexBy(static function (array $row): string { + $id = $row['id'] ?? null; + if (!is_int($id)) { + throw new UnexpectedValueException('Expected an integer row ID.'); + } + + return 'r' . $id; + })->all())->toBe([ 'r1' => ['id' => 1, 'team' => 'A', 'score' => 30], 'r2' => ['id' => 2, 'team' => 'B', 'score' => 50], 'r3' => ['id' => 3, 'team' => 'A', 'score' => 40], ]) - ->and($rows->copy()->mapWithKeys(fn (array $row) => [$row['id'] => $row['score']])->all())->toBe([1 => 30, 2 => 50, 3 => 40]) + ->and($rows->copy()->mapWithKeys(static function (array $row): array { + $id = $row['id'] ?? null; + $score = $row['score'] ?? null; + if (!is_int($id) || !is_int($score)) { + throw new UnexpectedValueException('Expected integer row fields.'); + } + + return [$id => $score]; + })->all())->toBe([1 => 30, 2 => 50, 3 => 40]) ->and($rows->process()->countBy('team'))->toBe(['A' => 2, 'B' => 1]); }); diff --git a/tests/Feature/Release530BatchATest.php b/tests/Feature/Release530BatchATest.php index d2d7ed3..27156ac 100644 --- a/tests/Feature/Release530BatchATest.php +++ b/tests/Feature/Release530BatchATest.php @@ -8,6 +8,16 @@ use Infocyph\ArrayKit\Collection\LazyCollection; use Infocyph\ArrayKit\Config\LayeredLazyFileConfig; +/** + * @param Closure(): void $beforeYield + * @return Generator + */ +function batchADeferredSource(Closure $beforeYield): Generator +{ + $beforeYield(); + yield 1; +} + function batchARemoveDirectory(string $path): void { if (is_file($path) || is_link($path)) { @@ -20,7 +30,9 @@ function batchARemoveDirectory(string $path): void return; } - foreach (scandir($path) ?: [] as $entry) { + $entries = scandir($path); + + foreach ($entries === false ? [] : $entries as $entry) { if ($entry === '.' || $entry === '..') { continue; } @@ -38,7 +50,7 @@ function batchARemoveDirectory(string $path): void throwOnTooDeep: true, ))->toThrow(RuntimeException::class); - expect(fn () => DotNotation::getSafe( + expect(static fn(): mixed => DotNotation::getSafe( ['rows' => range(1, 10000)], 'rows.*', maxNodes: 2, @@ -60,6 +72,9 @@ function () use (&$defaults): string { maxNodes: 3, ); + if (!is_array($result)) { + throw new RuntimeException('Expected an array result.'); + } expect(count($result))->toBeLessThanOrEqual(3) ->and($defaults)->toBeLessThanOrEqual(3); }); @@ -70,7 +85,7 @@ function () use (&$defaults): string { $value = [$value]; } - expect(fn () => DotNotation::getSafe( + expect(static fn(): mixed => DotNotation::getSafe( ['rows' => [$value]], 'rows.*.*.*.*.*.*.*.*.*.*.*.*', maxDepth: 2, @@ -130,8 +145,15 @@ function () use (&$defaults): string { try { $config = new LayeredLazyFileConfig($directory, namespaces: ['app']); - expect($config->exportCache($cache))->toBeTrue() - ->and(include $cache)->toBe(['app' => ['name' => 'source']]); + expect($config->exportCache($cache))->toBeTrue(); + if (!is_file($cache)) { + throw new RuntimeException('Expected exported config cache.'); + } + $contents = include $cache; + if (!is_array($contents)) { + throw new RuntimeException('Exported config must contain an array.'); + } + expect($contents)->toBe(['app' => ['name' => 'source']]); } finally { batchARemoveDirectory($directory); if (is_file($cache)) { @@ -144,17 +166,17 @@ function () use (&$defaults): string { $data = ['app' => ['name' => 'old'], 'remove' => true]; expect(ArrayKit::dot()->set($data, 'app.name', 'new'))->toBeTrue() - ->and($data['app']['name'])->toBe('new'); + ->and($data)->toBe(['app' => ['name' => 'new'], 'remove' => true]); ArrayKit::helper()->forget($data, 'remove'); expect($data)->not->toHaveKey('remove'); ArrayKit::dot()->fill($data, 'app.debug', true); - expect($data['app']['debug'])->toBeTrue(); + expect($data)->toBe(['app' => ['name' => 'new', 'debug' => true]]); expect(ArrayKit::dot()->rename($data, 'app.debug', 'app.enabled'))->toBeTrue() - ->and($data['app']['enabled'])->toBeTrue(); + ->and($data)->toBe(['app' => ['name' => 'new', 'enabled' => true]]); }); it('replays terminal lazy source failures instead of presenting truncated success', function () { @@ -166,7 +188,7 @@ function () use (&$defaults): string { foreach ([1, 2] as $attempt) { try { $lazy->all(); - test()->fail("Traversal {$attempt} unexpectedly succeeded."); + \PHPUnit\Framework\Assert::fail("Traversal {$attempt} unexpectedly succeeded."); } catch (RuntimeException $error) { expect($error->getMessage())->toBe('source failure'); } @@ -174,13 +196,10 @@ function () use (&$defaults): string { }); it('replays failures before the first lazy yield', function () { - $lazy = LazyCollection::from((function () { - if (true) { - throw new RuntimeException('initial failure'); - } - - yield 1; - })()); + $source = batchADeferredSource(static function (): void { + throw new RuntimeException('initial failure'); + }); + $lazy = LazyCollection::from($source); expect(fn () => $lazy->all())->toThrow(RuntimeException::class, 'initial failure') ->and(fn () => $lazy->all())->toThrow(RuntimeException::class, 'initial failure'); @@ -216,7 +235,7 @@ function () use (&$defaults): string { ))->toBe([ 'a.value' => 1, 'b.value' => 'missing', - ])->and(fn () => DotNotation::getSafe( + ])->and(static fn(): mixed => DotNotation::getSafe( $data, ['a.value', 'b.value'], 'missing', diff --git a/tests/Feature/Release530BatchBTest.php b/tests/Feature/Release530BatchBTest.php index 2731889..264a371 100644 --- a/tests/Feature/Release530BatchBTest.php +++ b/tests/Feature/Release530BatchBTest.php @@ -2,10 +2,17 @@ declare(strict_types=1); +namespace Infocyph\ArrayKit\Tests\Feature; + use Infocyph\ArrayKit\Config\Config; use Infocyph\ArrayKit\Config\LazyFileConfig; use Infocyph\ArrayKit\Config\Support\Environment; use Infocyph\ArrayKit\Tests\Fixtures\ConfigMode; +use Closure; +use InvalidArgumentException; +use RuntimeException; +use stdClass; +use UnexpectedValueException; function batchBRemoveDirectory(string $path): void { @@ -19,7 +26,9 @@ function batchBRemoveDirectory(string $path): void return; } - foreach (scandir($path) ?: [] as $entry) { + $entries = scandir($path); + + foreach ($entries === false ? [] : $entries as $entry) { if ($entry === '.' || $entry === '..') { continue; } @@ -30,6 +39,7 @@ function batchBRemoveDirectory(string $path): void rmdir($path); } +/** @param array $value */ function batchBWriteConfig(string $directory, string $namespace, array $value): void { if (!is_dir($directory)) { @@ -58,7 +68,8 @@ function batchBWriteConfig(string $directory, string $namespace, array $value): $object->name = 'after'; $referenced = 'after'; - expect($config->get('object.name'))->toBe('after') + expect($referenced)->toBe('after') + ->and($config->get('object.name'))->toBe('after') ->and($config->get('reference.name'))->toBe('after'); }); @@ -202,7 +213,14 @@ function batchBWriteConfig(string $directory, string $namespace, array $value): expect(fn () => $invalid->exportCache($cache)) ->toThrow(UnexpectedValueException::class); - expect(include $cache)->toBe(['app' => ['name' => 'stable']]); + if (!is_file($cache)) { + throw new RuntimeException('Expected existing cache file.'); + } + $contents = include $cache; + if (!is_array($contents)) { + throw new RuntimeException('Exported config must contain an array.'); + } + expect($contents)->toBe(['app' => ['name' => 'stable']]); } finally { if (is_file($cache)) { unlink($cache); @@ -414,8 +432,15 @@ function batchBWriteConfig(string $directory, string $namespace, array $value): ], ]); - expect($config->exportCache($cache))->toBeTrue() - ->and(include $cache)->toBe([ + expect($config->exportCache($cache))->toBeTrue(); + if (!is_file($cache)) { + throw new RuntimeException('Expected exported config cache.'); + } + $contents = include $cache; + if (!is_array($contents)) { + throw new RuntimeException('Exported config must contain an array.'); + } + expect($contents)->toBe([ 'app' => [ 'enabled' => true, 'mode' => ConfigMode::Prod, @@ -445,13 +470,13 @@ function batchBWriteConfig(string $directory, string $namespace, array $value): return $cycle; })(), 'closure-cycle' => (static function (): Closure { - $closure = null; $closure = static function () use (&$closure): Closure { return $closure; }; return $closure; })(), + default => throw new InvalidArgumentException('Unknown fixture case: ' . $case), }; $config = new Config(); diff --git a/tests/Feature/Release530BatchCTest.php b/tests/Feature/Release530BatchCTest.php index e6102a7..2909b92 100644 --- a/tests/Feature/Release530BatchCTest.php +++ b/tests/Feature/Release530BatchCTest.php @@ -7,9 +7,13 @@ use Infocyph\ArrayKit\Array\DotNotation; use Infocyph\ArrayKit\Collection\Collection; +/** @throws RuntimeException */ function batchCClosedResource(): mixed { $resource = fopen('php://temp', 'r+'); + if ($resource === false) { + throw new RuntimeException('Unable to open temporary resource.'); + } fclose($resource); return $resource; diff --git a/tests/Feature/Release530BatchDTest.php b/tests/Feature/Release530BatchDTest.php index ca594ed..848da17 100644 --- a/tests/Feature/Release530BatchDTest.php +++ b/tests/Feature/Release530BatchDTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Infocyph\ArrayKit\Tests\Feature; + use Infocyph\ArrayKit\Collection\LazyCollection; use Infocyph\ArrayKit\Tests\Fixtures\Release530BatchDAddress; use Infocyph\ArrayKit\Tests\Fixtures\Release530BatchDInherited; @@ -99,7 +101,7 @@ 'payload' => ['roles' => ['admin', 'editor']], ]); - expect($dto->address)->toBeInstanceOf(Release530BatchDAddress::class) + expect(get_class($dto->address))->toBe(Release530BatchDAddress::class) ->and($dto->address->city)->toBe('Dhaka') ->and($dto->payload)->toBe(['roles' => ['admin', 'editor']]); }); @@ -114,7 +116,7 @@ }); it('preserves readonly hydration behavior when the trait owns the property scope', function () { - $dto = new Release530BatchDReadonly(); + $dto = new \ReflectionClass(Release530BatchDReadonly::class)->newInstanceWithoutConstructor(); $dto->hydrateNestedGuarded(['name' => 'fixed']); expect($dto->name)->toBe('fixed') diff --git a/tests/Feature/Release530BatchETest.php b/tests/Feature/Release530BatchETest.php index bbab168..4d07040 100644 --- a/tests/Feature/Release530BatchETest.php +++ b/tests/Feature/Release530BatchETest.php @@ -12,6 +12,7 @@ use Infocyph\Runwire\RuntimeCapabilities; use Infocyph\Runwire\RuntimeContext; +/** @throws InvalidArgumentException */ function batchERuntime(bool $coroutines = false): RuntimeContext { return RuntimeContext::fromCapabilities( @@ -28,6 +29,14 @@ function batchERuntime(bool $coroutines = false): RuntimeContext ); } +/** + * @template TKey of array-key + * @template TValue + * @param LazyCollection $collection + * @return LazyCollection + * @throws InvalidArgumentException + * @throws LogicException + */ function batchEForwardBinding( LazyCollection $collection, RuntimeContext $runtime, @@ -62,14 +71,20 @@ function batchEForwardBinding( $code = str_replace('__SOURCE__', $source, $code); $process = proc_open([PHP_BINARY, '-r', $code], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); - expect(is_resource($process))->toBeTrue(); + if (!is_resource($process)) { + throw new RuntimeException('Unable to start fixture process.'); + } $stdout = stream_get_contents($pipes[1]); $stderr = stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); - expect(proc_close($process))->toBe(0, $stdout . $stderr); + $exit = proc_close($process); + if ($stdout === false || $stderr === false) { + throw new RuntimeException('Unable to read fixture process output.'); + } + expect($exit)->toBe(0, $stdout . $stderr); }); it('keeps installed but unbound lazy collections on the ordinary path', function () { @@ -152,7 +167,7 @@ function () use (&$factoryCalls): array { } } - test()->fail('Traversal unexpectedly completed after request cancellation.'); + \PHPUnit\Framework\Assert::fail('Traversal unexpectedly completed after request cancellation.'); } catch (CancelledException) { expect($seen)->toBe([1, 2]) ->and($consumed)->toBe(2); @@ -288,8 +303,8 @@ function () use (&$factoryCalls): array { public int $factoryCalls = 0; }; - expect(fn () => $coroutines->run( - function (CoroutineScope $scope) use ($runtime, $request, $state): array { + expect(static function () use ($coroutines, $runtime, $request, $state): void { + $coroutines->run(function (CoroutineScope $scope) use ($runtime, $request, $state): array { $scope->spawn(function () use ($request): void { $request->cancel(CancellationReason::HOST_CANCELLED); }); @@ -303,8 +318,8 @@ function () use ($state): array { ) ->withRunwire($runtime, $request, $scope, checkpointEvery: 1) ->all(); - }, - ))->toThrow(CancelledException::class); + }); + })->toThrow(CancelledException::class); expect($state->factoryCalls)->toBe(0) ->and($request->cancelled())->toBeTrue() diff --git a/tests/Feature/Release530BatchFTest.php b/tests/Feature/Release530BatchFTest.php index d3b9333..0f5be99 100644 --- a/tests/Feature/Release530BatchFTest.php +++ b/tests/Feature/Release530BatchFTest.php @@ -13,6 +13,7 @@ use Infocyph\Runwire\RuntimeContext; use Infocyph\Runwire\RuntimeOptions; +/** @throws InvalidArgumentException */ function batchFRuntime(RuntimeDriver $driver): RuntimeContext { $environment = new RuntimeEnvironment( @@ -103,7 +104,7 @@ function batchFRuntime(RuntimeDriver $driver): RuntimeContext }) ->all(); - test()->fail('Cancelled worker cycle unexpectedly completed.'); + \PHPUnit\Framework\Assert::fail('Cancelled worker cycle unexpectedly completed.'); } catch (CancelledException) { expect($seen)->toBe([$tenant, $tenant]); } diff --git a/tests/Feature/Release530ReviewRegressionTest.php b/tests/Feature/Release530ReviewRegressionTest.php index 17f2ac5..d0db2b2 100644 --- a/tests/Feature/Release530ReviewRegressionTest.php +++ b/tests/Feature/Release530ReviewRegressionTest.php @@ -28,6 +28,9 @@ RecursiveIteratorIterator::CHILD_FIRST, ); foreach ($entries as $entry) { + if (!$entry instanceof SplFileInfo) { + throw new RuntimeException('Unexpected directory entry.'); + } $entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname()); } rmdir($this->reviewDirectory); @@ -56,13 +59,13 @@ function review530Config(string $directory): LazyFileConfig expect(DotNotation::getSafe([], $keys, $default, maxNodes: 2))->toHaveCount(2) ->and($calls)->toBe(2); $calls = 0; - expect(fn () => DotNotation::getSafe([], $keys, $default, maxNodes: 2, throwOnTooDeep: true)) + expect(static fn(): mixed => DotNotation::getSafe([], $keys, $default, maxNodes: 2, throwOnTooDeep: true)) ->toThrow(RuntimeException::class) ->and($calls)->toBe(2); }); it('rejects unfinished throwing lookups and accepts an exactly complete budget', function () { - expect(fn () => DotNotation::getSafe(['a' => 1, 'b' => 2], ['a', 'b'], maxNodes: 1, throwOnTooDeep: true)) + expect(static fn(): mixed => DotNotation::getSafe(['a' => 1, 'b' => 2], ['a', 'b'], maxNodes: 1, throwOnTooDeep: true)) ->toThrow(RuntimeException::class) ->and(DotNotation::getSafe(['a' => 1, 'b' => 2], ['a', 'b'], maxNodes: 2, throwOnTooDeep: true)) ->toBe(['a' => 1, 'b' => 2]); @@ -76,6 +79,9 @@ function review530Config(string $directory): LazyFileConfig $right['self'] = &$right; $right['tail'] = 1; $result = ArrayMulti::sortRecursiveGuarded([$left, $right], maxDepth: $maxDepth, maxNodes: $maxNodes); + if (!is_array($result[0] ?? null) || !is_array($result[1] ?? null)) { + throw new RuntimeException('Expected two array results.'); + } expect($result)->toHaveCount(2) ->and($result[0]['tail'])->toBe(2) ->and($result[1]['tail'])->toBe(1); @@ -86,6 +92,9 @@ function review530Config(string $directory): LazyFileConfig $right = $left; $right[99999] = 2; $result = ArrayMulti::sortRecursiveGuarded([$right, $left], maxDepth: 1, maxNodes: 2); + if (!is_array($result[0] ?? null) || !is_array($result[1] ?? null)) { + throw new RuntimeException('Expected two array results.'); + } expect($result[0][99999])->toBe(2) ->and($result[1][99999])->toBe(1) ->and(ArrayMulti::sortRecursiveGuarded([[3, 1], [2, 0]], maxNodes: 6)) @@ -213,6 +222,7 @@ function review530Config(string $directory): LazyFileConfig public function calls(): int { return $this->calls; } + /** @return list */ public function toArray(): array { $this->calls++; @@ -230,6 +240,7 @@ public function toArray(): array { $dto = new class extends DTO { public int $reads = 0; + /** @var list */ public array $payload { get => ++$this->reads === 1 ? [1] : range(1, 10000); } @@ -252,10 +263,13 @@ public function toArray(): array { $second = 2; $lazy = LazyCollection::from(['first' => &$first, 'second' => &$second]); $first = 3; + expect($first)->toBe(3); expect($lazy->take(1)->all())->toBe(['first' => 3]); $first = 4; $second = 5; + expect([$first, $second])->toBe([4, 5]); expect($lazy->all())->toBe(['first' => 3, 'second' => 5]); $second = 6; + expect($second)->toBe(6); expect($lazy->all())->toBe(['first' => 3, 'second' => 5]); }); diff --git a/tests/Feature/Release532BatchATest.php b/tests/Feature/Release532BatchATest.php index 97758ea..96e0bf5 100644 --- a/tests/Feature/Release532BatchATest.php +++ b/tests/Feature/Release532BatchATest.php @@ -25,7 +25,7 @@ maxNodes: 2, throwOnTooDeep: true, ))->toThrow(RuntimeException::class); -})->with([SORT_REGULAR, SORT_NUMERIC, SORT_STRING, SORT_NATURAL, SORT_LOCALE_STRING]); +})->with([SORT_REGULAR, SORT_NUMERIC, SORT_STRING, SORT_NATURAL, ArrayMulti::SORT_LOCALE]); it('treats opaque and wide object values as an explicit bounded-sort boundary', function () { $wide = new stdClass(); @@ -64,9 +64,10 @@ public function __construct() it('retains the source after a rejecting magic setter and works through the facade', function () { $target = new class { + /** @throws RuntimeException */ public function __set(string $name, mixed $value): void { - throw new RuntimeException("Rejected {$name} value {$value}"); + throw new RuntimeException("Rejected {$name} value of type " . get_debug_type($value)); } }; diff --git a/tests/Feature/Release532BatchBTest.php b/tests/Feature/Release532BatchBTest.php index 6f89c06..fb63036 100644 --- a/tests/Feature/Release532BatchBTest.php +++ b/tests/Feature/Release532BatchBTest.php @@ -14,6 +14,7 @@ expect($config->snapshot('before'))->toBeTrue(); $scalar = 5; + expect($scalar)->toBe(5); $nested['v'] = 30; expect($config->changed('before'))->toBeTrue() ->and($config->restore('before'))->toBeTrue() @@ -48,6 +49,7 @@ ); expect($lazy->snapshot())->toBeTrue(); $lazyValue = 8; + expect($lazyValue)->toBe(8); expect($lazy->restore())->toBeTrue() ->and($lazy->get('app.v'))->toBe(1); @@ -59,6 +61,7 @@ ); $layered->snapshot(); $layeredValue = 9; + expect($layeredValue)->toBe(9); expect($layered->restore())->toBeTrue() ->and($layered->get('app.v'))->toBe(2); }); @@ -106,6 +109,9 @@ $process->run(); expect($process->getExitCode())->toBe(0, $process->getErrorOutput()); $result = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR); + if (!is_array($result) || !is_int($result['growth'] ?? null)) { + throw new RuntimeException('Invalid snapshot worker result.'); + } expect($result['growth'])->toBeLessThan(4 * 1024 * 1024) ->and($result['independent'])->toBeTrue() ->and($result['restored'])->toBe(1); @@ -157,6 +163,9 @@ new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST, ) as $entry) { + if (!$entry instanceof SplFileInfo) { + throw new RuntimeException('Unexpected directory entry.'); + } $entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname()); } rmdir($root); @@ -186,16 +195,20 @@ expect($fresh->get('0.value'))->toBe('0'); $layered = new LayeredLazyFileConfig($source, $cache, namespaces: ['0', '-1', '01']); + $all = $layered->all(); expect($layered->get('0.value'))->toBe('0') - ->and($layered->all()[0]['value'])->toBe('0') - ->and($layered->all()[-1]['value'])->toBe('-1') - ->and($layered->all()['01']['value'])->toBe('01'); + ->and($all[0] ?? null)->toBe(['value' => '0']) + ->and($all[-1] ?? null)->toBe(['value' => '-1']) + ->and($all['01'] ?? null)->toBe(['value' => '01']); $layered->warmNamespaceCache(); } finally { foreach (new RecursiveIteratorIterator( new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST, ) as $entry) { + if (!$entry instanceof SplFileInfo) { + throw new RuntimeException('Unexpected directory entry.'); + } $entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname()); } rmdir($root); diff --git a/tests/Feature/Release532BatchCTest.php b/tests/Feature/Release532BatchCTest.php index 41fba64..cb3f296 100644 --- a/tests/Feature/Release532BatchCTest.php +++ b/tests/Feature/Release532BatchCTest.php @@ -2,6 +2,10 @@ declare(strict_types=1); +namespace Infocyph\ArrayKit\Tests\Feature; + +use BadMethodCallException; +use InvalidArgumentException; use Infocyph\ArrayKit\Array\ArraySingle; use Infocyph\ArrayKit\Array\BaseArrayHelper; use Infocyph\ArrayKit\ArrayKit; @@ -11,8 +15,8 @@ use Infocyph\ArrayKit\Tests\Fixtures\Release532StringMode; it('validates positive random counts even for empty arrays', function () { - expect(fn () => BaseArrayHelper::random([], 1))->toThrow(InvalidArgumentException::class) - ->and(fn () => ArrayKit::helper()->random([], 2))->toThrow(InvalidArgumentException::class) + expect(static fn(): mixed => BaseArrayHelper::random([], 1))->toThrow(InvalidArgumentException::class) + ->and(static fn(): mixed => ArrayKit::helper()->random([], 2))->toThrow(InvalidArgumentException::class) ->and(BaseArrayHelper::random([]))->toBeNull() ->and(BaseArrayHelper::random([], 0))->toBe([]); }); @@ -62,9 +66,9 @@ it('forwards only callable public pipeline methods through collections', function () { $collection = Collection::make([3, 1, 2]); - expect(fn () => $collection->numericAggregate(null, true)) + expect(static fn(): mixed => $collection->__call('numericAggregate', [null, true])) ->toThrow(BadMethodCallException::class) - ->and(fn () => $collection->unrecognizedInternalMethod()) + ->and(static fn(): mixed => $collection->__call('unrecognizedInternalMethod', [])) ->toThrow(BadMethodCallException::class) ->and($collection->values()->all())->toBe([3, 1, 2]); }); @@ -76,6 +80,15 @@ it('retains small remainders when extreme finite values cancel during averaging', function (float $remainder) { $extremes = [PHP_FLOAT_MAX, PHP_FLOAT_MAX, -PHP_FLOAT_MAX, -PHP_FLOAT_MAX]; - expect(ArraySingle::avg([...$extremes, $remainder]))->toBe($remainder / 5) - ->and(ArraySingle::avg([$remainder, ...$extremes]))->toBe($remainder / 5); + expect(ArraySingle::avg([...$extremes, $remainder]))->toBe($remainder / 5.0) + ->and(ArraySingle::avg([$remainder, ...$extremes]))->toBe($remainder / 5.0); })->with([1.0, 1e-100, 1e-300, -1.0, -1e-100, -1e-300]); + +it('preserves integer precision and native mixed numeric promotion', function () { + $integer = PHP_INT_MAX - 2; + expect(ArraySingle::sum([$integer, 1]))->toBe(PHP_INT_MAX - 1) + ->and(ArraySingle::sum([' 42 ', '2e1', 0.5]))->toBe(62.5) + ->and(ArraySingle::median([1, 3]))->toBe(2) + ->and(ArraySingle::median([1, 2.0]))->toBe(1.5) + ->and(\Infocyph\ArrayKit\Array\ArrayMulti::sum([['value' => $integer], ['value' => 1]], 'value'))->toBe(PHP_INT_MAX - 1); +}); diff --git a/tests/Fixtures/Release530BatchDReadonly.php b/tests/Fixtures/Release530BatchDReadonly.php index 6b70369..fa87787 100644 --- a/tests/Fixtures/Release530BatchDReadonly.php +++ b/tests/Fixtures/Release530BatchDReadonly.php @@ -10,5 +10,5 @@ final class Release530BatchDReadonly { use DTOTrait; - public readonly string $name; + public function __construct(public readonly string $name = '') {} } diff --git a/tests/Fixtures/Release530BatchDUser.php b/tests/Fixtures/Release530BatchDUser.php index c1a1db7..be33ea5 100644 --- a/tests/Fixtures/Release530BatchDUser.php +++ b/tests/Fixtures/Release530BatchDUser.php @@ -13,4 +13,9 @@ final class Release530BatchDUser public Release530BatchDAddress $address; public mixed $payload = null; + + public function __construct() + { + $this->address = new Release530BatchDAddress(); + } } diff --git a/tests/Fixtures/TestPersonDto.php b/tests/Fixtures/TestPersonDto.php new file mode 100644 index 0000000..a7b908e --- /dev/null +++ b/tests/Fixtures/TestPersonDto.php @@ -0,0 +1,16 @@ +protectedValue, $this->privateValue]; + } +} diff --git a/tests/Support/Release530PersistentWorkerSoak.php b/tests/Support/Release530PersistentWorkerSoak.php index fa76f4c..26766f5 100644 --- a/tests/Support/Release530PersistentWorkerSoak.php +++ b/tests/Support/Release530PersistentWorkerSoak.php @@ -32,6 +32,10 @@ final class Release530PersistentWorkerSoak private readonly string $sourceDirectory; + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ public function __construct() { $suffix = bin2hex(random_bytes(6)); @@ -46,6 +50,13 @@ public function __construct() $this->runtime = $this->runtime(); } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable + * @throws \Infocyph\Runwire\Exception\CancelledException + */ public function run(): void { $this->installSignalHandlers(); @@ -89,26 +100,39 @@ private function removeDirectory(string $directory): void return; } - foreach (scandir($directory) ?: [] as $entry) { + $entries = scandir($directory); + foreach ($entries === false ? [] : $entries as $entry) { if ($entry === '.' || $entry === '..') { continue; } $path = $directory . DIRECTORY_SEPARATOR . $entry; - if (is_dir($path)) { + if (!is_link($path) && is_dir($path)) { $this->removeDirectory($path); } elseif (is_file($path) || is_link($path)) { - if (function_exists('opcache_invalidate')) { - opcache_invalidate($path, true); - } - unlink($path); - clearstatcache(true, $path); + $this->removeCacheFile($path); } } rmdir($directory); } + private function removeCacheFile(string $path): void + { + if (function_exists('opcache_invalidate')) { + opcache_invalidate($path, true); + } + unlink($path); + clearstatcache(true, $path); + } + + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable + * @throws \Infocyph\Runwire\Exception\CancelledException + */ private function runCycle(int $cycle): void { $tenant = 'tenant-' . $cycle; @@ -142,20 +166,7 @@ private function runCycle(int $cycle): void )->withRunwire($this->runtime, $request, checkpointEvery: 1); if (($cycle % 13) === 0) { - try { - $collection - ->mapLazy(function (array $row) use ($request): array { - if ($row['value'] === 2) { - $request->cancel(CancellationReason::HOST_CANCELLED); - } - - return $row; - }) - ->all(); - - throw new RuntimeException('Cancelled worker cycle unexpectedly completed.'); - } catch (CancelledException) { - } + $this->assertCancelledTraversal($collection, $request); } else { $rows = $collection->all(); if (count($rows) !== 3 || array_unique(array_column($rows, 'tenant')) !== [$tenant]) { @@ -176,6 +187,32 @@ private function runCycle(int $cycle): void } } + /** + * @template TKey of int + * @template TRow of array{tenant: string, value: int} + * @param LazyCollection $collection + * @throws RuntimeException + * @throws \LogicException + * @throws \Throwable + */ + private function assertCancelledTraversal(LazyCollection $collection, RequestContext $request): void + { + try { + $collection + ->mapLazy(function (array $row) use ($request): array { + if ($row['value'] === 2) { + $request->cancel(CancellationReason::HOST_CANCELLED); + } + + return $row; + }) + ->all(); + + throw new RuntimeException('Cancelled worker cycle unexpectedly completed.'); + } catch (CancelledException) { + } + } + private function retireInactiveGenerations(): void { $pointer = $this->cacheDirectory . '/.arraykit-generation'; @@ -184,13 +221,18 @@ private function retireInactiveGenerations(): void } $active = trim((string) file_get_contents($pointer)); - foreach (glob($this->cacheDirectory . '/.arraykit-gen-*', GLOB_ONLYDIR) ?: [] as $directory) { + $directories = glob($this->cacheDirectory . '/.arraykit-gen-*', GLOB_ONLYDIR); + foreach ($directories === false ? [] : $directories as $directory) { if (basename($directory) !== $active) { $this->removeDirectory($directory); } } } + /** + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ private function refreshGeneratedCache(int $cycle): void { $version = intdiv($cycle, 50) + 1; @@ -236,6 +278,9 @@ private function refreshGeneratedCache(int $cycle): void } } + /** + * @throws \InvalidArgumentException + */ private function runtime(): RuntimeContext { $environment = new RuntimeEnvironment( @@ -261,6 +306,9 @@ private function runtime(): RuntimeContext ); } + /** + * @throws \RuntimeException + */ private function writeSource(int $version): void { $source = sprintf( diff --git a/tests/Support/release530-persistent-worker.php b/tests/Support/release530-persistent-worker.php index d406519..cce1f23 100644 --- a/tests/Support/release530-persistent-worker.php +++ b/tests/Support/release530-persistent-worker.php @@ -2,7 +2,7 @@ declare(strict_types=1); -use Infocyph\ArrayKit\Tests\Support\Release530PersistentWorkerSoak; +namespace Infocyph\ArrayKit\Tests\Support; require dirname(__DIR__, 2) . '/vendor/autoload.php';