diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs
new file mode 100644
index 0000000..d29cc57
--- /dev/null
+++ b/.git-blame-ignore-revs
@@ -0,0 +1,6 @@
+# Formatting-only commits ignored by git blame.
+# Enable locally: git config blame.ignoreRevsFile .git-blame-ignore-revs
+# Use git blame -w to help attribute reformatted whitespace to earlier commits.
+
+# style: format PHP source and tests with Mago
+69d6c6137d3d17a3237d51ca77767c59cbab205d
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 75b9d5f..f866b1d 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -3,52 +3,87 @@ name: PHP Tests
on:
push:
branches: [ "master" ]
+ pull_request_review:
+ types: [ submitted, edited ]
+
+ pull_request:
+ types:
+ - opened
+ - edited
+ - synchronize
+ - reopened
+ branches:
+ - master
+
+ workflow_dispatch:
permissions:
contents: read
jobs:
+ quality:
+ name: Mago formatter, linter and analyzer
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@v7
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: '8.2'
+ coverage: none
+ - name: Install development dependencies
+ run: composer install --prefer-dist --no-progress --no-interaction
+ - name: Run formatter, linter and analyzer without a baseline
+ run: composer check
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+
run:
runs-on: ${{ matrix.operating-system }}
+ timeout-minutes: 15
strategy:
+ fail-fast: false
matrix:
operating-system: [ ubuntu-latest ]
- php-version: [ '8.1', '8.2' ]
+ php-version: [ '8.1', '8.2', '8.3', '8.4', '8.5' ]
- name: PHP ${{ matrix.php-version }} test on ${{ matrix.operating-system }}
+ name: PHP ${{ matrix.php-version }} tests on ${{ matrix.operating-system }}
steps:
- name: Checkout Code
- uses: actions/checkout@v3
+ uses: actions/checkout@v7
- name: Install PHP
id: php
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
+ coverage: xdebug
- name: Check PHP version
run: php -v
- - name: Cache Composer packages
+ - name: Get Composer cache directory
id: composer-cache
- uses: actions/cache@v3
+ run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT"
+
+ - name: Cache Composer downloads
+ uses: actions/cache@v6
with:
- path: vendor
- key: ${{ runner.os }}-${{ matrix.operating-system }}-php-${{ steps.php.outputs.php-version }}-composer-${{ hashFiles('**/composer.json') }}
+ path: ${{ steps.composer-cache.outputs.dir }}
+ key: ${{ runner.os }}-php-${{ matrix.php-version }}-composer-${{ hashFiles('composer.json', 'composer.lock') }}
restore-keys: |
- ${{ runner.os }}-${{ matrix.operating-system }}-php-${{ steps.php.outputs.php-version }}
+ ${{ runner.os }}-php-${{ matrix.php-version }}-composer-
- - if: steps.composer-cache.outputs.cache-hit != 'true'
- name: Install Composer dependencies
- run: composer install --prefer-dist --no-progress
+ - name: Install Composer dependencies
+ run: composer install --prefer-dist --no-progress --no-interaction
- name: PHPUnit Tests
- run: vendor/bin/phpunit --coverage-clover ./tests/coverage.xml --display-notices
+ run: vendor/bin/phpunit --testsuite=Tests --coverage-clover ./tests/coverage.xml --display-notices
- name: Upload coverage reports to Codecov
- uses: codecov/codecov-action@v3
+ uses: codecov/codecov-action@v7
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./tests/coverage.xml
diff --git a/MAGO.md b/MAGO.md
new file mode 100644
index 0000000..9f213c1
--- /dev/null
+++ b/MAGO.md
@@ -0,0 +1,32 @@
+# Mago checks
+
+Mago is pinned to [1.59.0](https://github.com/carthage-software/mago/releases/tag/1.59.0)
+as a development dependency. Install dependencies with `composer install`, then run:
+
+```sh
+composer check # formatting, linter, and analyzer for source and tests
+composer format-check # check formatting without changing files
+composer lint
+composer analyze
+composer format # apply formatting
+```
+
+`mago.toml` checks both `src` and `tests`, targeting PHP 8.1, the minimum supported
+version. Dependencies provide type information but are not
+checked. Generated files in `tests/cache`, `tests/coverage`, and `tests/tmp` are
+excluded.
+
+The linter settings follow PHP-AOP: strict types, named arguments, boolean flags,
+and `isset` retain the existing API conventions. Aggregate complexity metrics are
+left to review, and the parameter-count threshold is 10. Analyzer missing-type
+checks are enabled, and checks fail on findings at note severity or higher.
+
+Formatting, lint, and analyzer checks pass without a baseline or vendor type patch.
+`Metadata` has one documented `too-many-properties` expectation because its public
+fields mirror PHP stream metadata. All other findings are addressed in source and
+tests. The CI quality job runs `composer check`.
+
+The scripts invoke the project-local PHP launcher. Its first invocation downloads
+the matching native binary; CI supplies `GITHUB_TOKEN` for that download. On
+Windows, the launcher needs PHP's ZIP extension and a trusted CA certificate
+bundle configured for HTTPS downloads.
diff --git a/composer.json b/composer.json
index 4f5b7a9..1233739 100644
--- a/composer.json
+++ b/composer.json
@@ -19,7 +19,12 @@
],
"scripts": {
"test": "phpunit --display-notices",
- "test-coverage": "phpunit --coverage-html tests/coverage --display-notices"
+ "test-coverage": "phpunit --coverage-html tests/coverage --display-notices",
+ "format": "@php vendor/bin/mago format",
+ "format-check": "@php vendor/bin/mago format --check",
+ "lint": "@php vendor/bin/mago lint --minimum-fail-level note",
+ "analyze": "@php vendor/bin/mago analyze --minimum-fail-level note",
+ "check": ["@format-check", "@lint", "@analyze"]
},
"require": {
"php": ">=8.1",
@@ -32,6 +37,7 @@
"roave/better-reflection": "^6.8"
},
"require-dev": {
+ "carthage-software/mago": "1.59.0",
"phpunit/phpunit": "^10",
"symfony/var-dumper": "^6.2"
},
diff --git a/mago.toml b/mago.toml
new file mode 100644
index 0000000..0222421
--- /dev/null
+++ b/mago.toml
@@ -0,0 +1,39 @@
+php-version = "8.1"
+
+[source]
+paths = ["src", "tests"]
+includes = ["vendor"]
+excludes = ["tests/cache", "tests/coverage", "tests/tmp"]
+
+[linter]
+integrations = ["phpunit"]
+
+[linter.rules.disallowed-functions]
+enabled = true
+level = "error"
+functions = ["assert"]
+
+# Preserve the library's coercion contract and existing public call signatures.
+[linter.rules.strict-types]
+enabled = false
+[linter.rules.literal-named-argument]
+enabled = false
+[linter.rules.no-boolean-flag-parameter]
+enabled = false
+# isset intentionally distinguishes null from a usable value throughout this code.
+[linter.rules.no-isset]
+enabled = false
+# Complexity metrics are review aids, not correctness gates for a code transformation library.
+[linter.rules.halstead]
+enabled = false
+[linter.rules.kan-defect]
+enabled = false
+[linter.rules.cyclomatic-complexity]
+enabled = false
+[linter.rules.too-many-methods]
+enabled = false
+[linter.rules.excessive-parameter-list]
+threshold = 10
+
+[analyzer]
+check-missing-type-hints = true
diff --git a/src/CodeTransformerKernel.php b/src/CodeTransformerKernel.php
index 3cb9e5d..78bf60d 100644
--- a/src/CodeTransformerKernel.php
+++ b/src/CodeTransformerKernel.php
@@ -1,269 +1,263 @@
-Default: ROOT_DIR/cache/code-transformer
- *
- * @var string|null
- */
- protected ?string $cacheDir = null;
-
- /**
- * The exclude paths. Paths/directories in this array will be excluded
- *
- * @var array
- */
- protected array $excludePaths = [];
-
- /**
- * The cache file mode.
- *
Default: 0777 & ~{@link umask()}
- *
- * @var int|null
- */
- protected ?int $cacheFileMode = null;
-
- /**
- * Enable debug mode. This will disable the cache.
- *
Default: {@link false}
- *
- * @var bool
- */
- protected bool $debug = false;
-
- /**
- * The environment in which the application is running.
- *
Default: {@link Environment::DEVELOPMENT}
- *
- * If {@link Environment::PRODUCTION}, the cache will not be checked for
- * updates (better performance).
- * If {@link Environment::DEVELOPMENT}, the cache will be checked for
- * updates (better development experience).
- *
- * @var Environment
- */
- protected Environment $environment = Environment::DEVELOPMENT;
-
- /**
- * Throw an exception if the kernel is initialized twice.
- *
Default: {@link false}
- *
- * If {@link false}, any subsequent call to {@link init()} will be
- * ignored.
- *
- * @var bool
- */
- protected bool $throwExceptionOnDoubleInitialization = false;
-
- // endregion
-
- /**
- * List of transformers to be applied.
- *
- * @var class-string[]
- */
- protected array $transformers = [];
-
- /**
- * Resolve instance with dependency injection.
- *
- * @inheritDoc
- */
- public static function getInstance(): static
- {
- if (!isset(static::$instance)) {
- static::registerDependencyInjection();
-
- static::$instance = DI::get(static::class);
- }
-
- return static::$instance;
- }
-
- /**
- * Initialize the kernel.
- *
- * @return void
- */
- public static function init(): void
- {
- static::ensureNotKernelNamespace();
-
- $instance = static::getInstance();
-
- if ($instance->throwExceptionOnDoubleInitialization) {
- $instance->ensureNotInitialized();
- } elseif ($instance->initialized) {
- return;
- }
-
- // Initialize the services
- $instance->preInit();
- $instance->configureOptions();
- $instance->registerServices();
- $instance->registerAutoloadInterceptor();
-
- $instance->setInitialized();
- }
-
- /**
- * Internal dependency injection.
- *
- * @return void
- */
- protected static function registerDependencyInjection(): void
- {
- DI::getInstance()->register();
- }
-
- /**
- * Pre-initialize the services.
- *
- * @return void
- */
- protected function preInit(): void
- {
- // Set options
- $this->options->setOptions(
- cacheDir: $this->cacheDir,
- cacheFileMode: $this->cacheFileMode,
- debug: $this->debug,
- environment: $this->environment,
- excludePaths: $this->excludePaths,
- );
-
- // Add the transformers
- $this->transformerManager->addTransformers($this->transformers);
- }
-
- /**
- * Configure or modify kernel options.
- *
- * @return void
- */
- protected function configureOptions(): void
- {
- // Override this method to configure the options dynamically
- }
-
- /**
- * Custom dependency injection handler.
- *
- * Pass a closure that takes a transformer class name as the argument and
- * returns a transformer instance.
- *
- * @return null|Closure(class-string): Transformer
- */
- protected function dependencyInjectionHandler(): ?Closure
- {
- // Override this method to configure the dependency injection handler
-
- return null;
- }
-
- protected function registerServices(): void
- {
- $this->options->register();
-
- $this->transformerManager->registerCustomDependencyInjectionHandler(
- $this->dependencyInjectionHandler(),
- );
- $this->transformerManager->register();
-
- $this->cacheStateManager->register();
-
- $this->streamFilter->register();
- $this->cachedStreamFilter->register();
- }
-
- /**
- * Register the autoload interceptor.
- *
- * @return void
- */
- protected function registerAutoloadInterceptor(): void
- {
- // Overload the composer class loaders
- $this->autoloadInterceptor->register();
- }
-
- /**
- * Make sure that the kernel is not called from this class.
- *
- * @return void
- */
- protected static function ensureNotKernelNamespace(): void
- {
- // Get current namespace and class name
- $namespace = get_called_class();
-
- if ($namespace === CodeTransformerKernel::class) {
- throw new DirectKernelInitializationException;
- }
- }
-}
+Default: ROOT_DIR/cache/code-transformer
+ *
+ * @var string|null
+ */
+ protected ?string $cacheDir = null;
+
+ /**
+ * The exclude paths. Paths/directories in this array will be excluded
+ *
+ * @var string[]
+ */
+ protected array $excludePaths = [];
+
+ /**
+ * The cache file mode.
+ *
Default: 0777 & ~{@link umask()}
+ *
+ * @var int|null
+ */
+ protected ?int $cacheFileMode = null;
+
+ /**
+ * Enable debug mode. This will disable the cache.
+ *
Default: {@link false}
+ *
+ * @var bool
+ */
+ protected bool $debug = false;
+
+ /**
+ * The environment in which the application is running.
+ *
Default: {@link Environment::DEVELOPMENT}
+ *
+ * If {@link Environment::PRODUCTION}, the cache will not be checked for
+ * updates (better performance).
+ * If {@link Environment::DEVELOPMENT}, the cache will be checked for
+ * updates (better development experience).
+ *
+ * @var Environment
+ */
+ protected Environment $environment = Environment::DEVELOPMENT;
+
+ /**
+ * Throw an exception if the kernel is initialized twice.
+ *
Default: {@link false}
+ *
+ * If {@link false}, any subsequent call to {@link init()} will be
+ * ignored.
+ *
+ * @var bool
+ */
+ protected bool $throwExceptionOnDoubleInitialization = false;
+
+ // endregion
+
+ /**
+ * List of transformers to be applied.
+ *
+ * @var array
+ */
+ protected array $transformers = [];
+
+ /**
+ * Resolve instance with dependency injection.
+ *
+ * @inheritDoc
+ */
+ public static function getInstance(): static
+ {
+ if (!isset(static::$instance)) {
+ static::registerDependencyInjection();
+
+ static::$instance = DI::get(static::class);
+ }
+
+ /** @var mixed $instance */
+ $instance = static::$instance;
+ if (!$instance instanceof static) {
+ throw new LogicException('The container must return the requested kernel class.');
+ }
+
+ return $instance;
+ }
+
+ /**
+ * Initialize the kernel.
+ *
+ * @return void
+ */
+ public static function init(): void
+ {
+ static::ensureNotKernelNamespace();
+
+ $instance = static::getInstance();
+
+ if ($instance->throwExceptionOnDoubleInitialization) {
+ $instance->ensureNotInitialized();
+ }
+ if (!$instance->throwExceptionOnDoubleInitialization && $instance->initialized) {
+ return;
+ }
+
+ // Initialize the services
+ $instance->preInit();
+ $instance->configureOptions();
+ $instance->registerServices();
+ $instance->registerAutoloadInterceptor();
+
+ $instance->setInitialized();
+ }
+
+ /**
+ * Internal dependency injection.
+ *
+ * @return void
+ */
+ protected static function registerDependencyInjection(): void
+ {
+ DI::getInstance()->register();
+ }
+
+ /**
+ * Pre-initialize the services.
+ *
+ * @return void
+ */
+ protected function preInit(): void
+ {
+ // Set options
+ $this->options->setOptions(
+ cacheDir: $this->cacheDir,
+ cacheFileMode: $this->cacheFileMode,
+ debug: $this->debug,
+ environment: $this->environment,
+ excludePaths: $this->excludePaths,
+ );
+
+ // Add the transformers
+ $this->transformerManager->addTransformers($this->transformers);
+ }
+
+ /**
+ * Configure or modify kernel options.
+ *
+ * @return void
+ */
+ protected function configureOptions(): void
+ {
+ // Override this method to configure the options dynamically
+ }
+
+ /**
+ * Custom dependency injection handler.
+ *
+ * Pass a closure that takes a transformer class name as the argument and
+ * returns a transformer instance.
+ *
+ * @return null|Closure(class-string): Transformer
+ */
+ protected function dependencyInjectionHandler(): ?Closure
+ {
+ // Override this method to configure the dependency injection handler
+
+ return null;
+ }
+
+ protected function registerServices(): void
+ {
+ $this->options->register();
+
+ $this->transformerManager->registerCustomDependencyInjectionHandler($this->dependencyInjectionHandler());
+ $this->transformerManager->register();
+
+ DI::get(CacheStateManager::class)->register();
+
+ DI::get(StreamFilter::class)->register();
+ DI::get(CachedStreamFilter::class)->register();
+ }
+
+ /**
+ * Register the autoload interceptor.
+ *
+ * @return void
+ */
+ protected function registerAutoloadInterceptor(): void
+ {
+ // Overload the composer class loaders
+ DI::get(AutoloadInterceptor::class)->register();
+ }
+
+ /**
+ * Make sure that the kernel is not called from this class.
+ *
+ * @return void
+ */
+ protected static function ensureNotKernelNamespace(): void
+ {
+ // Get current namespace and class name
+ $namespace = get_called_class();
+
+ if ($namespace === CodeTransformerKernel::class) {
+ throw new DirectKernelInitializationException();
+ }
+ }
+}
diff --git a/src/Core/AutoloadInterceptor.php b/src/Core/AutoloadInterceptor.php
index b5a2753..6449ffe 100644
--- a/src/Core/AutoloadInterceptor.php
+++ b/src/Core/AutoloadInterceptor.php
@@ -1,80 +1,79 @@
-overloadComposerLoaders();
- }
-
- /**
- * Overload existing composer loaders
- *
- * @return void
- */
- private function overloadComposerLoaders(): void
- {
- // Get existing composer loaders
- $loaders = spl_autoload_functions();
- foreach ($loaders as $loader) {
- $loaderToUnregister = $loader;
-
- // Skip if not a class loader
- if (!is_array($loader)
- || !isset($loader[0])
- || !$loader[0] instanceof ComposerClassLoader
- ) {
- // @codeCoverageIgnoreStart
- continue;
- // @codeCoverageIgnoreEnd
- }
-
- // Get the original composer loader
- $originalClassLoader = $loader[0];
- $this->reflectionHelper->setClassLoader($originalClassLoader);
-
- // Create the Code Transformer class loader
- $loader[0] = DI::make(ClassLoader::class, [
- 'originalClassLoader' => $originalClassLoader,
- ]);
-
- // Unregister the original composer loader
- spl_autoload_unregister($loaderToUnregister);
-
- // Register the Code Transformer class loader
- spl_autoload_register($loader);
- }
- }
-}
+overloadComposerLoaders();
+ }
+
+ /**
+ * Overload existing composer loaders
+ *
+ * @return void
+ */
+ private function overloadComposerLoaders(): void
+ {
+ // Get existing composer loaders
+ $loaders = spl_autoload_functions();
+ foreach ($loaders as $loader) {
+ $loaderToUnregister = $loader;
+
+ // Skip if not a class loader
+ if (!is_array($loader) || !$loader[0] instanceof ComposerClassLoader) {
+ // @codeCoverageIgnoreStart
+ continue;
+
+ // @codeCoverageIgnoreEnd
+ }
+
+ // Get the original composer loader
+ $originalClassLoader = $loader[0];
+ $this->reflectionHelper->setClassLoader($originalClassLoader);
+
+ // Create the Code Transformer class loader
+ $classLoader = DI::make(ClassLoader::class, [
+ 'originalClassLoader' => $originalClassLoader,
+ ]);
+
+ // Unregister the original composer loader
+ spl_autoload_unregister($loaderToUnregister);
+
+ // Register the Code Transformer class loader
+ spl_autoload_register([$classLoader, 'loadClass']);
+ }
+ }
+}
diff --git a/src/Core/AutoloadInterceptor/ClassContainer.php b/src/Core/AutoloadInterceptor/ClassContainer.php
index 7f97917..ceced33 100644
--- a/src/Core/AutoloadInterceptor/ClassContainer.php
+++ b/src/Core/AutoloadInterceptor/ClassContainer.php
@@ -1,56 +1,60 @@
-
- */
- private array $classContext = [];
-
- /**
- * Add a class path.
- *
- * @param string $path
- * @param class-string $namespacedClass
- * @param string|null $cachedFilePath
- *
- * @return void
- */
- public function addClassContext(
- string $path,
- string $namespacedClass,
- ?string $cachedFilePath = null,
- ): void {
- $this->classContext[$path] = [
- 'namespacedClass' => $namespacedClass,
- 'cachedFilePath' => $cachedFilePath,
- ];
- }
-
- /**
- * Get a class path.
- *
- * @param string $path
- *
- * @return string
- */
- public function getNamespacedClassByPath(string $path): string
- {
- return $this->classContext[$path]['namespacedClass'];
- }
-
- public function getCachedFilePath(string $filePath): string
- {
- return $this->classContext[$filePath]['cachedFilePath'];
- }
-}
+
+ */
+ private array $classContext = [];
+
+ /**
+ * Add a class path.
+ *
+ * @param string $path
+ * @param class-string $namespacedClass
+ * @param string|null $cachedFilePath
+ *
+ * @return void
+ */
+ public function addClassContext(string $path, string $namespacedClass, ?string $cachedFilePath = null): void
+ {
+ $this->classContext[$path] = [
+ 'namespacedClass' => $namespacedClass,
+ 'cachedFilePath' => $cachedFilePath,
+ ];
+ }
+
+ /**
+ * Get a class path.
+ *
+ * @param string $path
+ *
+ * @return class-string
+ */
+ public function getNamespacedClassByPath(string $path): string
+ {
+ return $this->classContext[$path]['namespacedClass'];
+ }
+
+ public function getCachedFilePath(string $filePath): string
+ {
+ $cachedFilePath = $this->classContext[$filePath]['cachedFilePath'] ?? null;
+ if ($cachedFilePath === null) {
+ throw new LogicException('No cached file registered for ' . $filePath);
+ }
+
+ return $cachedFilePath;
+ }
+}
diff --git a/src/Core/AutoloadInterceptor/ClassLoader.php b/src/Core/AutoloadInterceptor/ClassLoader.php
index cbc1d20..7bf37ea 100644
--- a/src/Core/AutoloadInterceptor/ClassLoader.php
+++ b/src/Core/AutoloadInterceptor/ClassLoader.php
@@ -1,201 +1,166 @@
-findFile($namespacedClass)) {
- include $file;
-
- return true;
- }
-
- // @codeCoverageIgnoreStart
- // Not sure how to test this
- return false;
- // @codeCoverageIgnoreEnd
- }
-
- /**
- * Find the path to the file and match and apply the transformers.
- *
- * @param class-string $namespacedClass
- *
- * @return false|string
- *
- * @noinspection PhpParameterNameChangedDuringInheritanceInspection
- * @noinspection PhpStatementHasEmptyBodyInspection
- */
- public function findFile($namespacedClass): false|string
- {
- $filePath = $this->originalClassLoader->findFile($namespacedClass);
-
- // @codeCoverageIgnoreStart
- // Not sure how to test this
- if ($filePath === false) {
- return false;
- }
- // @codeCoverageIgnoreEnd
-
- // Prevent infinite recursion
- if ($this->isInternal($namespacedClass)) {
- return $filePath;
- }
-
- $filePath = Path::resolve($filePath);
-
- foreach ($this->options->getExcludePaths() as $path) {
- if (str_starts_with($filePath, Path::resolve($path))) {
- return $filePath;
- }
- }
-
- // Query cache state
- $cacheState = $this->cacheStateManager->queryCacheState($filePath);
-
- // When debugging, bypass the caching mechanism
- if ($this->options->isDebug()) {
- // ...
- }
-
- // In production mode, use the cache without checking if it is fresh
- elseif ($this->options->getEnvironment() === Environment::PRODUCTION
- && $cacheState
- ) {
- // Use the cached file if transformations have been applied
- if ($cacheFilePath = $cacheState->getFilePath()) {
- $this->classContainer->addClassContext(
- $filePath,
- $namespacedClass,
- $cacheFilePath,
- );
-
- // For cached files, the debugger will have trouble finding the
- // original file, that's why we rewrite the file path with a PHP
- // stream filter
- /** @see CachedStreamFilter::filter() */
- return $this->filterInjector->rewriteCached($filePath);
- }
-
- // Or return the original file if no transformations have been applied
- return $filePath;
- }
-
- // In development mode, check if the cache is fresh
- elseif ($this->options->getEnvironment() === Environment::DEVELOPMENT
- && $cacheState
- && $cacheState->isFresh()
- ) {
- if ($cacheFilePath = $cacheState->getFilePath()) {
- $this->classContainer->addClassContext(
- $filePath,
- $namespacedClass,
- $cacheFilePath,
- );
-
- return $this->filterInjector->rewriteCached($filePath);
- }
-
- return $filePath;
- }
-
-
- // Check if the class should be transformed
- if (!$this->transformerMatcher->matchAndStore($namespacedClass, $filePath)) {
- return $filePath;
- }
-
- // Add the class to store the file path
- $this->classContainer->addClassContext($filePath, $namespacedClass);
-
- // Replace the file path with a PHP stream filter
- /** @see StreamFilter::filter() */
- return $this->filterInjector->rewrite($filePath);
- }
-
- /**
- * Check if the class is internal to the Code Transformer.
- *
- * @param string $namespacedClass
- *
- * @return bool
- */
- protected function isInternal(string $namespacedClass): bool
- {
- return str_starts_with_any_but_not(
- $namespacedClass,
- [
- 'Okapi\\CodeTransformer\\',
- 'Okapi\\Path\\',
- 'Okapi\\Wildcards\\',
- 'DI\\',
- ],
- [
- 'Okapi\\CodeTransformer\\Tests\\',
- ],
- );
- }
-}
+findFile($class);
+ if ($file !== false) {
+ include $file;
+ return true;
+ }
+
+ return null;
+ }
+
+ /**
+ * Find the path to the file and match and apply the transformers.
+ *
+ * @param string $class
+ *
+ * @return false|string
+ */
+ public function findFile($class): false|string
+ {
+ /** @var class-string $namespacedClass */
+ $namespacedClass = $class;
+ $filePath = $this->originalClassLoader->findFile($namespacedClass);
+
+ // @codeCoverageIgnoreStart
+ // Not sure how to test this
+ if ($filePath === false) {
+ return false;
+ }
+ // @codeCoverageIgnoreEnd
+
+ // Prevent infinite recursion
+ if ($this->isInternal($namespacedClass)) {
+ return $filePath;
+ }
+
+ $filePath = Path::resolve($filePath);
+ if (!is_string($filePath)) {
+ return false;
+ }
+
+ foreach ($this->options->getExcludePaths() as $path) {
+ $resolvedPath = Path::resolve($path);
+ if (is_string($resolvedPath) && str_starts_with($filePath, $resolvedPath)) {
+ return $filePath;
+ }
+ }
+
+ // Query cache state
+ $cacheState = $this->cacheStateManager->queryCacheState($filePath);
+
+ $useCache =
+ !$this->options->isDebug()
+ && $cacheState !== null
+ && ($this->options->getEnvironment() === Environment::PRODUCTION || $cacheState->isFresh());
+ if ($useCache) {
+ $cacheFilePath = $cacheState->getFilePath();
+ if ($cacheFilePath !== null) {
+ $this->classContainer->addClassContext($filePath, $namespacedClass, $cacheFilePath);
+ return $this->filterInjector->rewriteCached($filePath);
+ }
+
+ return $filePath;
+ }
+
+ // Check if the class should be transformed
+ if (!$this->transformerMatcher->matchAndStore($namespacedClass, $filePath)) {
+ return $filePath;
+ }
+
+ // Add the class to store the file path
+ $this->classContainer->addClassContext($filePath, $namespacedClass);
+
+ // Replace the file path with a PHP stream filter
+ /** @see StreamFilter::filter() */
+ return $this->filterInjector->rewrite($filePath);
+ }
+
+ /**
+ * Check if the class is internal to the Code Transformer.
+ *
+ * @param string $namespacedClass
+ *
+ * @return bool
+ */
+ protected function isInternal(string $namespacedClass): bool
+ {
+ return str_starts_with_any_but_not(
+ $namespacedClass,
+ [
+ 'Okapi\\CodeTransformer\\',
+ 'Okapi\\Path\\',
+ 'Okapi\\Wildcards\\',
+ 'DI\\',
+ ],
+ [
+ 'Okapi\\CodeTransformer\\Tests\\',
+ ],
+ );
+ }
+}
diff --git a/src/Core/Cache/CachePaths.php b/src/Core/Cache/CachePaths.php
index 998db4a..7dcdd6d 100644
--- a/src/Core/Cache/CachePaths.php
+++ b/src/Core/Cache/CachePaths.php
@@ -1,86 +1,91 @@
-appendToCachePath($filePath, $this->transformedDir);
- }
-
- /**
- * Append a path to the cache path.
- *
- * @param string $file
- * @param string $append
- *
- * @return string
- */
- protected function appendToCachePath(string $file, string $append): string
- {
- $appDir = $this->options->getAppDir();
- $cacheDir = $this->options->getCacheDir();
-
- // Append the string to the cache dir
- $newDir = Path::join($cacheDir, $append);
-
- return Path::resolve(
- str_replace($appDir, $newDir, $file),
- );
- }
-
- /**
- * Get the file path for the cache file.
- *
- * @return string
- */
- public function getCacheFilePath(): string
- {
- $cacheDir = $this->options->getCacheDir();
-
- return Path::join($cacheDir, $this->cacheFileName);
- }
-}
+appendToCachePath($filePath, $this->transformedDir);
+ }
+
+ /**
+ * Append a path to the cache path.
+ *
+ * @param string $file
+ * @param string $append
+ *
+ * @return string
+ */
+ protected function appendToCachePath(string $file, string $append): string
+ {
+ $appDir = $this->options->getAppDir();
+ $cacheDir = $this->options->getCacheDir();
+
+ // Append the string to the cache dir
+ $newDir = Path::join($cacheDir, $append);
+
+ $path = Path::resolve(str_replace($appDir, $newDir, $file));
+ if (!is_string($path)) {
+ throw new RuntimeException('Cannot resolve cache path for ' . $file);
+ }
+
+ return $path;
+ }
+
+ /**
+ * Get the file path for the cache file.
+ *
+ * @return string
+ */
+ public function getCacheFilePath(): string
+ {
+ $cacheDir = $this->options->getCacheDir();
+
+ return Path::join($cacheDir, $this->cacheFileName);
+ }
+}
diff --git a/src/Core/Cache/CacheState.php b/src/Core/Cache/CacheState.php
index 546a1af..4686b8b 100644
--- a/src/Core/Cache/CacheState.php
+++ b/src/Core/Cache/CacheState.php
@@ -1,170 +1,182 @@
- $data
- */
- public function __construct(
- array $data = [],
- ) {
- $this->setData($data);
- }
-
- /**
- * Get the cache state as an array.
- *
- * @return array
- */
- public function toArray(): array
- {
- return [
- static::TYPE => $this->getType(),
- ...$this->getAllData(),
- ];
- }
-
- /**
- * Get the cache state as an array.
- *
- * @return array
- */
- private function getAllData(): array
- {
- $data = [];
-
- foreach ($this->getRequiredKeys() as $key) {
- $data[$key] = $this->{$key};
- }
-
- return $data;
- }
-
- /**
- * Get the cache state type.
- *
- * @return string
- */
- protected function getType(): string
- {
- // Return the class name without the namespace
- return substr(
- static::class,
- strrpos(static::class, '\\') + 1,
- );
- }
-
- /**
- * Get the required keys for the cache state.
- *
- * @return string[]
- */
- public function getRequiredKeys(): array
- {
- return [
- static::ORIGINAL_FILE_PATH_KEY,
- static::NAMESPACED_CLASS_KEY,
- static::MODIFICATION_TIME_KEY,
- ];
- }
-
- /**
- * Create a cache state if it is valid.
- *
- * @param array $cacheStateArray
- *
- * @return self|null
- */
- public function createIfValid(array $cacheStateArray): ?CacheState
- {
- if (!$this->valid($cacheStateArray)) {
- // @codeCoverageIgnoreStart
- return null;
- // @codeCoverageIgnoreEnd
- }
-
- $this->setData($cacheStateArray);
-
- return $this;
- }
-
- /**
- * Validate the cache state.
- *
- * @param array $cacheStateArray
- *
- * @return bool
- */
- private function valid(array $cacheStateArray): bool
- {
- // Check if all required keys are present
- foreach ($this->getRequiredKeys() as $requiredKey) {
- if (!isset($cacheStateArray[$requiredKey])) {
- // @codeCoverageIgnoreStart
- return false;
- // @codeCoverageIgnoreEnd
- }
- }
-
- return true;
- }
-
- /**
- * Set the cache state data.
- *
- * @param array $cacheStateArray
- */
- private function setData(array $cacheStateArray): void
- {
- foreach ($cacheStateArray as $key => $value) {
- $this->{$key} = $value;
- }
- }
-
- /**
- * Check if the cache state is fresh (not outdated).
- *
- * @return bool
- */
- public function isFresh(): bool
- {
- if (!file_exists($this->originalFilePath)) {
- // @codeCoverageIgnoreStart
- return false;
- // @codeCoverageIgnoreEnd
- }
-
- if (filemtime($this->originalFilePath) > $this->modificationTime) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Get the file path.
- *
- * @return string|null
- */
- abstract public function getFilePath(): ?string;
-}
+ $data
+ */
+ public function __construct(array $data = [])
+ {
+ $this->setData($data);
+ }
+
+ /**
+ * Get the cache state as an array.
+ *
+ * @return array
+ */
+ public function toArray(): array
+ {
+ return [
+ static::TYPE => $this->getType(),
+ ...$this->getAllData(),
+ ];
+ }
+
+ /**
+ * Get the cache state as an array.
+ *
+ * @return array
+ */
+ private function getAllData(): array
+ {
+ $data = [];
+
+ foreach ($this->getRequiredKeys() as $key) {
+ $property = new ReflectionProperty($this, $key);
+ /** @var mixed $value */
+ $value = $property->getValue($this);
+ $data[$key] = $value;
+ }
+
+ return $data;
+ }
+
+ /**
+ * Get the cache state type.
+ *
+ * @return string
+ */
+ protected function getType(): string
+ {
+ // Return the class name without the namespace
+ $separator = strrpos(static::class, '\\');
+ return $separator === false ? static::class : substr(static::class, $separator + 1);
+ }
+
+ /**
+ * Get the required keys for the cache state.
+ *
+ * @return string[]
+ */
+ public function getRequiredKeys(): array
+ {
+ return [
+ static::ORIGINAL_FILE_PATH_KEY,
+ static::NAMESPACED_CLASS_KEY,
+ static::MODIFICATION_TIME_KEY,
+ ];
+ }
+
+ /**
+ * Create a cache state if it is valid.
+ *
+ * @param array $cacheStateArray
+ *
+ * @return self|null
+ */
+ public function createIfValid(array $cacheStateArray): ?CacheState
+ {
+ if (!$this->valid($cacheStateArray)) {
+ // @codeCoverageIgnoreStart
+ return null;
+
+ // @codeCoverageIgnoreEnd
+ }
+
+ $this->setData($cacheStateArray);
+
+ return $this;
+ }
+
+ /**
+ * Validate the cache state.
+ *
+ * @param array $cacheStateArray
+ *
+ * @return bool
+ */
+ private function valid(array $cacheStateArray): bool
+ {
+ // Check if all required keys are present
+ foreach ($this->getRequiredKeys() as $requiredKey) {
+ if (!isset($cacheStateArray[$requiredKey])) {
+ // @codeCoverageIgnoreStart
+ return false;
+
+ // @codeCoverageIgnoreEnd
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Set the cache state data.
+ *
+ * @param array $cacheStateArray
+ */
+ private function setData(array $cacheStateArray): void
+ {
+ foreach (array_keys($cacheStateArray) as $key) {
+ /** @var mixed $value */
+ $value = $cacheStateArray[$key];
+ if (!is_string($key) || !property_exists($this, $key)) {
+ continue;
+ }
+ (new ReflectionProperty($this, $key))->setValue($this, $value);
+ }
+ }
+
+ /**
+ * Check if the cache state is fresh (not outdated).
+ *
+ * @return bool
+ */
+ public function isFresh(): bool
+ {
+ if (!file_exists($this->originalFilePath)) {
+ // @codeCoverageIgnoreStart
+ return false;
+
+ // @codeCoverageIgnoreEnd
+ }
+
+ $modified = filemtime($this->originalFilePath);
+ if ($modified === false || $modified > $this->modificationTime) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Get the file path.
+ *
+ * @return string|null
+ */
+ abstract public function getFilePath(): ?string;
+}
diff --git a/src/Core/Cache/CacheState/EmptyResultCacheState.php b/src/Core/Cache/CacheState/EmptyResultCacheState.php
index cbd783d..51e0168 100644
--- a/src/Core/Cache/CacheState/EmptyResultCacheState.php
+++ b/src/Core/Cache/CacheState/EmptyResultCacheState.php
@@ -1,22 +1,22 @@
-transformedFilePath)) {
- return false;
- }
-
- // Check if any of the transformer files have been modified or deleted
- foreach ($this->transformerFilePaths as $transformerFilePath) {
- if (!file_exists($transformerFilePath)) {
- // @codeCoverageIgnoreStart
- return false;
- // @codeCoverageIgnoreEnd
- }
-
- if (filemtime($transformerFilePath) > $this->modificationTime) {
- // @codeCoverageIgnoreStart
- return false;
- // @codeCoverageIgnoreEnd
- }
- }
-
- return true;
- }
-
- /**
- * @inheritDoc
- */
- public function getFilePath(): ?string
- {
- return $this->transformedFilePath;
- }
-}
+transformedFilePath)) {
+ return false;
+ }
+
+ // Check if any of the transformer files have been modified or deleted
+ foreach ($this->transformerFilePaths as $transformerFilePath) {
+ if (!file_exists($transformerFilePath)) {
+ // @codeCoverageIgnoreStart
+ return false;
+
+ // @codeCoverageIgnoreEnd
+ }
+
+ $modified = filemtime($transformerFilePath);
+ if ($modified === false || $modified > $this->modificationTime) {
+ // @codeCoverageIgnoreStart
+ return false;
+
+ // @codeCoverageIgnoreEnd
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function getFilePath(): ?string
+ {
+ return $this->transformedFilePath;
+ }
+}
diff --git a/src/Core/Cache/CacheStateFactory.php b/src/Core/Cache/CacheStateFactory.php
index ffbc1e1..7f928a0 100644
--- a/src/Core/Cache/CacheStateFactory.php
+++ b/src/Core/Cache/CacheStateFactory.php
@@ -1,74 +1,68 @@
- TransformedCacheState::class,
- 'EmptyResultCacheState' => EmptyResultCacheState::class,
- 'NoTransformationsCacheState' => NoTransformationsCacheState::class,
- ];
-
- /**
- * Create cache states from the cache state file.
- *
- * @param array> $cacheStatesArray
- *
- * @return CacheState[]
- */
- public function createCacheStates(array $cacheStatesArray): array
- {
- $cacheStateObjects = [];
-
- foreach ($cacheStatesArray as $cacheStateArray) {
- // Skip cache states without a type
- if (!isset($cacheStateArray[CacheState::TYPE])) {
- // @codeCoverageIgnoreStart
- continue;
- // @codeCoverageIgnoreEnd
- }
-
- // Get type
- $type = $cacheStateArray[CacheState::TYPE];
- unset($cacheStateArray[CacheState::TYPE]);
-
- // Instantiate cache state
- try {
- /** @var CacheState $cacheState */
- $cacheState = DI::make(static::CACHE_STATE_MAP[$type]);
- // @codeCoverageIgnoreStart
- } catch (TypeError) {
- continue;
- }
- // @codeCoverageIgnoreEnd
-
- // Create if valid
- $cacheState = $cacheState->createIfValid($cacheStateArray);
- if (!$cacheState) {
- // @codeCoverageIgnoreStart
- continue;
- // @codeCoverageIgnoreEnd
- }
-
- // Add cache state to array
- $cacheStateObjects[$cacheState->originalFilePath] = $cacheState;
- }
-
- return $cacheStateObjects;
- }
-}
+ TransformedCacheState::class,
+ 'EmptyResultCacheState' => EmptyResultCacheState::class,
+ 'NoTransformationsCacheState' => NoTransformationsCacheState::class,
+ ];
+
+ /**
+ * Create cache states from the cache state file.
+ *
+ * @param array $cacheStatesArray
+ *
+ * @return array
+ */
+ public function createCacheStates(array $cacheStatesArray): array
+ {
+ $cacheStateObjects = [];
+
+ foreach (array_keys($cacheStatesArray) as $cacheKey) {
+ /** @var mixed $cacheStateArray */
+ $cacheStateArray = $cacheStatesArray[$cacheKey];
+ if (!is_array($cacheStateArray)) {
+ continue;
+ }
+
+ /** @var mixed $type */
+ $type = $cacheStateArray[CacheState::TYPE] ?? null;
+ if (!is_string($type) || !isset(static::CACHE_STATE_MAP[$type])) {
+ continue;
+ }
+
+ unset($cacheStateArray[CacheState::TYPE]);
+ $cacheState = DI::make(static::CACHE_STATE_MAP[$type]);
+
+ // Create if valid
+ $cacheState = $cacheState->createIfValid($cacheStateArray);
+ if (!$cacheState) {
+ // @codeCoverageIgnoreStart
+ continue;
+
+ // @codeCoverageIgnoreEnd
+ }
+
+ // Add cache state to array
+ $cacheStateObjects[$cacheState->originalFilePath] = $cacheState;
+ }
+
+ return $cacheStateObjects;
+ }
+}
diff --git a/src/Core/Cache/CacheStateManager.php b/src/Core/Cache/CacheStateManager.php
index 97587a3..87bf550 100644
--- a/src/Core/Cache/CacheStateManager.php
+++ b/src/Core/Cache/CacheStateManager.php
@@ -1,251 +1,242 @@
-
- */
- private array $cacheState = [];
-
- /**
- * New metadata for the transformation state of a file.
- *
- * @var array
- */
- private array $newCacheState = [];
-
- // region Initialization
-
- /**
- * Register the cache path manager.
- *
- * @return void
- */
- public function register(): void
- {
- $this->initializeCacheDirectory();
-
- $this->loadCacheState();
- }
-
- /**
- * Initialize the cache directory.
- *
- * @return void
- */
- private function initializeCacheDirectory(): void
- {
- $cacheDir = $this->options->getCacheDir();
-
- if (file_exists($cacheDir)) {
- return;
- }
-
- Filesystem::mkdir(
- $cacheDir,
- $this->options->getCacheFileMode(),
- recursive: true,
- );
- }
-
- /**
- * Load the saved cache state if it exists.
- *
- * @return void
- */
- private function loadCacheState(): void
- {
- $cacheFilePath = $this->cachePaths->getCacheFilePath();
-
- if (!file_exists($cacheFilePath)) {
- return;
- }
-
- // Read file
- $cacheFileContent = Filesystem::readFile($cacheFilePath);
-
- $appDir = $this->options->getAppDir();
- $cacheDir = $this->options->getCacheDir();
-
- // Replace the keywords
- $cacheFileContent = str_replace(
- [static::CODE_TRANSFORMER_APP_DIR, static::CODE_TRANSFORMER_CACHE_DIR],
- [addslashes($appDir), addslashes($cacheDir)],
- $cacheFileContent,
- );
-
- // Remove the opening PHP tag
- $cacheFileContent = preg_replace('/^<\?php/', '', $cacheFileContent);
-
- // Unserialize
- $cacheStatesArray = eval($cacheFileContent);
-
- // Check the hash
- $hash = $this->getHash();
- if (!isset($cacheStatesArray[static::HASH])
- || $cacheStatesArray[static::HASH] !== $hash
- ) {
- return;
- }
- unset($cacheStatesArray[static::HASH]);
-
- // Create the cache state
- $cacheStates = $this->cacheStateFactory->createCacheStates($cacheStatesArray);
-
- $this->cacheState = $cacheStates;
- }
-
- /**
- * Get the hash of the transformers.
- *
- * @return string
- */
- protected function getHash(): string
- {
- $transformers = $this->transformerManager->getTransformers();
- return md5(serialize($transformers));
- }
-
- // endregion
-
- // region Destructor
-
- /**
- * Automatic destructor saves the cache state.
- */
- public function __destruct()
- {
- $this->saveCacheState();
- }
-
- /**
- * Save the cache state.
- *
- * @return void
- */
- private function saveCacheState(): void
- {
- if (empty($this->newCacheState)) {
- // @codeCoverageIgnoreStart
- return;
- // @codeCoverageIgnoreEnd
- }
-
- // Opening PHP tag
- $phpCode = " $cacheState->toArray(),
- array_merge($this->cacheState, $this->newCacheState),
- );
-
- // Set the hash
- $cacheStateArray[static::HASH] = $this->getHash();
-
- // Serialize the cache state
- $phpCode .= var_export($cacheStateArray, true);
-
- // Semicolon
- $phpCode .= ';';
-
- $appDir = $this->options->getAppDir();
- $cacheDir = $this->options->getCacheDir();
-
- // Replace the keywords
- $phpCode = str_replace(
- [addslashes($appDir), addslashes($cacheDir)],
- [static::CODE_TRANSFORMER_APP_DIR, static::CODE_TRANSFORMER_CACHE_DIR],
- $phpCode,
- );
-
- // Write file
- Filesystem::writeFile(
- $this->cachePaths->getCacheFilePath(),
- $phpCode,
- );
- }
-
- // endregion
-
- /**
- * Query the cache state for a file.
- *
- * @param string $filePath
- *
- * @return ?CacheState
- */
- public function queryCacheState(string $filePath): ?CacheState
- {
- return $this->cacheState[$filePath] ?? null;
- }
-
- /**
- * Set the cache state for a file.
- *
- * @param string $filePath
- * @param CacheState $cacheState
- *
- * @return void
- */
- public function setCacheState(
- string $filePath,
- CacheState $cacheState,
- ): void {
- $this->newCacheState[$filePath] = $cacheState;
- }
-}
+
+ */
+ private array $cacheState = [];
+
+ /**
+ * New metadata for the transformation state of a file.
+ *
+ * @var array
+ */
+ private array $newCacheState = [];
+
+ // region Initialization
+
+ /**
+ * Register the cache path manager.
+ *
+ * @return void
+ */
+ public function register(): void
+ {
+ $this->initializeCacheDirectory();
+
+ $this->loadCacheState();
+ }
+
+ /**
+ * Initialize the cache directory.
+ *
+ * @return void
+ */
+ private function initializeCacheDirectory(): void
+ {
+ $cacheDir = $this->options->getCacheDir();
+
+ if (file_exists($cacheDir)) {
+ return;
+ }
+
+ Filesystem::mkdir($cacheDir, $this->options->getCacheFileMode(), recursive: true);
+ }
+
+ /**
+ * Load the saved cache state if it exists.
+ *
+ * @return void
+ */
+ private function loadCacheState(): void
+ {
+ $cacheFilePath = $this->cachePaths->getCacheFilePath();
+
+ if (!file_exists($cacheFilePath)) {
+ return;
+ }
+
+ // Read the trusted PHP array generated by saveCacheState in an isolated scope.
+ /** @var mixed $cacheStatesArray */
+ $cacheStatesArray = (static fn(string $file): mixed => require $file)($cacheFilePath);
+ if (!is_array($cacheStatesArray)) {
+ return;
+ }
+
+ $appDir = $this->options->getAppDir();
+ $cacheDir = $this->options->getCacheDir();
+ array_walk_recursive($cacheStatesArray, static function (mixed &$value) use ($appDir, $cacheDir): void {
+ if (is_string($value)) {
+ $value = str_replace(
+ [static::CODE_TRANSFORMER_APP_DIR, static::CODE_TRANSFORMER_CACHE_DIR],
+ [$appDir, $cacheDir],
+ $value,
+ );
+ }
+ });
+
+ // Check the hash
+ $hash = $this->getHash();
+ if (!isset($cacheStatesArray[static::HASH]) || $cacheStatesArray[static::HASH] !== $hash) {
+ return;
+ }
+ unset($cacheStatesArray[static::HASH]);
+
+ // Create the cache state
+ $cacheStates = $this->cacheStateFactory->createCacheStates($cacheStatesArray);
+
+ $this->cacheState = $cacheStates;
+ }
+
+ /**
+ * Get the hash of the transformers.
+ *
+ * @return string
+ */
+ protected function getHash(): string
+ {
+ $transformers = $this->transformerManager->getTransformers();
+ return md5(serialize($transformers));
+ }
+
+ // endregion
+
+ // region Destructor
+
+ /**
+ * Automatic destructor saves the cache state.
+ */
+ public function __destruct()
+ {
+ $this->saveCacheState();
+ }
+
+ /**
+ * Save the cache state.
+ *
+ * @return void
+ */
+ private function saveCacheState(): void
+ {
+ if ($this->newCacheState === []) {
+ // @codeCoverageIgnoreStart
+ return;
+
+ // @codeCoverageIgnoreEnd
+ }
+
+ // Opening PHP tag
+ $phpCode = " $cacheState->toArray(),
+ array_merge($this->cacheState, $this->newCacheState),
+ );
+
+ // Set the hash
+ $cacheStateArray[static::HASH] = $this->getHash();
+
+ // Serialize the cache state
+ $phpCode .= var_export($cacheStateArray, true);
+
+ // Semicolon
+ $phpCode .= ';';
+
+ $appDir = $this->options->getAppDir();
+ $cacheDir = $this->options->getCacheDir();
+
+ // Replace the keywords
+ $phpCode = str_replace(
+ [addslashes($appDir), addslashes($cacheDir)],
+ [static::CODE_TRANSFORMER_APP_DIR, static::CODE_TRANSFORMER_CACHE_DIR],
+ $phpCode,
+ );
+
+ // Write file
+ Filesystem::writeFile($this->cachePaths->getCacheFilePath(), $phpCode);
+ }
+
+ // endregion
+
+ /**
+ * Query the cache state for a file.
+ *
+ * @param string $filePath
+ *
+ * @return ?CacheState
+ */
+ public function queryCacheState(string $filePath): ?CacheState
+ {
+ return $this->cacheState[$filePath] ?? null;
+ }
+
+ /**
+ * Set the cache state for a file.
+ *
+ * @param string $filePath
+ * @param CacheState $cacheState
+ *
+ * @return void
+ */
+ public function setCacheState(string $filePath, CacheState $cacheState): void
+ {
+ $this->newCacheState[$filePath] = $cacheState;
+ }
+}
diff --git a/src/Core/CachedStreamFilter.php b/src/Core/CachedStreamFilter.php
index 769bd70..bcbfaee 100644
--- a/src/Core/CachedStreamFilter.php
+++ b/src/Core/CachedStreamFilter.php
@@ -1,60 +1,71 @@
-data .= $bucket->data;
- }
-
- // If stream is closed, return the cached file
- if ($closing || feof($this->stream)) {
- $consumed = strlen($this->data);
-
- $metadata = DI::make(Metadata::class, [
- 'stream' => $this->stream,
- 'originalSource' => $this->data,
- ]);
-
- $classContainer = DI::get(ClassContainer::class);
- $cachedFilePath = $classContainer->getCachedFilePath($metadata->uri);
-
- $source = Filesystem::readFile($cachedFilePath);
-
- $bucket = stream_bucket_new($this->stream, $source);
- stream_bucket_append($out, $bucket);
-
- // Pass the (cached) source code to the next filter
- return PSFS_PASS_ON;
- }
-
- // No data has been consumed
- return PSFS_PASS_ON;
- }
-}
+stream;
+ if (!is_resource($stream)) {
+ throw new InvalidStreamException();
+ }
+
+ // Read stream until EOF
+ while (true) {
+ $bucket = stream_bucket_make_writeable($in);
+ if ($bucket === null) {
+ break;
+ }
+ $this->data .= $bucket->data;
+ }
+
+ // If stream is closed, return the cached file
+ if ($closing || feof($stream)) {
+ $consumed = strlen($this->data);
+
+ $metadata = DI::make(Metadata::class, [
+ 'stream' => $this->stream,
+ 'originalSource' => $this->data,
+ ]);
+
+ $classContainer = DI::get(ClassContainer::class);
+ $cachedFilePath = $classContainer->getCachedFilePath($metadata->uri);
+
+ $source = Filesystem::readFile($cachedFilePath);
+
+ $bucket = stream_bucket_new($stream, $source);
+ stream_bucket_append($out, $bucket);
+
+ // Pass the (cached) source code to the next filter
+ return PSFS_PASS_ON;
+ }
+
+ // No data has been consumed
+ return PSFS_PASS_ON;
+ }
+}
diff --git a/src/Core/Container/TransformerContainer.php b/src/Core/Container/TransformerContainer.php
index d4d5ebc..22f89aa 100644
--- a/src/Core/Container/TransformerContainer.php
+++ b/src/Core/Container/TransformerContainer.php
@@ -1,22 +1,22 @@
-[]
- */
- private array $transformers = [];
-
- /**
- * The list of transformer containers.
- *
- * @var array Key is the transformer file path
- */
- private array $transformerContainers = [];
-
- /**
- * @var null|Closure(class-string): Transformer
- */
- private ?Closure $dependencyInjectionHandler = null;
-
- // region Pre-Initialization
-
- /**
- * Add transformers.
- *
- * @param class-string[] $transformers
- *
- * @return void
- */
- public function addTransformers(array $transformers): void
- {
- $this->transformers = array_merge(
- $this->transformers,
- $transformers,
- );
- }
-
- // endregion
-
- // region Initialization
-
- /**
- * @param null|(Closure(class-string): Transformer) $dependencyInjectionHandler
- */
- public function registerCustomDependencyInjectionHandler(
- ?Closure $dependencyInjectionHandler
- ): void {
- $this->dependencyInjectionHandler = $dependencyInjectionHandler;
- }
-
- public function register(): void
- {
- $this->loadTransformers();
- }
-
- private function loadTransformers(): void
- {
- foreach ($this->transformers as $transformer) {
- $this->loadTransformer($transformer);
- }
- }
-
- /**
- * @param class-string $transformerClassName
- *
- * @noinspection PhpUnhandledExceptionInspection
- * @noinspection PhpDocMissingThrowsInspection
- */
- private function loadTransformer(mixed $transformerClassName): void
- {
- // Check if the transformer is already loaded
- if (array_key_exists($transformerClassName, $this->transformerContainers)) {
- // @codeCoverageIgnoreStart
- return;
- // @codeCoverageIgnoreEnd
- }
-
- // Validate the transformer
- if (gettype($transformerClassName) !== 'string') {
- throw new InvalidTransformerClassNameException;
- }
-
- // Instantiate the transformer
- if ($this->dependencyInjectionHandler) {
- $transformerInstance = ($this->dependencyInjectionHandler)(
- $transformerClassName,
- ...($this->getAdditionalDependencyInjectionParams()),
- );
- } else {
- try {
- $transformerInstance = DI::make($transformerClassName);
- } catch (Error|Exception) {
- throw new TransformerNotFoundException($transformerClassName);
- }
- }
-
- // Validate the transformer
- $isTransformer = $transformerInstance instanceof Transformer;
- if (!$isTransformer) {
- throw new InvalidTransformerClassException($transformerClassName);
- }
-
- // Create transformer container
- $transformerContainer = DI::make(TransformerContainer::class, [
- 'transformerInstance' => $transformerInstance,
- ]);
-
- // Create a reflection of the transformer
- $transformerRefClass = new BaseReflectionClass($transformerInstance);
-
- $filePath = $transformerRefClass->getFileName();
- $this->transformerContainers[$filePath] = $transformerContainer;
- }
-
- protected function getAdditionalDependencyInjectionParams(): array
- {
- return [];
- }
-
- // endregion
-
- /**
- * Get the transformers.
- *
- * @return class-string[]
- */
- public function getTransformers(): array
- {
- return $this->transformers;
- }
-
- /**
- * Get the transformer containers.
- *
- * @return array Key is the transformer file path
- */
- public function getTransformerContainers(): array
- {
- return $this->transformerContainers;
- }
-}
+
+ */
+ private array $transformers = [];
+
+ /**
+ * The list of transformer containers.
+ *
+ * @var array Key is the transformer file path
+ */
+ private array $transformerContainers = [];
+
+ /**
+ * @var null|Closure(class-string): Transformer
+ */
+ private ?Closure $dependencyInjectionHandler = null;
+
+ // region Pre-Initialization
+
+ /**
+ * Add transformers.
+ *
+ * @param array $transformers
+ *
+ * @return void
+ */
+ public function addTransformers(array $transformers): void
+ {
+ $this->transformers = array_merge($this->transformers, $transformers);
+ }
+
+ // endregion
+
+ // region Initialization
+
+ /**
+ * @param null|(Closure(class-string): Transformer) $dependencyInjectionHandler
+ */
+ public function registerCustomDependencyInjectionHandler(?Closure $dependencyInjectionHandler): void
+ {
+ $this->dependencyInjectionHandler = $dependencyInjectionHandler;
+ }
+
+ public function register(): void
+ {
+ $this->loadTransformers();
+ }
+
+ private function loadTransformers(): void
+ {
+ foreach (array_keys($this->transformers) as $transformerKey) {
+ /** @var mixed $transformer */
+ $transformer = $this->transformers[$transformerKey];
+ $this->loadTransformer($transformer);
+ }
+ }
+
+ /**
+ * @param mixed $transformerClassName
+ *
+ * @noinspection PhpUnhandledExceptionInspection
+ * @noinspection PhpDocMissingThrowsInspection
+ */
+ private function loadTransformer(mixed $transformerClassName): void
+ {
+ if (!is_string($transformerClassName)) {
+ throw new InvalidTransformerClassNameException();
+ }
+ if (!class_exists($transformerClassName)) {
+ throw new TransformerNotFoundException($transformerClassName);
+ }
+ if (!is_subclass_of($transformerClassName, Transformer::class)) {
+ throw new InvalidTransformerClassException($transformerClassName);
+ }
+
+ /** @var mixed $transformerInstance */
+ $transformerInstance = $this->instantiateTransformer($transformerClassName);
+
+ // Validate the transformer
+ $isTransformer = $transformerInstance instanceof Transformer;
+ if (!$isTransformer) {
+ throw new InvalidTransformerClassException($transformerClassName);
+ }
+
+ // Create transformer container
+ $transformerContainer = DI::make(TransformerContainer::class, [
+ 'transformerInstance' => $transformerInstance,
+ ]);
+
+ // Create a reflection of the transformer
+ $transformerRefClass = new BaseReflectionClass($transformerInstance);
+
+ $filePath = $transformerRefClass->getFileName();
+ if ($filePath === false) {
+ throw new LogicException('A transformer must have a source file.');
+ }
+ $this->transformerContainers[$filePath] = $transformerContainer;
+ }
+
+ /** @param class-string $class */
+ private function instantiateTransformer(string $class): mixed
+ {
+ if ($this->dependencyInjectionHandler !== null) {
+ return ($this->dependencyInjectionHandler)($class, ...$this->getAdditionalDependencyInjectionParams());
+ }
+
+ try {
+ return DI::make($class);
+ } catch (Throwable) {
+ throw new TransformerNotFoundException($class);
+ }
+ }
+
+ /** @return list */
+ protected function getAdditionalDependencyInjectionParams(): array
+ {
+ return [];
+ }
+
+ // endregion
+
+ /**
+ * Get the transformers.
+ *
+ * @return array
+ */
+ public function getTransformers(): array
+ {
+ return $this->transformers;
+ }
+
+ /**
+ * Get the transformer containers.
+ *
+ * @return array Key is the transformer file path
+ */
+ public function getTransformerContainers(): array
+ {
+ return $this->transformerContainers;
+ }
+}
diff --git a/src/Core/DI.php b/src/Core/DI.php
index 3c75b78..558d419 100644
--- a/src/Core/DI.php
+++ b/src/Core/DI.php
@@ -1,129 +1,142 @@
-ensureNotInitialized();
-
- $containerBuilder = $this->getContainerBuilder();
- $containerBuilder->useAttributes(true);
-
- /** @noinspection PhpUnhandledExceptionInspection */
- $this->container = $containerBuilder->build();
-
- $this->setInitialized();
- }
-
- /**
- * Get the dependency injection container builder.
- *
- * @return ContainerBuilder
- */
- public static function getContainerBuilder(): ContainerBuilder
- {
- $instance = static::getInstance();
- $instance->ensureNotInitialized();
-
- if (!isset($instance->containerBuilder)) {
- $instance->containerBuilder = new ContainerBuilder();
- }
-
- return $instance->containerBuilder;
- }
-
- /**
- * Get an (already initialized) instance of the given class.
- *
- * @template T
- *
- * @param class-string $class
- *
- * @return T
- *
- * @noinspection PhpDocMissingThrowsInspection
- */
- public static function get(string $class)
- {
- $instance = static::getInstance();
- $instance->ensureInitialized();
-
- /** @noinspection PhpUnhandledExceptionInspection */
- return $instance->container->get($class);
- }
-
- /**
- * Replace an existing instance of the given class.
- *
- * @param string $class
- * @param $value
- *
- * @return void
- *
- * @codeCoverageIgnore
- */
- public static function set(string $class, $value): void
- {
- $instance = static::getInstance();
- $instance->ensureInitialized();
-
- $instance->container->set($class, $value);
- }
-
- /**
- * Create an instance of the given class.
- *
- * This method behaves like a factory.
- *
- * @template T
- *
- * @param class-string $class
- * @param array $parameters
- *
- * @return T
- *
- * @noinspection PhpDocMissingThrowsInspection
- */
- public static function make(string $class, array $parameters = [])
- {
- $instance = static::getInstance();
- $instance->ensureInitialized();
-
- /** @noinspection PhpUnhandledExceptionInspection */
- return $instance->container->make($class, $parameters);
- }
-}
+ensureNotInitialized();
+
+ $containerBuilder = $this->getContainerBuilder();
+ $containerBuilder->useAttributes(true);
+
+ /** @noinspection PhpUnhandledExceptionInspection */
+ $this->container = $containerBuilder->build();
+
+ $this->setInitialized();
+ }
+
+ /**
+ * Get the dependency injection container builder.
+ *
+ * @return ContainerBuilder
+ */
+ public static function getContainerBuilder(): ContainerBuilder
+ {
+ $instance = static::getInstance();
+ $instance->ensureNotInitialized();
+
+ if (!isset($instance->containerBuilder)) {
+ $instance->containerBuilder = new ContainerBuilder();
+ }
+
+ return $instance->containerBuilder;
+ }
+
+ /**
+ * Get an (already initialized) instance of the given class.
+ *
+ * @template T of object
+ *
+ * @param class-string $class
+ *
+ * @return T
+ *
+ * @noinspection PhpDocMissingThrowsInspection
+ */
+ public static function get(string $class): mixed
+ {
+ $instance = static::getInstance();
+ $instance->ensureInitialized();
+
+ /** @noinspection PhpUnhandledExceptionInspection */
+ /** @var mixed $service */
+ $service = $instance->container->get($class);
+ if (!$service instanceof $class) {
+ throw new LogicException('The container must return the requested class.');
+ }
+
+ return $service;
+ }
+
+ /**
+ * Replace an existing instance of the given class.
+ *
+ * @param string $class
+ * @param mixed $value
+ *
+ * @return void
+ *
+ * @codeCoverageIgnore
+ */
+ public static function set(string $class, mixed $value): void
+ {
+ $instance = static::getInstance();
+ $instance->ensureInitialized();
+
+ $instance->container->set($class, $value);
+ }
+
+ /**
+ * Create an instance of the given class.
+ *
+ * This method behaves like a factory.
+ *
+ * @template T of object
+ *
+ * @param class-string $class
+ * @param array $parameters
+ *
+ * @return T
+ *
+ * @noinspection PhpDocMissingThrowsInspection
+ */
+ public static function make(string $class, array $parameters = []): mixed
+ {
+ $instance = static::getInstance();
+ $instance->ensureInitialized();
+
+ /** @noinspection PhpUnhandledExceptionInspection */
+ /** @var mixed $service */
+ $service = $instance->container->make($class, $parameters);
+ if (!$service instanceof $class) {
+ throw new LogicException('The container must return the requested class.');
+ }
+
+ return $service;
+ }
+}
diff --git a/src/Core/Exception/CodeTransformerException.php b/src/Core/Exception/CodeTransformerException.php
index f14cba3..f01fd21 100644
--- a/src/Core/Exception/CodeTransformerException.php
+++ b/src/Core/Exception/CodeTransformerException.php
@@ -1,14 +1,12 @@
-message\n\nFull code:\n```php\n$code\n```",
- previous: $previous,
- );
- }
-}
+message}
+
+ Full code:
+ ```php
+ {$code}
+ ```
+ MESSAGE;
+
+ parent::__construct(message: $message, previous: $previous);
+ }
+}
diff --git a/src/Core/Exception/Transformer/TransformerNotFoundException.php b/src/Core/Exception/Transformer/TransformerNotFoundException.php
index b8f90f6..e1400fd 100644
--- a/src/Core/Exception/Transformer/TransformerNotFoundException.php
+++ b/src/Core/Exception/Transformer/TransformerNotFoundException.php
@@ -1,25 +1,23 @@
-
- */
- private array $matchedTransformerContainers = [];
-
- /**
- * Check if the class should be transformed.
- *
- * @param class-string $namespacedClass
- * @param string $filePath
- *
- * @return bool
- */
- public function matchAndStore(string $namespacedClass, string $filePath): bool
- {
- // Get the transformers
- $transformerContainers = $this->transformerContainer->getTransformerContainers();
-
- // Match the transformers
- $matchedTransformerContainers = [];
- foreach ($transformerContainers as $transformerContainer) {
- $wildcardPatterns = (array)$transformerContainer->transformerInstance->getTargetClass();
-
- foreach ($wildcardPatterns as $wildcardPattern) {
- $regex = Regex::fromWildcard($wildcardPattern);
- if ($regex->matches($namespacedClass)) {
- // Check if the transformer has already been matched
- $alreadyMatched = array_reduce(
- $matchedTransformerContainers,
- function (bool $carry, TransformerContainer $container) use ($transformerContainer) {
- return $carry || $container === $transformerContainer;
- },
- false,
- );
-
- if ($alreadyMatched) {
- continue;
- }
-
- $matchedTransformerContainers[] = $transformerContainer;
- }
- }
- }
-
- // Cache the result
- $this->matchedTransformerContainers[$namespacedClass] = $matchedTransformerContainers;
-
- // Cache the result
- if (!$matchedTransformerContainers) {
- $this->cacheEmptyResult(
- $namespacedClass,
- $filePath,
- );
- }
-
- return (bool)$matchedTransformerContainers;
- }
-
- private function cacheEmptyResult(
- string $namespacedClass,
- string $filePath,
- ): void {
- $filePath = Path::resolve($filePath);
- $cacheState = DI::make(EmptyResultCacheState::class, [
- CacheState::DATA => [
- CacheState::ORIGINAL_FILE_PATH_KEY => $filePath,
- CacheState::NAMESPACED_CLASS_KEY => $namespacedClass,
- CacheState::MODIFICATION_TIME_KEY => filemtime($filePath),
- ],
- ]);
-
- // Set the cache state
- $this->cacheStateManager->setCacheState(
- $filePath,
- $cacheState,
- );
- }
-
- /**
- * Get the matched transformers for the given class.
- *
- * @param class-string $namespacedClass
- *
- * @return TransformerContainer[]
- */
- public function getMatchedTransformerContainers(string $namespacedClass): array
- {
- // Check if the query has been cached
- return $this->matchedTransformerContainers[$namespacedClass] ?? [];
- }
-}
+
+ */
+ private array $matchedTransformerContainers = [];
+
+ /**
+ * Check if the class should be transformed.
+ *
+ * @param class-string $namespacedClass
+ * @param string $filePath
+ *
+ * @return bool
+ */
+ public function matchAndStore(string $namespacedClass, string $filePath): bool
+ {
+ // Get the transformers
+ $transformerContainers = $this->transformerContainer->getTransformerContainers();
+
+ // Match the transformers
+ $matchedTransformerContainers = [];
+ foreach ($transformerContainers as $transformerContainer) {
+ $wildcardPatterns = (array) $transformerContainer->transformerInstance->getTargetClass();
+
+ foreach ($wildcardPatterns as $wildcardPattern) {
+ $regex = Regex::fromWildcard($wildcardPattern);
+ if ($regex->matches($namespacedClass)) {
+ // Check if the transformer has already been matched
+ $alreadyMatched = array_reduce(
+ $matchedTransformerContainers,
+ static fn(bool $carry, TransformerContainer $container) => (
+ $carry
+ || $container === $transformerContainer
+ ),
+ initial: false,
+ );
+
+ if ($alreadyMatched) {
+ continue;
+ }
+
+ $matchedTransformerContainers[] = $transformerContainer;
+ }
+ }
+ }
+
+ // Cache the result
+ $this->matchedTransformerContainers[$namespacedClass] = $matchedTransformerContainers;
+
+ // Cache the result
+ if (!$matchedTransformerContainers) {
+ $this->cacheEmptyResult($namespacedClass, $filePath);
+ }
+
+ return (bool) $matchedTransformerContainers;
+ }
+
+ private function cacheEmptyResult(string $namespacedClass, string $filePath): void
+ {
+ $filePath = Path::resolve($filePath);
+ if (!is_string($filePath)) {
+ throw new RuntimeException('Cannot resolve the source file path.');
+ }
+
+ $cacheState = DI::make(EmptyResultCacheState::class, [
+ CacheState::DATA => [
+ CacheState::ORIGINAL_FILE_PATH_KEY => $filePath,
+ CacheState::NAMESPACED_CLASS_KEY => $namespacedClass,
+ CacheState::MODIFICATION_TIME_KEY => filemtime($filePath),
+ ],
+ ]);
+
+ // Set the cache state
+ $this->cacheStateManager->setCacheState($filePath, $cacheState);
+ }
+
+ /**
+ * Get the matched transformers for the given class.
+ *
+ * @param class-string $namespacedClass
+ *
+ * @return TransformerContainer[]
+ */
+ public function getMatchedTransformerContainers(string $namespacedClass): array
+ {
+ // Check if the query has been cached
+ return $this->matchedTransformerContainers[$namespacedClass] ?? [];
+ }
+}
diff --git a/src/Core/Options.php b/src/Core/Options.php
index 36cc3b7..d6b038c 100644
--- a/src/Core/Options.php
+++ b/src/Core/Options.php
@@ -1,164 +1,176 @@
-getFileName();
- $rootDir = Path::resolve(Path::join($composerDir, '../../..'));
-
- $this->appDir = $rootDir;
- $this->cacheDir = $cacheDir ?? Path::join($rootDir, $this->defaultCacheDir);
- $this->cacheFileMode = $cacheFileMode ?? (0777 & ~umask());
- $this->debug = $debug;
- $this->environment = $environment;
- $this->excludePaths = $excludePaths;
- }
-
- // endregion
-
- // region Initialization
-
- /**
- * @inheritDoc
- */
- public function register(): void
- {
- // Nothing to do here.
- }
-
- // endregion
-
- /**
- * Get the application directory.
- */
- public function getAppDir(): string
- {
- return $this->appDir;
- }
-
- /**
- * Get the cache directory.
- */
- public function getCacheDir(): string
- {
- return $this->cacheDir;
- }
-
- /**
- * Get the exclude paths.
- */
- public function getExcludePaths(): array
- {
- return $this->excludePaths;
- }
-
- /**
- * Get the cache file mode.
- */
- public function getCacheFileMode(): int
- {
- return $this->cacheFileMode;
- }
-
- /**
- * Check if debug mode is enabled.
- */
- public function isDebug(): bool
- {
- return $this->debug;
- }
-
- /**
- * Get the environment in which the application is running.
- */
- public function getEnvironment(): Environment
- {
- return $this->environment;
- }
-}
+getFileName();
+ if ($composerDir === false) {
+ throw new LogicException('Composer must have a source file.');
+ }
+
+ $rootDir = Path::resolve(Path::join($composerDir, '../../..'));
+ if (!is_string($rootDir)) {
+ throw new RuntimeException('Cannot resolve the application directory.');
+ }
+
+ $this->appDir = $rootDir;
+ $this->cacheDir = $cacheDir ?? Path::join($rootDir, $this->defaultCacheDir);
+ $this->cacheFileMode = $cacheFileMode ?? 0o777 & ~umask();
+ $this->debug = $debug;
+ $this->environment = $environment;
+ $this->excludePaths = $excludePaths;
+ }
+
+ // endregion
+
+ // region Initialization
+
+ /**
+ * @inheritDoc
+ */
+ public function register(): void
+ {
+ // Nothing to do here.
+ }
+
+ // endregion
+
+ /**
+ * Get the application directory.
+ */
+ public function getAppDir(): string
+ {
+ return $this->appDir;
+ }
+
+ /**
+ * Get the cache directory.
+ */
+ public function getCacheDir(): string
+ {
+ return $this->cacheDir;
+ }
+
+ /**
+ * Get the exclude paths.
+ *
+ * @return string[]
+ */
+ public function getExcludePaths(): array
+ {
+ return $this->excludePaths;
+ }
+
+ /**
+ * Get the cache file mode.
+ */
+ public function getCacheFileMode(): int
+ {
+ return $this->cacheFileMode;
+ }
+
+ /**
+ * Check if debug mode is enabled.
+ */
+ public function isDebug(): bool
+ {
+ return $this->debug;
+ }
+
+ /**
+ * Get the environment in which the application is running.
+ */
+ public function getEnvironment(): Environment
+ {
+ return $this->environment;
+ }
+}
diff --git a/src/Core/Processor/TransformerProcessor.php b/src/Core/Processor/TransformerProcessor.php
index 68a2147..08d2933 100644
--- a/src/Core/Processor/TransformerProcessor.php
+++ b/src/Core/Processor/TransformerProcessor.php
@@ -1,142 +1,132 @@
-code->getNamespacedClass();
-
- // Process the transformers
- $transformerContainers = $this->transformerMatcher->getMatchedTransformerContainers($namespacedClass);
- $this->processTransformers($metadata, $transformerContainers);
-
- $originalFilePath = $metadata->uri;
- $transformedFilePath = $this->cachePaths->getTransformedCachePath($originalFilePath);
- $transformed = $metadata->code->hasChanges();
-
- // Save the transformed code
- if ($transformed) {
- Filesystem::writeFile(
- $transformedFilePath,
- $metadata->code->getNewSource(),
- );
- }
-
- // Update the cache state
- $modificationTime = $_SERVER['REQUEST_TIME'] ?? time();
- if ($transformed) {
- $transformerFilePaths = $this->getTransformerFilePaths($transformerContainers);
-
- $cacheState = DI::make(TransformedCacheState::class, [
- CacheState::DATA => [
- CacheState::ORIGINAL_FILE_PATH_KEY => $originalFilePath,
- CacheState::NAMESPACED_CLASS_KEY => $namespacedClass,
- CacheState::MODIFICATION_TIME_KEY => $modificationTime,
- TransformedCacheState::TRANSFORMED_FILE_PATH_KEY => $transformedFilePath,
- TransformedCacheState::TRANSFORMER_FILE_PATHS_KEY => $transformerFilePaths,
- ],
- ]);
- } else {
- $cacheState = DI::make(NoTransformationsCacheState::class, [
- CacheState::DATA => [
- CacheState::ORIGINAL_FILE_PATH_KEY => $originalFilePath,
- CacheState::NAMESPACED_CLASS_KEY => $namespacedClass,
- CacheState::MODIFICATION_TIME_KEY => $modificationTime,
- ],
- ]);
- }
-
- $this->cacheStateManager->setCacheState($originalFilePath, $cacheState);
- }
-
- /**
- * Process the transformers.
- *
- * @param Metadata $metadata
- * @param TransformerContainer[] $transformerContainers
- *
- * @return void
- */
- protected function processTransformers(
- Metadata $metadata,
- array $transformerContainers,
- ): void {
- // Sort the transformers by priority
- usort(
- $transformerContainers,
- function (TransformerContainer $a, TransformerContainer $b) {
- return $a->transformerInstance->order <=> $b->transformerInstance->order;
- },
- );
-
- foreach ($transformerContainers as $transformerContainer) {
- $transformerContainer->transformerInstance->transform(
- $metadata->code,
- );
- }
- }
-
- /**
- * Get the file paths of the given transformers.
- *
- * @param TransformerContainer[] $transformerContainers
- *
- * @return string[]
- *
- * @noinspection PhpDocMissingThrowsInspection Handled by TransformerNotFoundException
- */
- protected function getTransformerFilePaths(
- array $transformerContainers,
- ): array {
- return array_map(
- function (TransformerContainer $transformerContainer) {
- /** @noinspection PhpUnhandledExceptionInspection Handled by TransformerNotFoundException */
- $reflection = new BaseReflectionClass(
- $transformerContainer->transformerInstance
- );
- return $reflection->getFileName();
- },
- $transformerContainers,
- );
- }
-}
+code->getNamespacedClass();
+
+ // Process the transformers
+ $transformerContainers = $this->transformerMatcher->getMatchedTransformerContainers($namespacedClass);
+ $this->processTransformers($metadata, $transformerContainers);
+
+ $originalFilePath = $metadata->uri;
+ $transformedFilePath = $this->cachePaths->getTransformedCachePath($originalFilePath);
+ $transformed = $metadata->code->hasChanges();
+
+ // Save the transformed code
+ if ($transformed) {
+ Filesystem::writeFile($transformedFilePath, $metadata->code->getNewSource());
+ }
+
+ // Update the cache state
+ $modificationTime = $_SERVER['REQUEST_TIME'] ?? time();
+ $cacheStateClass = NoTransformationsCacheState::class;
+ $data = [
+ CacheState::ORIGINAL_FILE_PATH_KEY => $originalFilePath,
+ CacheState::NAMESPACED_CLASS_KEY => $namespacedClass,
+ CacheState::MODIFICATION_TIME_KEY => $modificationTime,
+ ];
+ if ($transformed) {
+ $cacheStateClass = TransformedCacheState::class;
+ $data[TransformedCacheState::TRANSFORMED_FILE_PATH_KEY] = $transformedFilePath;
+ $data[TransformedCacheState::TRANSFORMER_FILE_PATHS_KEY] =
+ $this->getTransformerFilePaths($transformerContainers);
+ }
+
+ $cacheState = DI::make($cacheStateClass, [CacheState::DATA => $data]);
+
+ $this->cacheStateManager->setCacheState($originalFilePath, $cacheState);
+ }
+
+ /**
+ * Process the transformers.
+ *
+ * @param Metadata $metadata
+ * @param TransformerContainer[] $transformerContainers
+ *
+ * @return void
+ */
+ protected function processTransformers(Metadata $metadata, array $transformerContainers): void
+ {
+ // Sort the transformers by priority
+ usort(
+ $transformerContainers,
+ static fn(TransformerContainer $a, TransformerContainer $b) => (
+ $a->transformerInstance->order <=> $b->transformerInstance->order
+ ),
+ );
+
+ foreach ($transformerContainers as $transformerContainer) {
+ $transformerContainer->transformerInstance->transform($metadata->code);
+ }
+ }
+
+ /**
+ * Get the file paths of the given transformers.
+ *
+ * @param TransformerContainer[] $transformerContainers
+ *
+ * @return string[]
+ *
+ * @noinspection PhpDocMissingThrowsInspection Handled by TransformerNotFoundException
+ */
+ protected function getTransformerFilePaths(array $transformerContainers): array
+ {
+ return array_map(
+ static function (TransformerContainer $transformerContainer) {
+ /** @noinspection PhpUnhandledExceptionInspection Handled by TransformerNotFoundException */
+ $reflection = new BaseReflectionClass($transformerContainer->transformerInstance);
+ $file = $reflection->getFileName();
+ if ($file === false) {
+ throw new LogicException('A transformer must have a source file.');
+ }
+
+ return $file;
+ },
+ $transformerContainers,
+ );
+ }
+}
diff --git a/src/Core/ServiceInterface.php b/src/Core/ServiceInterface.php
index 1d7634a..ab74025 100644
--- a/src/Core/ServiceInterface.php
+++ b/src/Core/ServiceInterface.php
@@ -1,18 +1,18 @@
-data .= $bucket->data;
- }
-
- // If the stream is closed, transform the code
- if ($closing || feof($this->stream)) {
- $consumed = strlen($this->data);
-
- // Store the metadata
- $metadata = DI::make(Metadata::class, [
- 'stream' => $this->stream,
- 'originalSource' => $this->data,
- ]);
-
- // Transform the code
- $transformerProcessor = DI::get(TransformerProcessor::class);
- $transformerProcessor->transform($metadata);
-
- // Set the new source code
- $source = $metadata->code->getNewSource();
-
- $bucket = stream_bucket_new($this->stream, $source);
- stream_bucket_append($out, $bucket);
-
- // Pass the (transformed) source code to the next filter
- return PSFS_PASS_ON;
- }
-
- // No data has been consumed
- return PSFS_FEED_ME;
- }
-}
+stream;
+ if (!is_resource($stream)) {
+ throw new InvalidStreamException();
+ }
+
+ // Read the stream until EOF
+ while (true) {
+ $bucket = stream_bucket_make_writeable($in);
+ if ($bucket === null) {
+ break;
+ }
+ $this->data .= $bucket->data;
+ }
+
+ // If the stream is closed, transform the code
+ if ($closing || feof($stream)) {
+ $consumed = strlen($this->data);
+
+ // Store the metadata
+ $metadata = DI::make(Metadata::class, [
+ 'stream' => $this->stream,
+ 'originalSource' => $this->data,
+ ]);
+
+ // Transform the code
+ $transformerProcessor = DI::get(TransformerProcessor::class);
+ $transformerProcessor->transform($metadata);
+
+ // Set the new source code
+ $source = $metadata->code->getNewSource();
+
+ $bucket = stream_bucket_new($stream, $source);
+ stream_bucket_append($out, $bucket);
+
+ // Pass the (transformed) source code to the next filter
+ return PSFS_PASS_ON;
+ }
+
+ // No data has been consumed
+ return PSFS_FEED_ME;
+ }
+}
diff --git a/src/Core/StreamFilter/FilterInjector.php b/src/Core/StreamFilter/FilterInjector.php
index ced4df1..329f2fa 100644
--- a/src/Core/StreamFilter/FilterInjector.php
+++ b/src/Core/StreamFilter/FilterInjector.php
@@ -1,55 +1,45 @@
-
- * @see https://www.php.net/manual/wrappers.php.php#wrappers.php.filter PHP Stream Filter
- */
-class FilterInjector
-{
- /**
- * Allows the application to inject filters into the PHP code.
- *
- * @see StreamFilter::filter()
- */
- public const PHP_FILTER_READ = 'php://filter/read=';
-
- /**
- * Rewrite the PHP code to inject the filter.
- *
- * @param string $filePath
- *
- * @return string
- */
- public function rewrite(string $filePath): string
- {
- // Create a filter for the given file
- return sprintf(
- "%s%s/resource=%s",
- static::PHP_FILTER_READ,
- StreamFilter::FILTER_ID,
- $filePath
- );
- }
-
- public function rewriteCached(string $filePath): string
- {
- return sprintf(
- "%s%s/resource=%s",
- static::PHP_FILTER_READ,
- CachedStreamFilter::CACHED_FILTER_ID,
- $filePath,
- );
- }
-}
+
+ * @see https://www.php.net/manual/wrappers.php.php#wrappers.php.filter PHP Stream Filter
+ */
+class FilterInjector
+{
+ /**
+ * Allows the application to inject filters into the PHP code.
+ *
+ * @see StreamFilter::filter()
+ */
+ public const PHP_FILTER_READ = 'php://filter/read=';
+
+ /**
+ * Rewrite the PHP code to inject the filter.
+ *
+ * @param string $filePath
+ *
+ * @return string
+ */
+ public function rewrite(string $filePath): string
+ {
+ // Create a filter for the given file
+ return sprintf('%s%s/resource=%s', static::PHP_FILTER_READ, StreamFilter::FILTER_ID, $filePath);
+ }
+
+ public function rewriteCached(string $filePath): string
+ {
+ return sprintf('%s%s/resource=%s', static::PHP_FILTER_READ, CachedStreamFilter::CACHED_FILTER_ID, $filePath);
+ }
+}
diff --git a/src/Core/StreamFilter/Metadata.php b/src/Core/StreamFilter/Metadata.php
index 5eac847..d112bf2 100644
--- a/src/Core/StreamFilter/Metadata.php
+++ b/src/Core/StreamFilter/Metadata.php
@@ -1,85 +1,100 @@
-timed_out = $metadata['timed_out'];
- $this->blocked = $metadata['blocked'];
- $this->eof = $metadata['eof'];
- $this->unread_bytes = $metadata['unread_bytes'];
- $this->stream_type = $metadata['stream_type'];
- $this->wrapper_type = $metadata['wrapper_type'];
- $this->wrapper_data = $metadata['wrapper_data'] ?? null;
- $this->mode = $metadata['mode'];
- $this->seekable = $metadata['seekable'];
- $this->uri = $metadata['uri'];
- $this->crypto = $metadata['crypto'] ?? null;
- $this->mediatype = $metadata['mediatype'] ?? null;
-
- $classContainer = DI::get(ClassContainer::class);
-
- $this->code = DI::make(Code::class, [
- 'source' => $originalSource,
- 'namespacedClass' => $classContainer->getNamespacedClassByPath($this->uri),
- ]);
- }
-}
+|null */
+ public ?array $crypto;
+ public ?string $mediatype;
+
+ /**
+ * Metadata constructor.
+ *
+ * @param mixed $stream
+ * @param string $originalSource
+ */
+ public function __construct(mixed $stream, string $originalSource)
+ {
+ if (!is_resource($stream)) {
+ // @codeCoverageIgnoreStart
+ throw new InvalidStreamException();
+
+ // @codeCoverageIgnoreEnd
+ }
+
+ // Create metadata from stream
+ /** @var array{timed_out: bool, blocked: bool, eof: bool, unread_bytes: int, stream_type: string, wrapper_type?: string, wrapper_data?: mixed, mode: string, seekable: bool, uri?: string, crypto?: array, mediatype?: string} $metadata */
+ $metadata = stream_get_meta_data($stream);
+ if (!isset($metadata['uri'])) {
+ throw new InvalidStreamException();
+ }
+
+ $matches = [];
+ if (preg_match('/resource=(.+)$/', $metadata['uri'], $matches)) {
+ // Resolve the '/resource=...' uri to a path
+ $uri = Path::resolve($matches[1]);
+ if (!is_string($uri)) {
+ throw new InvalidStreamException();
+ }
+
+ $metadata['uri'] = $uri;
+ }
+
+ $this->timed_out = $metadata['timed_out'];
+ $this->blocked = $metadata['blocked'];
+ $this->eof = $metadata['eof'];
+ $this->unread_bytes = $metadata['unread_bytes'];
+ $this->stream_type = $metadata['stream_type'];
+ $this->wrapper_type = $metadata['wrapper_type'] ?? '';
+ $this->wrapper_data = $metadata['wrapper_data'] ?? null;
+ $this->mode = $metadata['mode'];
+ $this->seekable = $metadata['seekable'];
+ $this->uri = $metadata['uri'];
+ $this->crypto = $metadata['crypto'] ?? null;
+ $this->mediatype = $metadata['mediatype'] ?? null;
+
+ $classContainer = DI::get(ClassContainer::class);
+
+ $this->code = DI::make(Code::class, [
+ 'source' => $originalSource,
+ 'namespacedClass' => $classContainer->getNamespacedClassByPath($this->uri),
+ ]);
+ }
+}
diff --git a/src/Core/Util/CodeChecker.php b/src/Core/Util/CodeChecker.php
index 3849a28..f48b70d 100644
--- a/src/Core/Util/CodeChecker.php
+++ b/src/Core/Util/CodeChecker.php
@@ -1,40 +1,42 @@
-parseSourceFile($code);
- $errors = DiagnosticsProvider::getDiagnostics($sourceFileNode);
-
- if (count($errors) > 0) {
- $errors = array_reverse($errors);
-
- // Chain errors
- $error = null;
- foreach ($errors as $e) {
- $error = new SyntaxError($e, $code, $error);
- }
-
- throw $error;
- }
- }
-}
+parseSourceFile($code);
+ $errors = DiagnosticsProvider::getDiagnostics($sourceFileNode);
+
+ if (count($errors) > 0) {
+ $errors = array_reverse($errors);
+
+ // Chain errors
+ $error = null;
+ foreach ($errors as $e) {
+ $error = new SyntaxError($e, $code, $error);
+ }
+
+ if ($error !== null) {
+ throw $error;
+ }
+ }
+ }
+}
diff --git a/src/Core/Util/ReflectionHelper.php b/src/Core/Util/ReflectionHelper.php
index 76d1c86..a0ce881 100644
--- a/src/Core/Util/ReflectionHelper.php
+++ b/src/Core/Util/ReflectionHelper.php
@@ -1,52 +1,53 @@
-classLoader = $classLoader;
- }
-
- /**
- * Get reflection class.
- *
- * @param class-string $namespacedClass
- *
- * @return ReflectionClass
- */
- public function getReflectionClass(string $namespacedClass): ReflectionClass
- {
- $astLocator = (new BetterReflection())->astLocator();
- $reflector = new DefaultReflector(new AggregateSourceLocator([
- new ComposerSourceLocator($this->classLoader, $astLocator),
- new PhpInternalSourceLocator($astLocator, new ReflectionSourceStubber()),
- ]));
-
- return $reflector->reflectClass($namespacedClass);
- }
-}
+classLoader = $classLoader;
+ }
+
+ /**
+ * Get reflection class.
+ *
+ * @param class-string $namespacedClass
+ *
+ * @return ReflectionClass
+ */
+ public function getReflectionClass(string $namespacedClass): ReflectionClass
+ {
+ $astLocator = (new BetterReflection())->astLocator();
+ $reflector = new DefaultReflector(new AggregateSourceLocator([
+ new ComposerSourceLocator($this->classLoader, $astLocator),
+ new PhpInternalSourceLocator($astLocator, new ReflectionSourceStubber()),
+ ]));
+
+ return $reflector->reflectClass($namespacedClass);
+ }
+}
diff --git a/src/Core/Util/StringMutator.php b/src/Core/Util/StringMutator.php
index 70cbf31..e3909b7 100644
--- a/src/Core/Util/StringMutator.php
+++ b/src/Core/Util/StringMutator.php
@@ -1,76 +1,81 @@
-string = $string;
- }
-
- /**
- * Add an edit to the string.
- *
- * @param int $start
- * @param int $length
- * @param string $replacement
- *
- * @return $this
- */
- public function edit(int $start, int $length, string $replacement): self
- {
- $this->edits[] = [$start, $length, $replacement];
- return $this;
- }
-
- /**
- * Get the mutated string.
- *
- * @return string
- */
- public function getMutatedString(): string
- {
- // Sort the edits by start position.
- usort($this->edits, function ($a, $b) {
- return $a[0] <=> $b[0];
- });
-
- // Apply the edits.
- $result = $this->string;
- $offset = 0;
- foreach ($this->edits as $edit) {
- [$start, $length, $replacement] = $edit;
- $start += $offset;
- $result = substr_replace($result, $replacement, $start, $length);
- $offset += strlen($replacement) - $length;
- }
- return $result;
- }
-}
+ Start position, length, replacement
+ */
+ public array $edits = [];
+
+ /**
+ * StringMutator constructor.
+ *
+ * @param string $string
+ */
+ public function __construct(string $string)
+ {
+ $this->string = $string;
+ }
+
+ /**
+ * Add an edit to the string.
+ *
+ * @param int $start
+ * @param int $length
+ * @param string $replacement
+ *
+ * @return $this
+ */
+ public function edit(int $start, int $length, string $replacement): self
+ {
+ if ($length < 0) {
+ throw new InvalidArgumentException('Edit length must not be negative.');
+ }
+
+ $this->edits[] = [$start, $length, $replacement];
+
+ return $this;
+ }
+
+ /**
+ * Get the mutated string.
+ *
+ * @return string
+ */
+ public function getMutatedString(): string
+ {
+ // Sort the edits by start position.
+ usort($this->edits, static fn($a, $b) => $a[0] <=> $b[0]);
+
+ // Apply the edits.
+ $result = $this->string;
+ $offset = 0;
+ foreach ($this->edits as $edit) {
+ [$start, $length, $replacement] = $edit;
+ $start += $offset;
+ $result = substr_replace($result, $replacement, $start, $length);
+ $offset += strlen($replacement) - $length;
+ }
+ return $result;
+ }
+}
diff --git a/src/Transformer.php b/src/Transformer.php
index 9e783d9..1ccd779 100644
--- a/src/Transformer.php
+++ b/src/Transformer.php
@@ -1,42 +1,42 @@
-stringMutator = DI::make(StringMutator::class, [
- 'string' => $this->source,
- ]);
- }
-
- // region Mutators
-
- /**
- * Add an edit to the source code.
- *
- * @param Token|Node $token The token or node to edit.
- * @param string $replacement The replacement string.
- *
- * @return void
- *
- * @noinspection PhpDocMissingThrowsInspection
- */
- public function edit(Token|Node $token, string $replacement): void
- {
- /** @noinspection PhpUnhandledExceptionInspection */
- $this->stringMutator->edit(
- $token->getStartPosition(),
- $token->getWidth(),
- $replacement,
- );
- }
-
- /**
- * Add an edit to the source code at a specific position.
- *
- * @param int $startPosition
- * @param int $width
- * @param string $replacement
- *
- * @return void
- */
- public function editAt(
- int $startPosition,
- int $width,
- string $replacement,
- ): void {
- $this->stringMutator->edit(
- $startPosition,
- $width,
- $replacement,
- );
- }
-
- /**
- * Add a string to the end of the source code.
- *
- * @param string $string
- *
- * @return void
- */
- public function append(string $string): void
- {
- $this->appendList[] = $string;
- }
-
- // endregion
-
- // region Getters
-
- /**
- * Get the original source code.
- *
- * @return string
- */
- public function getOriginalSource(): string
- {
- return $this->source;
- }
-
- /**
- * Get source file node.
- *
- * @return SourceFileNode
- */
- public function getSourceFileNode(): SourceFileNode
- {
- if (!isset($this->sourceFileNode)) {
- $this->sourceFileNode = (new Parser)->parseSourceFile($this->source);
- }
-
- return $this->sourceFileNode;
- }
-
- /**
- * Get the reflection class.
- *
- * @return BetterReflectionClass
- */
- public function getReflectionClass(): BetterReflectionClass
- {
- return $this->reflectionHelper->getReflectionClass(
- $this->getNamespacedClass(),
- );
- }
-
- /**
- * Get the new source code with all edits and appends applied.
- *
- * @return string
- */
- public function getNewSource(): string
- {
- // If there are no edits or appends, return the original source
- if (!$this->hasChanges()) {
- // @codeCoverageIgnoreStart
- // This is actually being run, but it's not being counted for some reason
- return $this->source;
- // @codeCoverageIgnoreEnd
- }
-
- // Apply edits
- $newSource = $this->stringMutator->getMutatedString();
-
- // Append strings
- foreach ($this->appendList as $append) {
- $newSource .= $append;
- }
-
- // Check the new source code for syntax errors
- DI::get(CodeChecker::class)->isValidPhpCode($newSource);
-
- return $newSource;
- }
-
- // endregion
-
- /**
- * Whether the source code has any edits or appends.
- *
- * @return bool
- */
- public function hasChanges(): bool
- {
- return count($this->stringMutator->edits) > 0
- || count($this->appendList) > 0;
- }
-
- /**
- * Get the namespaced class name.
- *
- * @return class-string
- */
- public function getNamespacedClass(): string
- {
- return $this->namespacedClass;
- }
-
- /**
- * Get the class name.
- *
- * @return string
- */
- public function getClassName(): string
- {
- return substr(
- $this->namespacedClass,
- strrpos($this->namespacedClass, '\\') + 1,
- );
- }
-}
+
+ */
+ private array $appendList = [];
+
+ /**
+ * The source file node.
+ *
+ * @var SourceFileNode
+ */
+ private SourceFileNode $sourceFileNode;
+
+ /**
+ * Code constructor.
+ *
+ * @param string $source The source code.
+ * @param class-string $namespacedClass The namespaced class name.
+ */
+ public function __construct(
+ private readonly string $source,
+ private readonly string $namespacedClass,
+ ) {
+ // Create the string mutator
+ $this->stringMutator = DI::make(StringMutator::class, [
+ 'string' => $this->source,
+ ]);
+ }
+
+ // region Mutators
+
+ /**
+ * Add an edit to the source code.
+ *
+ * @param Token|Node $token The token or node to edit.
+ * @param string $replacement The replacement string.
+ *
+ * @return void
+ *
+ * @noinspection PhpDocMissingThrowsInspection
+ */
+ public function edit(Token|Node $token, string $replacement): void
+ {
+ /** @noinspection PhpUnhandledExceptionInspection */
+ $this->stringMutator->edit($token->getStartPosition(), $token->getWidth(), $replacement);
+ }
+
+ /**
+ * Add an edit to the source code at a specific position.
+ *
+ * @param int $startPosition
+ * @param int $width
+ * @param string $replacement
+ *
+ * @return void
+ */
+ public function editAt(int $startPosition, int $width, string $replacement): void
+ {
+ $this->stringMutator->edit($startPosition, $width, $replacement);
+ }
+
+ /**
+ * Add a string to the end of the source code.
+ *
+ * @param string $string
+ *
+ * @return void
+ */
+ public function append(string $string): void
+ {
+ $this->appendList[] = $string;
+ }
+
+ // endregion
+
+ // region Getters
+
+ /**
+ * Get the original source code.
+ *
+ * @return string
+ */
+ public function getOriginalSource(): string
+ {
+ return $this->source;
+ }
+
+ /**
+ * Get source file node.
+ *
+ * @return SourceFileNode
+ */
+ public function getSourceFileNode(): SourceFileNode
+ {
+ if (!isset($this->sourceFileNode)) {
+ $this->sourceFileNode = (new Parser())->parseSourceFile($this->source);
+ }
+
+ return $this->sourceFileNode;
+ }
+
+ /**
+ * Get the reflection class.
+ *
+ * @return BetterReflectionClass
+ */
+ public function getReflectionClass(): BetterReflectionClass
+ {
+ return $this->reflectionHelper->getReflectionClass($this->getNamespacedClass());
+ }
+
+ /**
+ * Get the new source code with all edits and appends applied.
+ *
+ * @return string
+ */
+ public function getNewSource(): string
+ {
+ // If there are no edits or appends, return the original source
+ if (!$this->hasChanges()) {
+ // @codeCoverageIgnoreStart
+ // This is actually being run, but it's not being counted for some reason
+ return $this->source;
+
+ // @codeCoverageIgnoreEnd
+ }
+
+ // Apply edits
+ $newSource = $this->stringMutator->getMutatedString();
+
+ // Append strings
+ foreach ($this->appendList as $append) {
+ $newSource .= $append;
+ }
+
+ // Check the new source code for syntax errors
+ DI::get(CodeChecker::class)->isValidPhpCode($newSource);
+
+ return $newSource;
+ }
+
+ // endregion
+
+ /**
+ * Whether the source code has any edits or appends.
+ *
+ * @return bool
+ */
+ public function hasChanges(): bool
+ {
+ return count($this->stringMutator->edits) > 0 || count($this->appendList) > 0;
+ }
+
+ /**
+ * Get the namespaced class name.
+ *
+ * @return class-string
+ */
+ public function getNamespacedClass(): string
+ {
+ return $this->namespacedClass;
+ }
+
+ /**
+ * Get the class name.
+ *
+ * @return string
+ */
+ public function getClassName(): string
+ {
+ $separator = strrpos($this->namespacedClass, '\\');
+ return $separator === false ? $this->namespacedClass : substr($this->namespacedClass, $separator + 1);
+ }
+}
diff --git a/src/functions.php b/src/functions.php
index b7d18ae..fb22277 100644
--- a/src/functions.php
+++ b/src/functions.php
@@ -1,41 +1,38 @@
-classLoader)) {
- $this->findClassLoader();
- }
-
- return $this->classLoader->findFile($class);
- }
-
- private function findOriginalClassMock(string $class): string
- {
- if (!isset($this->classLoader)) {
- $this->findClassLoader();
- }
-
- $original = new ReflectionProperty(ClassLoader::class, 'originalClassLoader');
- $original = $original->getValue($this->classLoader);
- return $original->findFile($class);
- }
-
- private function findClassLoader(): void
- {
- foreach (spl_autoload_functions() as $function) {
- if (is_array($function) && $function[0] instanceof ClassLoader) {
- $this->classLoader = $function[0];
- break;
- }
- }
- }
-
- public function assertWillBeTransformed(string $className): void
- {
- $originalFilePath = Path::resolve($this->findOriginalClassMock($className));
-
- $transformPath =
- FilterInjector::PHP_FILTER_READ .
- StreamFilter::FILTER_ID . '/resource=' .
- $originalFilePath;
-
- $filePathMock = $this->findClassMock($className);
-
- Assert::assertEquals(
- $transformPath,
- $filePathMock,
- "$className will not be transformed",
- );
- }
-
- public function assertTransformerLoadedFromCache(string $className): void
- {
- $filePath = Path::resolve($this->findOriginalClassMock($className));
-
- $cachePath =
- FilterInjector::PHP_FILTER_READ .
- CachedStreamFilter::CACHED_FILTER_ID . '/resource=' .
- $filePath;
-
- $filePathMock = $this->findClassMock($className);
-
- Assert::assertEquals(
- $cachePath,
- $filePathMock,
- $className . ' will not be loaded from cache',
- );
- }
-
- public function assertTransformerNotApplied(string $className): void
- {
- $originalFilePath = Path::resolve($this->findOriginalClassMock($className));
- $filePathMock = $this->findClassMock($className);
-
- Assert::assertEquals(
- $originalFilePath,
- $filePathMock,
- $className . ' will be transformed',
- );
- }
-}
+classLoader)) {
+ $this->findClassLoader();
+ }
+
+ Assert::assertInstanceOf(ClassLoader::class, $this->classLoader);
+ $file = $this->classLoader->findFile($class);
+ Assert::assertIsString($file);
+ return $file;
+ }
+
+ private function findOriginalClassMock(string $class): string
+ {
+ if (!isset($this->classLoader)) {
+ $this->findClassLoader();
+ }
+
+ $original = new ReflectionProperty(ClassLoader::class, 'originalClassLoader');
+ Assert::assertInstanceOf(ClassLoader::class, $this->classLoader);
+ /** @var mixed $loader */
+ $loader = $original->getValue($this->classLoader);
+ Assert::assertInstanceOf(\Composer\Autoload\ClassLoader::class, $loader);
+ $file = $loader->findFile($class);
+ Assert::assertIsString($file);
+ return $file;
+ }
+
+ private function findClassLoader(): void
+ {
+ foreach (spl_autoload_functions() as $function) {
+ if (!(is_array($function) && $function[0] instanceof ClassLoader)) {
+ continue;
+ }
+
+ $this->classLoader = $function[0];
+ break;
+ }
+ }
+
+ public function assertWillBeTransformed(string $className): void
+ {
+ $originalFilePath = Path::resolve($this->findOriginalClassMock($className));
+ Assert::assertIsString($originalFilePath);
+
+ $transformPath = FilterInjector::PHP_FILTER_READ . StreamFilter::FILTER_ID . '/resource=' . $originalFilePath;
+
+ $filePathMock = $this->findClassMock($className);
+
+ Assert::assertEquals($transformPath, $filePathMock, "{$className} will not be transformed");
+ }
+
+ public function assertTransformerLoadedFromCache(string $className): void
+ {
+ $filePath = Path::resolve($this->findOriginalClassMock($className));
+ Assert::assertIsString($filePath);
+
+ $cachePath = FilterInjector::PHP_FILTER_READ . CachedStreamFilter::CACHED_FILTER_ID . '/resource=' . $filePath;
+
+ $filePathMock = $this->findClassMock($className);
+
+ Assert::assertEquals($cachePath, $filePathMock, $className . ' will not be loaded from cache');
+ }
+
+ public function assertTransformerNotApplied(string $className): void
+ {
+ $originalFilePath = Path::resolve($this->findOriginalClassMock($className));
+ Assert::assertIsString($originalFilePath);
+ $filePathMock = $this->findClassMock($className);
+
+ Assert::assertEquals($originalFilePath, $filePathMock, $className . ' will be transformed');
+ }
+}
diff --git a/tests/Functional/Cache/CachedFileAndDestructor/CachedFileAndDestructorTest.php b/tests/Functional/Cache/CachedFileAndDestructor/CachedFileAndDestructorTest.php
index 9aa2d69..c5c0598 100644
--- a/tests/Functional/Cache/CachedFileAndDestructor/CachedFileAndDestructorTest.php
+++ b/tests/Functional/Cache/CachedFileAndDestructor/CachedFileAndDestructorTest.php
@@ -1,95 +1,82 @@
-assertWillBeTransformed($class);
-
- $stringClass = new $class();
- $this->assertSame(
- 'Hello from Code Transformer!',
- $stringClass->test(),
- );
-
- $file = Util::getFilePath(StringClass::class);
- $content = Filesystem::readFile($file);
-
- $this->assertEquals(
- $content,
- StringTransformer::$originalSourceCode,
- );
- }
-
- public function testCachedReplaceStringClass(): void
- {
- Kernel::init();
-
- $class = StringClass::class;
- $this->assertTransformerLoadedFromCache($class);
-
- $stringClass = new $class();
- $this->assertSame(
- 'Hello from Code Transformer!',
- $stringClass->test(),
- );
- }
-
- public function testCachedFile(): void
- {
- $cachedFilePath = Util::getTransformedFilePath(StringClass::class);
-
- $this->assertFileExists($cachedFilePath);
- $file = Filesystem::readFile($cachedFilePath);
-
- $this->assertStringContainsString(
- 'Hello from Code Transformer!',
- $file,
- );
-
- $this->assertStringContainsString(
- '$iAmAppended = true;',
- $file,
- );
- }
-
- public function testDestructor(): void
- {
- Util::clearCache();
- Kernel::init();
-
- $class = StringClass::class;
- $stringClass = new $class();
-
- $cacheStateManager = DI::get(CacheStateManager::class);
-
- $this->assertFileDoesNotExist(Util::CACHE_STATES_FILE);
- $cacheStateManager->__destruct();
- $this->assertFileExists(Util::CACHE_STATES_FILE);
-
- $file = require Util::CACHE_STATES_FILE;
-
- $key = 'CODE_TRANSFORMER_APP_DIR\tests\Functional\Cache\CachedFileAndDestructor\Target\StringClass.php';
- $key = str_replace('\\', DIRECTORY_SEPARATOR, $key);
- $this->assertArrayHasKey($key, $file);
- }
-}
+assertWillBeTransformed($class);
+
+ $stringClass = new StringClass();
+ static::assertSame('Hello from Code Transformer!', $stringClass->test());
+
+ $file = Util::getFilePath(StringClass::class);
+ $content = Filesystem::readFile($file);
+
+ static::assertEquals($content, StringTransformer::$originalSourceCode);
+ }
+
+ public function testCachedReplaceStringClass(): void
+ {
+ Kernel::init();
+
+ $class = StringClass::class;
+ $this->assertTransformerLoadedFromCache($class);
+
+ $stringClass = new StringClass();
+ static::assertSame('Hello from Code Transformer!', $stringClass->test());
+ }
+
+ public function testCachedFile(): void
+ {
+ $cachedFilePath = Util::getTransformedFilePath(StringClass::class);
+
+ static::assertFileExists($cachedFilePath);
+ $file = Filesystem::readFile($cachedFilePath);
+
+ static::assertStringContainsString('Hello from Code Transformer!', $file);
+
+ static::assertStringContainsString('$iAmAppended = true;', $file);
+ }
+
+ public function testDestructor(): void
+ {
+ Util::clearCache();
+ Kernel::init();
+
+ $class = StringClass::class;
+ $stringClass = new StringClass();
+
+ $cacheStateManager = DI::get(CacheStateManager::class);
+
+ static::assertFileDoesNotExist(Util::CACHE_STATES_FILE);
+ $cacheStateManager->__destruct();
+ static::assertFileExists(Util::CACHE_STATES_FILE);
+
+ /** @var mixed $file */
+ $file = require Util::CACHE_STATES_FILE;
+ static::assertIsArray($file);
+
+ $key = 'CODE_TRANSFORMER_APP_DIR\tests\Functional\Cache\CachedFileAndDestructor\Target\StringClass.php';
+ $key = str_replace('\\', DIRECTORY_SEPARATOR, $key);
+ static::assertArrayHasKey($key, $file);
+ }
+}
diff --git a/tests/Functional/Cache/CachedFileAndDestructor/Target/StringClass.php b/tests/Functional/Cache/CachedFileAndDestructor/Target/StringClass.php
index 1ba0c29..c22ce6c 100644
--- a/tests/Functional/Cache/CachedFileAndDestructor/Target/StringClass.php
+++ b/tests/Functional/Cache/CachedFileAndDestructor/Target/StringClass.php
@@ -1,11 +1,11 @@
-getSourceFileNode();
-
- foreach ($sourceFileNode->getDescendantNodes() as $node) {
- // Find 'Hello World!' string
- if ($node instanceof StringLiteral
- && $node->getStringContentsText() === 'Hello World!'
- ) {
- // Replace it with 'Hello from Code Transformer!'
- $code->edit(
- $node->children,
- "'Hello from Code Transformer!'",
- );
-
-
-
- $code->append('$iAmAppended = true;');
- }
- }
-
- self::$originalSourceCode = $code->getOriginalSource();
- }
-}
+getSourceFileNode();
+
+ /** @var iterable<\Microsoft\PhpParser\Node> $nodes */
+ $nodes = $sourceFileNode->getDescendantNodes();
+ foreach ($nodes as $node) {
+ // Find 'Hello World!' string
+ if (!($node instanceof StringLiteral && $node->getStringContentsText() === 'Hello World!')) {
+ continue;
+ }
+
+ // Replace it with 'Hello from Code Transformer!'
+ $code->edit($node, "'Hello from Code Transformer!'");
+
+ $code->append('$iAmAppended = true;');
+ }
+
+ self::$originalSourceCode = $code->getOriginalSource();
+ }
+}
diff --git a/tests/Functional/Cache/DeleteCacheFile/DeleteCacheFileTest.php b/tests/Functional/Cache/DeleteCacheFile/DeleteCacheFileTest.php
index a9625e2..9e7a5c5 100644
--- a/tests/Functional/Cache/DeleteCacheFile/DeleteCacheFileTest.php
+++ b/tests/Functional/Cache/DeleteCacheFile/DeleteCacheFileTest.php
@@ -1,49 +1,46 @@
-assertWillBeTransformed($class);
-
- $deleteCacheFileClass = new $class();
- $this->assertSame(
- 'Hello World!',
- $deleteCacheFileClass->test(),
- );
- }
-
- public function testCachedDeleteCacheFileClass(): void
- {
- Kernel::init();
-
- $cachedFilePath = Util::getTransformedFilePath(Target::class);
-
- $this->assertFileExists($cachedFilePath);
- Filesystem::rm($cachedFilePath);
- $this->assertFileDoesNotExist($cachedFilePath);
-
- $class = Target::class;
- $this->assertWillBeTransformed($class);
-
- $deleteCacheFileClass = new $class();
- $this->assertSame('Hello World!', $deleteCacheFileClass->test());
-
- $this->assertFileExists($cachedFilePath);
- }
-}
+assertWillBeTransformed($class);
+
+ $deleteCacheFileClass = new Target();
+ static::assertSame('Hello World!', $deleteCacheFileClass->test());
+ }
+
+ public function testCachedDeleteCacheFileClass(): void
+ {
+ Kernel::init();
+
+ $cachedFilePath = Util::getTransformedFilePath(Target::class);
+
+ static::assertFileExists($cachedFilePath);
+ Filesystem::rm($cachedFilePath);
+ static::assertFileDoesNotExist($cachedFilePath);
+
+ $class = Target::class;
+ $this->assertWillBeTransformed($class);
+
+ $deleteCacheFileClass = new Target();
+ static::assertSame('Hello World!', $deleteCacheFileClass->test());
+
+ static::assertFileExists($cachedFilePath);
+ }
+}
diff --git a/tests/Functional/Cache/DeleteCacheFile/Target.php b/tests/Functional/Cache/DeleteCacheFile/Target.php
index 7982d82..963a75e 100644
--- a/tests/Functional/Cache/DeleteCacheFile/Target.php
+++ b/tests/Functional/Cache/DeleteCacheFile/Target.php
@@ -1,11 +1,11 @@
-append('// Hello from Code Transformer!');
- }
-}
+append('// Hello from Code Transformer!');
+ }
+}
diff --git a/tests/Functional/Kernel/AddedTransformer/AddedTransformerTest.php b/tests/Functional/Kernel/AddedTransformer/AddedTransformerTest.php
index 60312f6..34c5ff6 100644
--- a/tests/Functional/Kernel/AddedTransformer/AddedTransformerTest.php
+++ b/tests/Functional/Kernel/AddedTransformer/AddedTransformerTest.php
@@ -1,46 +1,40 @@
-assertWillBeTransformed($class);
-
- $addedTransformerClass = new $class();
-
- $this->assertSame(
- 'Hello Code Transformer!',
- $addedTransformerClass->test(),
- );
- }
-
- public function testCachedAddedTransformer(): void
- {
- AddedTransformerKernel::init();
-
- $class = Target::class;
- $this->assertWillBeTransformed($class);
-
- $addedTransformerClass = new $class();
- $this->assertSame(
- 'Hello from Code Transformer!',
- $addedTransformerClass->test(),
- );
- }
-}
+assertWillBeTransformed($class);
+
+ $addedTransformerClass = new Target();
+
+ static::assertSame('Hello Code Transformer!', $addedTransformerClass->test());
+ }
+
+ public function testCachedAddedTransformer(): void
+ {
+ AddedTransformerKernel::init();
+
+ $class = Target::class;
+ $this->assertWillBeTransformed($class);
+
+ $addedTransformerClass = new Target();
+ static::assertSame('Hello from Code Transformer!', $addedTransformerClass->test());
+ }
+}
diff --git a/tests/Functional/Kernel/AddedTransformer/Kernel/AddedTransformerKernel.php b/tests/Functional/Kernel/AddedTransformer/Kernel/AddedTransformerKernel.php
index 60eedb1..f86bad7 100644
--- a/tests/Functional/Kernel/AddedTransformer/Kernel/AddedTransformerKernel.php
+++ b/tests/Functional/Kernel/AddedTransformer/Kernel/AddedTransformerKernel.php
@@ -1,17 +1,18 @@
-transformerManager->addTransformers($this->addedTransformers);
- }
-}
+ */
+ protected array $addedTransformers = [
+ AddedTransformer2::class,
+ ];
+
+ protected function configureOptions(): void
+ {
+ $this->transformerManager->addTransformers($this->addedTransformers);
+ }
+}
diff --git a/tests/Functional/Kernel/AddedTransformer/Target.php b/tests/Functional/Kernel/AddedTransformer/Target.php
index 6e09ce7..ec9406d 100644
--- a/tests/Functional/Kernel/AddedTransformer/Target.php
+++ b/tests/Functional/Kernel/AddedTransformer/Target.php
@@ -1,14 +1,14 @@
-getSourceFileNode();
-
- foreach ($sourceFileNode->getDescendantNodes() as $node) {
- if ($node instanceof ExpressionStatement) {
- assert($node->expression instanceof AssignmentExpression);
- $leftOperand = $node->expression->leftOperand;
- assert($leftOperand instanceof Variable);
- $leftOperandValue = $leftOperand->getText();
- $rightOperand = $node->expression->rightOperand;
- assert($rightOperand instanceof StringLiteral);
-
- if ($leftOperandValue === '$world') {
- $code->editAt(
- $rightOperand->getStartPosition() + 1,
- $rightOperand->getWidth() - 2,
- 'Code Transformer'
- );
- }
- }
- }
- }
-}
+getSourceFileNode();
+
+ /** @var iterable<\Microsoft\PhpParser\Node> $nodes */
+ $nodes = $sourceFileNode->getDescendantNodes();
+ foreach ($nodes as $node) {
+ if (!$node instanceof ExpressionStatement) {
+ continue;
+ }
+
+ $expression = $node->expression;
+ Assert::assertInstanceOf(
+ AssignmentExpression::class,
+ $expression,
+ 'The parser node must match this fixture.',
+ );
+ $leftOperand = $expression->leftOperand;
+ Assert::assertInstanceOf(Variable::class, $leftOperand, 'The parser node must match this fixture.');
+ $leftOperandValue = $leftOperand->getText();
+ $rightOperand = $expression->rightOperand;
+ Assert::assertInstanceOf(StringLiteral::class, $rightOperand, 'The parser node must match this fixture.');
+
+ if ($leftOperandValue === '$world') {
+ $code->editAt($rightOperand->getStartPosition() + 1, $rightOperand->getWidth() - 2, 'Code Transformer');
+ }
+ }
+ }
+}
diff --git a/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer2.php b/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer2.php
index 3aaad9c..265657a 100644
--- a/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer2.php
+++ b/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer2.php
@@ -1,43 +1,49 @@
-getSourceFileNode();
-
- foreach ($sourceFileNode->getDescendantNodes() as $node) {
- if ($node instanceof ExpressionStatement) {
- assert($node->expression instanceof AssignmentExpression);
- $leftOperand = $node->expression->leftOperand;
- assert($leftOperand instanceof Variable);
- $leftOperandValue = $leftOperand->getText();
- $rightOperand = $node->expression->rightOperand;
- assert($rightOperand instanceof StringLiteral);
-
- if ($leftOperandValue === '$hello') {
- $code->editAt(
- $rightOperand->getStartPosition() + 1,
- $rightOperand->getWidth() - 2,
- 'Hello from'
- );
- }
- }
- }
- }
-}
+getSourceFileNode();
+
+ /** @var iterable<\Microsoft\PhpParser\Node> $nodes */
+ $nodes = $sourceFileNode->getDescendantNodes();
+ foreach ($nodes as $node) {
+ if (!$node instanceof ExpressionStatement) {
+ continue;
+ }
+
+ $expression = $node->expression;
+ Assert::assertInstanceOf(
+ AssignmentExpression::class,
+ $expression,
+ 'The parser node must match this fixture.',
+ );
+ $leftOperand = $expression->leftOperand;
+ Assert::assertInstanceOf(Variable::class, $leftOperand, 'The parser node must match this fixture.');
+ $leftOperandValue = $leftOperand->getText();
+ $rightOperand = $expression->rightOperand;
+ Assert::assertInstanceOf(StringLiteral::class, $rightOperand, 'The parser node must match this fixture.');
+
+ if ($leftOperandValue === '$hello') {
+ $code->editAt($rightOperand->getStartPosition() + 1, $rightOperand->getWidth() - 2, 'Hello from');
+ }
+ }
+ }
+}
diff --git a/tests/Functional/Kernel/AlreadyInitializedKernel/AlreadyInitializedKernelTest.php b/tests/Functional/Kernel/AlreadyInitializedKernel/AlreadyInitializedKernelTest.php
index 175d16d..c7eae71 100644
--- a/tests/Functional/Kernel/AlreadyInitializedKernel/AlreadyInitializedKernelTest.php
+++ b/tests/Functional/Kernel/AlreadyInitializedKernel/AlreadyInitializedKernelTest.php
@@ -18,7 +18,7 @@ public function testInitializedKernelTwice(): void
EmptyKernel::init();
EmptyKernel::init();
- $this->assertTrue(true);
+ static::assertTrue(true);
}
public function testInitializeKernelTwiceWithExceptionOnDoubleInitializationOption(): void
diff --git a/tests/Functional/Kernel/AlreadyInitializedKernel/Kernel.php b/tests/Functional/Kernel/AlreadyInitializedKernel/Kernel.php
index f5ef477..ecf47f4 100644
--- a/tests/Functional/Kernel/AlreadyInitializedKernel/Kernel.php
+++ b/tests/Functional/Kernel/AlreadyInitializedKernel/Kernel.php
@@ -1,4 +1,5 @@
assertStringContainsString(
- 'Generating transformer instance: ' . StringTransformer::class,
- $output,
- );
+ static::assertStringContainsString('Generating transformer instance: ' . StringTransformer::class, $output);
$class = new StringClass();
- $this->assertSame(
- 'Hello from Code Transformer!',
- $class->test(),
- );
+ static::assertSame('Hello from Code Transformer!', $class->test());
}
}
diff --git a/tests/Functional/Kernel/CustomDependencyInjectionHandler/Kernel.php b/tests/Functional/Kernel/CustomDependencyInjectionHandler/Kernel.php
index d55e433..253bc7f 100644
--- a/tests/Functional/Kernel/CustomDependencyInjectionHandler/Kernel.php
+++ b/tests/Functional/Kernel/CustomDependencyInjectionHandler/Kernel.php
@@ -13,10 +13,11 @@ class Kernel extends CodeTransformerKernel
protected function dependencyInjectionHandler(): ?Closure
{
- return function (string $transformerClass) {
+ /** @param class-string<\Okapi\CodeTransformer\Transformer> $transformerClass */
+ return static function (string $transformerClass): \Okapi\CodeTransformer\Transformer {
echo 'Generating transformer instance: ' . $transformerClass . PHP_EOL;
- return new $transformerClass();
+ return new StringTransformer();
};
}
diff --git a/tests/Functional/Kernel/DirectKernel/DirectKernelTest.php b/tests/Functional/Kernel/DirectKernel/DirectKernelTest.php
index 6dbae03..e88db85 100644
--- a/tests/Functional/Kernel/DirectKernel/DirectKernelTest.php
+++ b/tests/Functional/Kernel/DirectKernel/DirectKernelTest.php
@@ -1,17 +1,17 @@
-expectException(DirectKernelInitializationException::class);
-
- CodeTransformerKernel::init();
- }
-}
+expectException(DirectKernelInitializationException::class);
+
+ CodeTransformerKernel::init();
+ }
+}
diff --git a/tests/Functional/Kernel/Environment/EnvironmentTest.php b/tests/Functional/Kernel/Environment/EnvironmentTest.php
index 9efc04c..eca9058 100644
--- a/tests/Functional/Kernel/Environment/EnvironmentTest.php
+++ b/tests/Functional/Kernel/Environment/EnvironmentTest.php
@@ -29,12 +29,9 @@ public function testDevelopmentEnvironment(): void
$class = HelloWorld::class;
$this->assertWillBeTransformed($class);
- $helloWorldClass = new $class();
+ $helloWorldClass = new HelloWorld();
- $this->assertSame(
- 'Hello from Code Transformer!',
- $helloWorldClass->say(),
- );
+ static::assertSame('Hello from Code Transformer!', $helloWorldClass->say());
}
/**
@@ -47,12 +44,9 @@ public function testCachedDevelopmentEnvironment(): void
$class = HelloWorld::class;
$this->assertTransformerLoadedFromCache($class);
- $helloWorldClass = new $class();
+ $helloWorldClass = new HelloWorld();
- $this->assertSame(
- 'Hello from Code Transformer!',
- $helloWorldClass->say(),
- );
+ static::assertSame('Hello from Code Transformer!', $helloWorldClass->say());
}
/**
@@ -61,14 +55,10 @@ public function testCachedDevelopmentEnvironment(): void
public function testChangedDevelopmentEnvironment(): void
{
// Change class
- $classFilePath = Util::getFilePath(HelloWorld::class);
+ $classFilePath = Util::getFilePath(HelloWorld::class);
$originalClassFileContent = Filesystem::readFile($classFilePath);
- $changedFileContent = str_replace(
- 'Hello World!',
- 'Hello Changed World!',
- $originalClassFileContent,
- );
+ $changedFileContent = str_replace('Hello World!', 'Hello Changed World!', $originalClassFileContent);
sleep(1);
Filesystem::writeFile($classFilePath, $changedFileContent);
@@ -80,11 +70,8 @@ public function testChangedDevelopmentEnvironment(): void
$class = HelloWorld::class;
$this->assertWillBeTransformed($class);
- $classInstance = new $class();
- $this->assertSame(
- 'Hello Changed World from Code Transformer!',
- $classInstance->say(),
- );
+ $classInstance = new HelloWorld();
+ static::assertSame('Hello Changed World from Code Transformer!', $classInstance->say());
} catch (Throwable $e) {
$exception = $e;
}
@@ -109,12 +96,9 @@ public function testProductionEnvironment(): void
$class = HelloWorld::class;
$this->assertWillBeTransformed($class);
- $helloWorldClass = new $class();
+ $helloWorldClass = new HelloWorld();
- $this->assertSame(
- 'Hello from Code Transformer!',
- $helloWorldClass->say(),
- );
+ static::assertSame('Hello from Code Transformer!', $helloWorldClass->say());
}
/**
@@ -127,12 +111,9 @@ public function testCachedProductionEnvironment(): void
$class = HelloWorld::class;
$this->assertTransformerLoadedFromCache($class);
- $helloWorldClass = new $class();
+ $helloWorldClass = new HelloWorld();
- $this->assertSame(
- 'Hello from Code Transformer!',
- $helloWorldClass->say(),
- );
+ static::assertSame('Hello from Code Transformer!', $helloWorldClass->say());
}
/**
@@ -141,14 +122,10 @@ public function testCachedProductionEnvironment(): void
public function testChangedProductionEnvironment(): void
{
// Change class
- $classFilePath = Util::getFilePath(HelloWorld::class);
+ $classFilePath = Util::getFilePath(HelloWorld::class);
$originalClassFileContent = Filesystem::readFile($classFilePath);
- $changedFileContent = str_replace(
- 'Hello World!',
- 'Hello Changed World!',
- $originalClassFileContent,
- );
+ $changedFileContent = str_replace('Hello World!', 'Hello Changed World!', $originalClassFileContent);
sleep(1);
Filesystem::writeFile($classFilePath, $changedFileContent);
@@ -160,11 +137,8 @@ public function testChangedProductionEnvironment(): void
$class = HelloWorld::class;
$this->assertTransformerLoadedFromCache($class);
- $classInstance = new $class();
- $this->assertSame(
- 'Hello from Code Transformer!',
- $classInstance->say(),
- );
+ $classInstance = new HelloWorld();
+ static::assertSame('Hello from Code Transformer!', $classInstance->say());
} catch (Throwable $e) {
$exception = $e;
}
diff --git a/tests/Functional/Kernel/Environment/Transformer/StringTransformer.php b/tests/Functional/Kernel/Environment/Transformer/StringTransformer.php
index 82e9bfc..f7d11eb 100644
--- a/tests/Functional/Kernel/Environment/Transformer/StringTransformer.php
+++ b/tests/Functional/Kernel/Environment/Transformer/StringTransformer.php
@@ -18,22 +18,22 @@ public function transform(Code $code): void
{
$sourceFileNode = $code->getSourceFileNode();
- foreach ($sourceFileNode->getDescendantNodes() as $node) {
+ /** @var iterable<\Microsoft\PhpParser\Node> $nodes */
+ $nodes = $sourceFileNode->getDescendantNodes();
+ foreach ($nodes as $node) {
// Find 'Hello World!' string
- if ($node instanceof StringLiteral) {
- if ($node->getStringContentsText() === 'Hello World!') {
- // Replace it with 'Hello from Code Transformer!'
- $code->edit(
- $node->children,
- "'Hello from Code Transformer!'",
- );
- } else if ($node->getStringContentsText() === 'Hello Changed World!') {
- // Replace it with 'Hello Changed World from Code Transformer!'
- $code->edit(
- $node->children,
- "'Hello Changed World from Code Transformer!'",
- );
- }
+ if (!$node instanceof StringLiteral) {
+ continue;
+ }
+
+ if ($node->getStringContentsText() === 'Hello World!') {
+ // Replace it with 'Hello from Code Transformer!'
+ $code->edit($node, "'Hello from Code Transformer!'");
+ continue;
+ }
+ if ($node->getStringContentsText() === 'Hello Changed World!') {
+ // Replace it with 'Hello Changed World from Code Transformer!'
+ $code->edit($node, "'Hello Changed World from Code Transformer!'");
}
}
}
diff --git a/tests/Functional/Kernel/KernelTest.php b/tests/Functional/Kernel/KernelTest.php
index 1b0e152..e3017dc 100644
--- a/tests/Functional/Kernel/KernelTest.php
+++ b/tests/Functional/Kernel/KernelTest.php
@@ -1,32 +1,32 @@
-assertFalse(EmptyKernel::isInitialized());
- EmptyKernel::init();
- $this->assertTrue(EmptyKernel::isInitialized());
-
- $this->assertFileDoesNotExist(Util::CACHE_STATES_FILE);
- }
-
- public function testCachedKernel(): void
- {
- $this->assertFalse(EmptyKernel::isInitialized());
- EmptyKernel::init();
- $this->assertTrue(EmptyKernel::isInitialized());
-
- $this->assertFileExists(Util::CACHE_STATES_FILE);
- }
-}
+assertWillBeTransformed($class);
-
- $changedClass = new $class();
- $this->assertSame(
- 'Hello World from Code Transformer!',
- $changedClass->test(),
- );
- }
-
- public function testCachedChangedClass(): void
- {
- // Change class
- $classFilePath = Util::getFilePath(Target::class);
- $originalClassFileContent = Filesystem::readFile($classFilePath);
-
- $changedFileContent = str_replace(
- 'Hello World!',
- 'Hello Changed World!',
- $originalClassFileContent,
- );
-
- sleep(1);
- Filesystem::writeFile($classFilePath, $changedFileContent);
-
- $exception = null;
- try {
- Kernel::init();
-
- $class = Target::class;
- $this->assertWillBeTransformed($class);
-
- $classInstance = new $class();
- $this->assertSame(
- 'Hello Changed World from Code Transformer!',
- $classInstance->test(),
- );
- } catch (Throwable $e) {
- $exception = $e;
- }
-
- // Restore class
- Filesystem::writeFile($classFilePath, $originalClassFileContent);
-
- if ($exception !== null) {
- /** @noinspection PhpUnhandledExceptionInspection */
- throw $exception;
- }
- }
-}
+assertWillBeTransformed($class);
+
+ $changedClass = new Target();
+ static::assertSame('Hello World from Code Transformer!', $changedClass->test());
+ }
+
+ public function testCachedChangedClass(): void
+ {
+ // Change class
+ $classFilePath = Util::getFilePath(Target::class);
+ $originalClassFileContent = Filesystem::readFile($classFilePath);
+
+ $changedFileContent = str_replace('Hello World!', 'Hello Changed World!', $originalClassFileContent);
+
+ sleep(1);
+ Filesystem::writeFile($classFilePath, $changedFileContent);
+
+ $exception = null;
+ try {
+ Kernel::init();
+
+ $class = Target::class;
+ $this->assertWillBeTransformed($class);
+
+ $classInstance = new Target();
+ static::assertSame('Hello Changed World from Code Transformer!', $classInstance->test());
+ } catch (Throwable $e) {
+ $exception = $e;
+ }
+
+ // Restore class
+ Filesystem::writeFile($classFilePath, $originalClassFileContent);
+
+ if ($exception !== null) {
+ /** @noinspection PhpUnhandledExceptionInspection */
+ throw $exception;
+ }
+ }
+}
diff --git a/tests/Functional/Target/ChangedClass/Target.php b/tests/Functional/Target/ChangedClass/Target.php
index 1050574..d32dc3e 100755
--- a/tests/Functional/Target/ChangedClass/Target.php
+++ b/tests/Functional/Target/ChangedClass/Target.php
@@ -1,11 +1,11 @@
-getSourceFileNode();
-
- foreach ($sourceFileNode->getDescendantNodes() as $node) {
- // Find 'Hello World!' string
- if ($node instanceof StringLiteral) {
- if ($node->getStringContentsText() === 'Hello World!') {
- // Replace it with 'Hello World from Code Transformer!'
- $code->edit(
- $node->children,
- "'Hello World from Code Transformer!'",
- );
- } else if ($node->getStringContentsText() === 'Hello Changed World!') {
- // Replace it with 'Hello Changed World from Code Transformer!'
- $code->edit(
- $node->children,
- "'Hello Changed World from Code Transformer!'",
- );
- }
- }
- }
- }
-}
+getSourceFileNode();
+
+ /** @var iterable<\Microsoft\PhpParser\Node> $nodes */
+ $nodes = $sourceFileNode->getDescendantNodes();
+ foreach ($nodes as $node) {
+ // Find 'Hello World!' string
+ if (!$node instanceof StringLiteral) {
+ continue;
+ }
+
+ if ($node->getStringContentsText() === 'Hello World!') {
+ // Replace it with 'Hello World from Code Transformer!'
+ $code->edit($node, "'Hello World from Code Transformer!'");
+ continue;
+ }
+ if ($node->getStringContentsText() === 'Hello Changed World!') {
+ // Replace it with 'Hello Changed World from Code Transformer!'
+ $code->edit($node, "'Hello Changed World from Code Transformer!'");
+ }
+ }
+ }
+}
diff --git a/tests/Functional/Target/NoChanges/NoChangesTest.php b/tests/Functional/Target/NoChanges/NoChangesTest.php
index a1487b0..6716320 100644
--- a/tests/Functional/Target/NoChanges/NoChangesTest.php
+++ b/tests/Functional/Target/NoChanges/NoChangesTest.php
@@ -1,40 +1,40 @@
-assertWillBeTransformed($class);
-
- new $class();
- }
-
- public function testCachedNoChangesClass(): void
- {
- Kernel::init();
-
- $class = Target::class;
- $this->assertTransformerNotApplied($class);
-
- new $class();
-
- $originalFilePath = Util::getFilePath(Target::class);
- $cachedFilePath = Util::getTransformedFilePath(Target::class);
- $this->assertFileExists($originalFilePath);
- $this->assertFileDoesNotExist($cachedFilePath);
- }
-}
+assertWillBeTransformed($class);
+
+ new Target();
+ }
+
+ public function testCachedNoChangesClass(): void
+ {
+ Kernel::init();
+
+ $class = Target::class;
+ $this->assertTransformerNotApplied($class);
+
+ new Target();
+
+ $originalFilePath = Util::getFilePath(Target::class);
+ $cachedFilePath = Util::getTransformedFilePath(Target::class);
+ static::assertFileExists($originalFilePath);
+ static::assertFileDoesNotExist($cachedFilePath);
+ }
+}
diff --git a/tests/Functional/Target/NoChanges/Target.php b/tests/Functional/Target/NoChanges/Target.php
index adf09f0..d726927 100644
--- a/tests/Functional/Target/NoChanges/Target.php
+++ b/tests/Functional/Target/NoChanges/Target.php
@@ -1,7 +1,5 @@
-expectException(TransformerNotFoundException::class);
-
- TransformerDoesNotExistKernel::init();
- }
-
- /**
- * @see InvalidTransformerTypeKernel
- */
- public function testInvalidTransformerType(): void
- {
- Util::clearCache();
-
- $this->expectException(InvalidTransformerClassNameException::class);
-
- InvalidTransformerTypeKernel::init();
- }
-
- /**
- * @see TransformerDoesNotExtendTransformerKernel
- */
- public function testTransformerDoesNotExtendTransformer(): void
- {
- Util::clearCache();
-
- $this->expectException(InvalidTransformerClassException::class);
-
- TransformerDoesNotExtendTransformerKernel::init();
- }
-}
+expectException(TransformerNotFoundException::class);
+
+ TransformerDoesNotExistKernel::init();
+ }
+
+ /**
+ * @see InvalidTransformerTypeKernel
+ */
+ public function testInvalidTransformerType(): void
+ {
+ Util::clearCache();
+
+ $this->expectException(InvalidTransformerClassNameException::class);
+
+ InvalidTransformerTypeKernel::init();
+ }
+
+ /**
+ * @see TransformerDoesNotExtendTransformerKernel
+ */
+ public function testTransformerDoesNotExtendTransformer(): void
+ {
+ Util::clearCache();
+
+ $this->expectException(InvalidTransformerClassException::class);
+
+ TransformerDoesNotExtendTransformerKernel::init();
+ }
+}
diff --git a/tests/Functional/Transformer/InvalidTransformerClass/Kernel/TransformerDoesNotExistKernel.php b/tests/Functional/Transformer/InvalidTransformerClass/Kernel/TransformerDoesNotExistKernel.php
index 8073489..df02c6c 100644
--- a/tests/Functional/Transformer/InvalidTransformerClass/Kernel/TransformerDoesNotExistKernel.php
+++ b/tests/Functional/Transformer/InvalidTransformerClass/Kernel/TransformerDoesNotExistKernel.php
@@ -1,15 +1,15 @@
-assertWillBeTransformed($class);
-
- $multipleTransformersClass = new $class();
-
- $this->assertSame(
- 'Hello from Code Transformer!',
- $multipleTransformersClass->test(),
- );
-
- $this->assertSame(
- "You can't get me!",
- $multipleTransformersClass->privateProperty,
- );
- }
-
- public function testCachedMultipleTransformers(): void
- {
- Kernel::init();
-
- $class = TargetClass::class;
- $this->assertTransformerLoadedFromCache($class);
-
- $multipleTransformersClass = new $class();
-
- $this->assertSame(
- 'Hello from Code Transformer!',
- $multipleTransformersClass->test(),
- );
-
- $this->assertSame(
- "You can't get me!",
- $multipleTransformersClass->privateProperty,
- );
- }
-}
+assertWillBeTransformed($class);
+
+ $multipleTransformersClass = new TargetClass();
+
+ $this->assertTransformedMembers($multipleTransformersClass);
+ }
+
+ public function testCachedMultipleTransformers(): void
+ {
+ Kernel::init();
+
+ $class = TargetClass::class;
+ $this->assertTransformerLoadedFromCache($class);
+
+ $multipleTransformersClass = new TargetClass();
+
+ $this->assertTransformedMembers($multipleTransformersClass);
+ }
+
+ private function assertTransformedMembers(TargetClass $target): void
+ {
+ $method = new ReflectionMethod($target, 'test');
+ $property = new ReflectionProperty($target, 'privateProperty');
+
+ static::assertTrue($method->isPublic());
+ static::assertTrue($property->isPublic());
+ static::assertSame('Hello from Code Transformer!', $method->invoke($target));
+ static::assertSame("You can't get me!", $property->getValue($target));
+ static::assertSame(['Hello from Code Transformer!', "You can't get me!"], $target->snapshot());
+ }
+}
diff --git a/tests/Functional/Transformer/MultipleTransformer/TargetClass.php b/tests/Functional/Transformer/MultipleTransformer/TargetClass.php
index 4cb8be8..d8e3356 100644
--- a/tests/Functional/Transformer/MultipleTransformer/TargetClass.php
+++ b/tests/Functional/Transformer/MultipleTransformer/TargetClass.php
@@ -1,13 +1,20 @@
-test(), $this->privateProperty];
+ }
+
+ private function test(): string
+ {
+ return 'Hello World!';
+ }
+}
diff --git a/tests/Functional/Transformer/MultipleTransformer/Transformer/UnPrivateTransformer.php b/tests/Functional/Transformer/MultipleTransformer/Transformer/UnPrivateTransformer.php
index a90d539..b63119f 100644
--- a/tests/Functional/Transformer/MultipleTransformer/Transformer/UnPrivateTransformer.php
+++ b/tests/Functional/Transformer/MultipleTransformer/Transformer/UnPrivateTransformer.php
@@ -1,27 +1,31 @@
-getSourceFileNode();
-
- foreach ($sourceFileNode->getDescendantTokens() as $token) {
- if ($token->kind === TokenKind::PrivateKeyword) {
- $code->edit($token, 'public');
- }
- }
- }
-}
+getSourceFileNode();
+
+ /** @var iterable<\Microsoft\PhpParser\Token> $tokens */
+ $tokens = $sourceFileNode->getDescendantTokens();
+ foreach ($tokens as $token) {
+ if ($token->kind !== TokenKind::PrivateKeyword) {
+ continue;
+ }
+
+ $code->edit($token, 'public');
+ }
+ }
+}
diff --git a/tests/Functional/Transformer/SyntaxErrorInTransformedClass/SyntaxErrorInTransformedClassTest.php b/tests/Functional/Transformer/SyntaxErrorInTransformedClass/SyntaxErrorInTransformedClassTest.php
index 861042e..201de8f 100644
--- a/tests/Functional/Transformer/SyntaxErrorInTransformedClass/SyntaxErrorInTransformedClassTest.php
+++ b/tests/Functional/Transformer/SyntaxErrorInTransformedClass/SyntaxErrorInTransformedClassTest.php
@@ -1,26 +1,26 @@
-expectException(SyntaxError::class);
-
- /** @noinspection PhpUnusedLocalVariableInspection */
- $syntaxErrorClass = new Target();
- }
-}
+expectException(SyntaxError::class);
+
+ /** @noinspection PhpUnusedLocalVariableInspection */
+ $syntaxErrorClass = new Target();
+ }
+}
diff --git a/tests/Functional/Transformer/SyntaxErrorInTransformedClass/Target.php b/tests/Functional/Transformer/SyntaxErrorInTransformedClass/Target.php
index 74cb482..34356d3 100644
--- a/tests/Functional/Transformer/SyntaxErrorInTransformedClass/Target.php
+++ b/tests/Functional/Transformer/SyntaxErrorInTransformedClass/Target.php
@@ -1,7 +1,5 @@
-append('}');
-
- $refClass = $code->getReflectionClass();
- assert($refClass->getName() === Target::class);
-
- $className = $code->getNewSource();
- assert($className === 'SyntaxErrorClass');
- }
-}
+append('}');
+
+ $refClass = $code->getReflectionClass();
+ Assert::assertSame(Target::class, $refClass->getName(), 'The reflected member must match this fixture.');
+
+ $className = $code->getNewSource();
+ Assert::assertSame('SyntaxErrorClass', $className, 'The reflected member must match this fixture.');
+ }
+}
diff --git a/tests/Unit/CacheStateTest.php b/tests/Unit/CacheStateTest.php
new file mode 100644
index 0000000..543ce75
--- /dev/null
+++ b/tests/Unit/CacheStateTest.php
@@ -0,0 +1,59 @@
+ __FILE__,
+ CacheState::NAMESPACED_CLASS_KEY => self::class,
+ CacheState::MODIFICATION_TIME_KEY => time(),
+ TransformedCacheState::TRANSFORMED_FILE_PATH_KEY => __FILE__,
+ TransformedCacheState::TRANSFORMER_FILE_PATHS_KEY => [__FILE__],
+ ];
+ $state = new TransformedCacheState($data);
+ $serialized = $state->toArray();
+ static::assertSame(['type' => 'TransformedCacheState', ...$data], $serialized);
+
+ unset($serialized[CacheState::TYPE]);
+ $restored = (new TransformedCacheState())->createIfValid($serialized);
+ static::assertInstanceOf(TransformedCacheState::class, $restored);
+ static::assertSame($state->toArray(), $restored->toArray());
+ static::assertTrue($restored->isFresh());
+ static::assertSame(__FILE__, $restored->getFilePath());
+ }
+
+ #[RunInSeparateProcess]
+ public function testFactorySkipsInvalidEntriesAndRestoresValidState(): void
+ {
+ DI::getInstance()->register();
+ $valid = [
+ CacheState::TYPE => 'NoTransformationsCacheState',
+ CacheState::ORIGINAL_FILE_PATH_KEY => __FILE__,
+ CacheState::NAMESPACED_CLASS_KEY => self::class,
+ CacheState::MODIFICATION_TIME_KEY => time(),
+ ];
+ $states = (new CacheStateFactory())->createCacheStates([
+ null,
+ 'invalid',
+ [],
+ [CacheState::TYPE => []],
+ [CacheState::TYPE => 'UnknownCacheState'],
+ [CacheState::TYPE => 'TransformedCacheState'],
+ $valid,
+ ]);
+
+ static::assertSame([__FILE__], array_keys($states));
+ static::assertSame($valid, $states[__FILE__]->toArray());
+ static::assertNull($states[__FILE__]->getFilePath());
+ }
+}
diff --git a/tests/Unit/ClassLoaderTest.php b/tests/Unit/ClassLoaderTest.php
new file mode 100644
index 0000000..e81976f
--- /dev/null
+++ b/tests/Unit/ClassLoaderTest.php
@@ -0,0 +1,18 @@
+findFile('Nonexistent\\MissingClass'));
+ static::assertNull($loader->loadClass('Nonexistent\\MissingClass'));
+ }
+}
diff --git a/tests/Unit/CodeTest.php b/tests/Unit/CodeTest.php
new file mode 100644
index 0000000..e64db2f
--- /dev/null
+++ b/tests/Unit/CodeTest.php
@@ -0,0 +1,21 @@
+register();
+
+ static::assertSame('stdClass', (new Code('getClassName());
+ static::assertSame('CodeTest', (new Code('getClassName());
+ }
+}
diff --git a/tests/Unit/DITest.php b/tests/Unit/DITest.php
new file mode 100644
index 0000000..3e972cd
--- /dev/null
+++ b/tests/Unit/DITest.php
@@ -0,0 +1,35 @@
+register();
+ DI::set(stdClass::class, static fn(): string => 'invalid service');
+
+ $this->expectException(LogicException::class);
+ $this->expectExceptionMessage('The container must return the requested class.');
+
+ DI::get(stdClass::class);
+ }
+
+ public function testMakeRejectsAnIncompatibleContainerEntry(): void
+ {
+ DI::getInstance()->register();
+ DI::set(stdClass::class, static fn(): string => 'invalid service');
+
+ $this->expectException(LogicException::class);
+ $this->expectExceptionMessage('The container must return the requested class.');
+
+ DI::make(stdClass::class);
+ }
+}
diff --git a/tests/Unit/StringMutatorTest.php b/tests/Unit/StringMutatorTest.php
new file mode 100644
index 0000000..1f21064
--- /dev/null
+++ b/tests/Unit/StringMutatorTest.php
@@ -0,0 +1,24 @@
+edit(6, 5, 'PHP')->edit(0, 5, 'Hi')->edit(12, 0, '!');
+
+ static::assertSame('Hi PHP!!', $mutator->getMutatedString());
+ }
+
+ public function testNegativeEditLengthIsRejected(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ (new StringMutator('Hello World!'))->edit(0, -1, 'Hi');
+ }
+}
diff --git a/tests/Util.php b/tests/Util.php
index d6209d4..8cee9b6 100644
--- a/tests/Util.php
+++ b/tests/Util.php
@@ -1,58 +1,38 @@
-