From abd8b7f459a723a7ec4ae02ebd56dd2dfbffa225 Mon Sep 17 00:00:00 2001 From: WalterWoshid Date: Fri, 13 Nov 2026 22:45:17 +0100 Subject: [PATCH 1/6] ci: test PHP 8.1-8.5 and update workflow actions Add pull request, review, and manual triggers. Cache Composer downloads and install dependencies on every run. Enable Xdebug coverage, add job timeouts, and disable fail-fast. --- .github/workflows/tests.yml | 44 ++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 75b9d5f..290f57f 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -3,6 +3,19 @@ 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 @@ -10,45 +23,50 @@ permissions: jobs: 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 From 8a85bb9f3ee06bd4c1f2040cf5ab6a53743c22e7 Mon Sep 17 00:00:00 2001 From: WalterWoshid Date: Fri, 13 Nov 2026 22:54:53 +0100 Subject: [PATCH 2/6] chore: add Mago 1.59.0 quality checks Add a shared configuration for source and tests, Composer scripts, and a CI quality job. Document usage and leave existing findings for a separate cleanup. --- .github/workflows/tests.yml | 17 +++++++++++++++++ MAGO.md | 33 +++++++++++++++++++++++++++++++++ composer.json | 8 +++++++- mago.toml | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 MAGO.md create mode 100644 mago.toml diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 290f57f..f866b1d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -21,6 +21,23 @@ 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 diff --git a/MAGO.md b/MAGO.md new file mode 100644 index 0000000..e0740ad --- /dev/null +++ b/MAGO.md @@ -0,0 +1,33 @@ +# 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 when ready to address the findings +``` + +`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. + +Existing formatting, lint, and analyzer findings are left for a separate cleanup. +There is no baseline, vendor type patch, or diagnostic suppression. The CI quality +job runs `composer check` and will fail until those findings are addressed. +Composer stops at the first failing command, so run `composer lint` and +`composer analyze` separately to inspect findings while formatting still fails. + +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..ec31e2d --- /dev/null +++ b/mago.toml @@ -0,0 +1,34 @@ +php-version = "8.1" + +[source] +paths = ["src", "tests"] +includes = ["vendor"] +excludes = ["tests/cache", "tests/coverage", "tests/tmp"] + +[linter] +integrations = ["phpunit"] + +# 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 From 69d6c6137d3d17a3237d51ca77767c59cbab205d Mon Sep 17 00:00:00 2001 From: WalterWoshid Date: Fri, 13 Nov 2026 22:57:17 +0100 Subject: [PATCH 3/6] style: format PHP source and tests with Mago --- src/CodeTransformerKernel.php | 536 +++++++++--------- src/Core/AutoloadInterceptor.php | 159 +++--- .../AutoloadInterceptor/ClassContainer.php | 109 ++-- src/Core/AutoloadInterceptor/ClassLoader.php | 392 +++++++------ src/Core/Cache/CachePaths.php | 171 +++--- src/Core/Cache/CacheState.php | 340 +++++------ .../CacheState/EmptyResultCacheState.php | 44 +- .../NoTransformationsCacheState.php | 46 +- .../CacheState/TransformedCacheState.php | 146 ++--- src/Core/Cache/CacheStateFactory.php | 151 ++--- src/Core/Cache/CacheStateManager.php | 493 ++++++++-------- src/Core/CachedStreamFilter.php | 120 ++-- src/Core/Container/TransformerContainer.php | 44 +- src/Core/Container/TransformerManager.php | 322 ++++++----- src/Core/DI.php | 258 ++++----- .../Exception/CodeTransformerException.php | 26 +- .../DirectKernelInitializationException.php | 50 +- src/Core/Exception/KernelException.php | 22 +- .../StreamFilter/InvalidStreamException.php | 48 +- src/Core/Exception/StreamFilterException.php | 22 +- .../InvalidTransformerClassException.php | 52 +- .../InvalidTransformerClassNameException.php | 4 +- .../Exception/Transformer/SyntaxError.php | 61 +- .../TransformerNotFoundException.php | 48 +- src/Core/Exception/TransformerException.php | 22 +- src/Core/Matcher/TransformerMatcher.php | 243 ++++---- src/Core/Options.php | 328 +++++------ src/Core/Processor/TransformerProcessor.php | 272 +++++---- src/Core/ServiceInterface.php | 36 +- src/Core/StreamFilter.php | 170 +++--- src/Core/StreamFilter/FilterInjector.php | 100 ++-- src/Core/StreamFilter/Metadata.php | 170 +++--- src/Core/Util/CodeChecker.php | 80 +-- src/Core/Util/ReflectionHelper.php | 105 ++-- src/Core/Util/StringMutator.php | 152 ++--- src/Transformer.php | 84 +-- src/Transformer/Code.php | 439 +++++++------- src/functions.php | 79 ++- tests/ClassLoaderMockTrait.php | 170 +++--- .../CachedFileAndDestructorTest.php | 175 +++--- .../Target/StringClass.php | 22 +- .../Transformer/StringTransformer.php | 79 ++- .../DeleteCacheFile/DeleteCacheFileTest.php | 95 ++-- .../Cache/DeleteCacheFile/Target.php | 22 +- .../Cache/DeleteCacheFile/Transformer.php | 38 +- .../AddedTransformer/AddedTransformerTest.php | 86 ++- .../Kernel/AddedTransformerKernel.php | 34 +- .../Kernel/AddedTransformer/Target.php | 28 +- .../Transformer/AddedTransformer1.php | 87 +-- .../Transformer/AddedTransformer2.php | 82 ++- .../AlreadyInitializedKernel/Kernel.php | 1 + .../CustomDependencyInjectionHandlerTest.php | 10 +- .../Kernel/DirectKernel/DirectKernelTest.php | 34 +- .../Kernel/Environment/EnvironmentTest.php | 46 +- .../Transformer/StringTransformer.php | 10 +- tests/Functional/Kernel/KernelTest.php | 64 +-- .../Target/ChangedClass/ChangedClassTest.php | 136 ++--- .../Functional/Target/ChangedClass/Target.php | 22 +- .../Target/ChangedClass/Transformer.php | 72 ++- .../Target/NoChanges/NoChangesTest.php | 80 +-- tests/Functional/Target/NoChanges/Target.php | 12 +- .../Target/NoChanges/Transformer.php | 38 +- .../InvalidTransformer.php | 38 +- .../InvalidTransformerClassTest.php | 106 ++-- .../Kernel/TransformerDoesNotExistKernel.php | 30 +- ...nsformerDoesNotExtendTransformerKernel.php | 32 +- .../MultipleTransformersTest.php | 98 ++-- .../MultipleTransformer/TargetClass.php | 27 +- .../Transformer/UnPrivateTransformer.php | 54 +- .../SyntaxErrorInTransformedClassTest.php | 52 +- .../SyntaxErrorInTransformedClass/Target.php | 12 +- .../Transformer.php | 50 +- tests/Util.php | 96 ++-- 73 files changed, 3876 insertions(+), 4106 deletions(-) diff --git a/src/CodeTransformerKernel.php b/src/CodeTransformerKernel.php index 3cb9e5d..05db27a 100644 --- a/src/CodeTransformerKernel.php +++ b/src/CodeTransformerKernel.php @@ -1,269 +1,267 @@ -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 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(); + } + } +} diff --git a/src/Core/AutoloadInterceptor.php b/src/Core/AutoloadInterceptor.php index b5a2753..e5121b1 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) || !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); + } + } +} diff --git a/src/Core/AutoloadInterceptor/ClassContainer.php b/src/Core/AutoloadInterceptor/ClassContainer.php index 7f97917..a864883 100644 --- a/src/Core/AutoloadInterceptor/ClassContainer.php +++ b/src/Core/AutoloadInterceptor/ClassContainer.php @@ -1,56 +1,53 @@ - - */ - 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 string + */ + public function getNamespacedClassByPath(string $path): string + { + return $this->classContext[$path]['namespacedClass']; + } + + public function getCachedFilePath(string $filePath): string + { + return $this->classContext[$filePath]['cachedFilePath']; + } +} diff --git a/src/Core/AutoloadInterceptor/ClassLoader.php b/src/Core/AutoloadInterceptor/ClassLoader.php index cbc1d20..8e5f593 100644 --- a/src/Core/AutoloadInterceptor/ClassLoader.php +++ b/src/Core/AutoloadInterceptor/ClassLoader.php @@ -1,201 +1,191 @@ -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($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\\', + ], + ); + } +} diff --git a/src/Core/Cache/CachePaths.php b/src/Core/Cache/CachePaths.php index 998db4a..9fda4df 100644 --- a/src/Core/Cache/CachePaths.php +++ b/src/Core/Cache/CachePaths.php @@ -1,86 +1,85 @@ -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); + + 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); + } +} diff --git a/src/Core/Cache/CacheState.php b/src/Core/Cache/CacheState.php index 546a1af..8587c15 100644 --- a/src/Core/Cache/CacheState.php +++ b/src/Core/Cache/CacheState.php @@ -1,170 +1,170 @@ - $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) { + $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; +} 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 + } + + if (filemtime($transformerFilePath) > $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..3cf190b 100644 --- a/src/Core/Cache/CacheStateFactory.php +++ b/src/Core/Cache/CacheStateFactory.php @@ -1,74 +1,77 @@ - 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 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; + } +} diff --git a/src/Core/Cache/CacheStateManager.php b/src/Core/Cache/CacheStateManager.php index 97587a3..6a8fabf 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 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; + } +} diff --git a/src/Core/CachedStreamFilter.php b/src/Core/CachedStreamFilter.php index 769bd70..b4e1b83 100644 --- a/src/Core/CachedStreamFilter.php +++ b/src/Core/CachedStreamFilter.php @@ -1,60 +1,60 @@ -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; - } -} +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; + } +} 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 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; + } +} diff --git a/src/Core/DI.php b/src/Core/DI.php index 3c75b78..12ddba9 100644 --- a/src/Core/DI.php +++ b/src/Core/DI.php @@ -1,129 +1,129 @@ -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 + * + * @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); + } +} 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\n\nFull code:\n```php\n$code\n```", + previous: $previous, + ); + } +} diff --git a/src/Core/Exception/Transformer/TransformerNotFoundException.php b/src/Core/Exception/Transformer/TransformerNotFoundException.php index b8f90f6..3511945 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, + 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] ?? []; + } +} diff --git a/src/Core/Options.php b/src/Core/Options.php index 36cc3b7..3c8b70a 100644 --- a/src/Core/Options.php +++ b/src/Core/Options.php @@ -1,164 +1,164 @@ -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(); + $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; + } +} diff --git a/src/Core/Processor/TransformerProcessor.php b/src/Core/Processor/TransformerProcessor.php index 68a2147..0345075 100644 --- a/src/Core/Processor/TransformerProcessor.php +++ b/src/Core/Processor/TransformerProcessor.php @@ -1,142 +1,130 @@ -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(); + 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, + ); + } +} 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; - } -} +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; + } +} 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..5716c4e 100644 --- a/src/Core/StreamFilter/Metadata.php +++ b/src/Core/StreamFilter/Metadata.php @@ -1,85 +1,85 @@ -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), - ]); - } -} +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..4a35a76 100644 --- a/src/Core/Util/CodeChecker.php +++ b/src/Core/Util/CodeChecker.php @@ -1,40 +1,40 @@ -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); + } + + 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..21706d8 100644 --- a/src/Core/Util/StringMutator.php +++ b/src/Core/Util/StringMutator.php @@ -1,76 +1,76 @@ -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; - } -} +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; + } +} diff --git a/src/Transformer.php b/src/Transformer.php index 9e783d9..2b76c0f 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, - ); - } -} +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); + } +} diff --git a/src/functions.php b/src/functions.php index b7d18ae..0286232 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(); + } + + 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'); + } +} diff --git a/tests/Functional/Cache/CachedFileAndDestructor/CachedFileAndDestructorTest.php b/tests/Functional/Cache/CachedFileAndDestructor/CachedFileAndDestructorTest.php index 9aa2d69..719b3f2 100644 --- a/tests/Functional/Cache/CachedFileAndDestructor/CachedFileAndDestructorTest.php +++ b/tests/Functional/Cache/CachedFileAndDestructor/CachedFileAndDestructorTest.php @@ -1,95 +1,80 @@ -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 $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); + } +} 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(); + + 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(); + } +} diff --git a/tests/Functional/Cache/DeleteCacheFile/DeleteCacheFileTest.php b/tests/Functional/Cache/DeleteCacheFile/DeleteCacheFileTest.php index a9625e2..bbce738 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 $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); + } +} 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..c126967 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 $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()); + } +} diff --git a/tests/Functional/Kernel/AddedTransformer/Kernel/AddedTransformerKernel.php b/tests/Functional/Kernel/AddedTransformer/Kernel/AddedTransformerKernel.php index 60eedb1..a448b9f 100644 --- a/tests/Functional/Kernel/AddedTransformer/Kernel/AddedTransformerKernel.php +++ b/tests/Functional/Kernel/AddedTransformer/Kernel/AddedTransformerKernel.php @@ -1,17 +1,17 @@ -transformerManager->addTransformers($this->addedTransformers); - } -} +transformerManager->addTransformers($this->addedTransformers); + } +} diff --git a/tests/Functional/Kernel/AddedTransformer/Target.php b/tests/Functional/Kernel/AddedTransformer/Target.php index 6e09ce7..e5f61fc 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(); + + 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', + ); + } + } + } + } +} diff --git a/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer2.php b/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer2.php index 3aaad9c..9462edf 100644 --- a/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer2.php +++ b/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer2.php @@ -1,43 +1,39 @@ -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(); + + 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'); + } + } + } + } +} 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, - ); + $this->assertStringContainsString('Generating transformer instance: ' . StringTransformer::class, $output); $class = new StringClass(); - $this->assertSame( - 'Hello from Code Transformer!', - $class->test(), - ); + $this->assertSame('Hello from Code Transformer!', $class->test()); } } 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..4d14b48 100644 --- a/tests/Functional/Kernel/Environment/EnvironmentTest.php +++ b/tests/Functional/Kernel/Environment/EnvironmentTest.php @@ -31,10 +31,7 @@ public function testDevelopmentEnvironment(): void $helloWorldClass = new $class(); - $this->assertSame( - 'Hello from Code Transformer!', - $helloWorldClass->say(), - ); + $this->assertSame('Hello from Code Transformer!', $helloWorldClass->say()); } /** @@ -49,10 +46,7 @@ public function testCachedDevelopmentEnvironment(): void $helloWorldClass = new $class(); - $this->assertSame( - 'Hello from Code Transformer!', - $helloWorldClass->say(), - ); + $this->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); @@ -81,10 +71,7 @@ public function testChangedDevelopmentEnvironment(): void $this->assertWillBeTransformed($class); $classInstance = new $class(); - $this->assertSame( - 'Hello Changed World from Code Transformer!', - $classInstance->say(), - ); + $this->assertSame('Hello Changed World from Code Transformer!', $classInstance->say()); } catch (Throwable $e) { $exception = $e; } @@ -111,10 +98,7 @@ public function testProductionEnvironment(): void $helloWorldClass = new $class(); - $this->assertSame( - 'Hello from Code Transformer!', - $helloWorldClass->say(), - ); + $this->assertSame('Hello from Code Transformer!', $helloWorldClass->say()); } /** @@ -129,10 +113,7 @@ public function testCachedProductionEnvironment(): void $helloWorldClass = new $class(); - $this->assertSame( - 'Hello from Code Transformer!', - $helloWorldClass->say(), - ); + $this->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); @@ -161,10 +138,7 @@ public function testChangedProductionEnvironment(): void $this->assertTransformerLoadedFromCache($class); $classInstance = new $class(); - $this->assertSame( - 'Hello from Code Transformer!', - $classInstance->say(), - ); + $this->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..70ae918 100644 --- a/tests/Functional/Kernel/Environment/Transformer/StringTransformer.php +++ b/tests/Functional/Kernel/Environment/Transformer/StringTransformer.php @@ -23,16 +23,10 @@ public function transform(Code $code): void if ($node instanceof StringLiteral) { if ($node->getStringContentsText() === 'Hello World!') { // Replace it with 'Hello from Code Transformer!' - $code->edit( - $node->children, - "'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!'", - ); + $code->edit($node->children, "'Hello Changed World from Code Transformer!'"); } } } diff --git a/tests/Functional/Kernel/KernelTest.php b/tests/Functional/Kernel/KernelTest.php index 1b0e152..bc21d5d 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); - } -} +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); + } +} diff --git a/tests/Functional/Target/ChangedClass/ChangedClassTest.php b/tests/Functional/Target/ChangedClass/ChangedClassTest.php index dd9ba52..c86f749 100644 --- a/tests/Functional/Target/ChangedClass/ChangedClassTest.php +++ b/tests/Functional/Target/ChangedClass/ChangedClassTest.php @@ -1,73 +1,63 @@ -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 $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; + } + } +} 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(); + + 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!'"); + } + } + } + } +} diff --git a/tests/Functional/Target/NoChanges/NoChangesTest.php b/tests/Functional/Target/NoChanges/NoChangesTest.php index a1487b0..ea7bf5c 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 $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); + } +} 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 $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); + } +} diff --git a/tests/Functional/Transformer/MultipleTransformer/TargetClass.php b/tests/Functional/Transformer/MultipleTransformer/TargetClass.php index 4cb8be8..d44b819 100644 --- a/tests/Functional/Transformer/MultipleTransformer/TargetClass.php +++ b/tests/Functional/Transformer/MultipleTransformer/TargetClass.php @@ -1,13 +1,14 @@ -getSourceFileNode(); - - foreach ($sourceFileNode->getDescendantTokens() as $token) { - if ($token->kind === TokenKind::PrivateKeyword) { - $code->edit($token, 'public'); - } - } - } -} +getSourceFileNode(); + + foreach ($sourceFileNode->getDescendantTokens() as $token) { + if ($token->kind === TokenKind::PrivateKeyword) { + $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($refClass->getName() === Target::class); + + $className = $code->getNewSource(); + assert($className === 'SyntaxErrorClass'); + } +} 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 @@ - Date: Fri, 13 Nov 2026 22:58:39 +0100 Subject: [PATCH 4/6] chore: ignore formatting commit in git blame --- .git-blame-ignore-revs | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .git-blame-ignore-revs 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 From c58290f96ee6bef6a0afa6aec7e0e388a409e0b9 Mon Sep 17 00:00:00 2001 From: WalterWoshid Date: Fri, 13 Nov 2026 23:25:53 +0100 Subject: [PATCH 5/6] fix: resolve Mago lint and analysis findings --- MAGO.md | 11 ++- src/CodeTransformerKernel.php | 36 +++++----- src/Core/AutoloadInterceptor.php | 6 +- .../AutoloadInterceptor/ClassContainer.php | 11 ++- src/Core/AutoloadInterceptor/ClassLoader.php | 69 ++++++------------- src/Core/Cache/CachePaths.php | 8 ++- src/Core/Cache/CacheState.php | 34 ++++++--- .../CacheState/TransformedCacheState.php | 7 +- src/Core/Cache/CacheStateFactory.php | 33 ++++----- src/Core/Cache/CacheStateManager.php | 38 +++++----- src/Core/CachedStreamFilter.php | 17 ++++- src/Core/Container/TransformerManager.php | 66 ++++++++++-------- src/Core/DI.php | 31 ++++++--- .../Exception/Transformer/SyntaxError.php | 14 ++-- .../TransformerNotFoundException.php | 2 +- src/Core/Matcher/TransformerMatcher.php | 16 +++-- src/Core/Options.php | 16 ++++- src/Core/Processor/TransformerProcessor.php | 50 +++++++------- src/Core/StreamFilter.php | 17 ++++- src/Core/StreamFilter/Metadata.php | 19 ++++- src/Core/Util/CodeChecker.php | 10 +-- src/Core/Util/StringMutator.php | 13 ++-- src/Transformer.php | 2 +- src/Transformer/Code.php | 5 +- src/functions.php | 4 +- tests/ClassLoaderMockTrait.php | 27 ++++++-- .../CachedFileAndDestructorTest.php | 26 +++---- .../Transformer/StringTransformer.php | 16 +++-- .../DeleteCacheFile/DeleteCacheFileTest.php | 14 ++-- .../AddedTransformer/AddedTransformerTest.php | 8 +-- .../Kernel/AddedTransformerKernel.php | 1 + .../Kernel/AddedTransformer/Target.php | 2 +- .../Transformer/AddedTransformer1.php | 36 ++++++---- .../Transformer/AddedTransformer2.php | 32 ++++++--- .../AlreadyInitializedKernelTest.php | 2 +- .../CustomDependencyInjectionHandlerTest.php | 5 +- .../Kernel.php | 5 +- .../Kernel/Environment/EnvironmentTest.php | 24 +++---- .../Transformer/StringTransformer.php | 24 ++++--- tests/Functional/Kernel/KernelTest.php | 12 ++-- .../Target/ChangedClass/ChangedClassTest.php | 10 ++- .../Target/ChangedClass/Transformer.php | 24 ++++--- .../Target/NoChanges/NoChangesTest.php | 8 +-- .../InvalidTransformer.php | 1 + .../MultipleTransformersTest.php | 24 +++++-- .../MultipleTransformer/TargetClass.php | 6 ++ .../Transformer/UnPrivateTransformer.php | 10 ++- .../Transformer.php | 5 +- tests/Unit/CacheStateTest.php | 59 ++++++++++++++++ tests/Unit/ClassLoaderTest.php | 18 +++++ tests/Unit/CodeTest.php | 21 ++++++ tests/Unit/DITest.php | 35 ++++++++++ tests/Unit/StringMutatorTest.php | 24 +++++++ 53 files changed, 661 insertions(+), 353 deletions(-) create mode 100644 tests/Unit/CacheStateTest.php create mode 100644 tests/Unit/ClassLoaderTest.php create mode 100644 tests/Unit/CodeTest.php create mode 100644 tests/Unit/DITest.php create mode 100644 tests/Unit/StringMutatorTest.php diff --git a/MAGO.md b/MAGO.md index e0740ad..9f213c1 100644 --- a/MAGO.md +++ b/MAGO.md @@ -8,7 +8,7 @@ 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 when ready to address the findings +composer format # apply formatting ``` `mago.toml` checks both `src` and `tests`, targeting PHP 8.1, the minimum supported @@ -21,11 +21,10 @@ and `isset` retain the existing API conventions. Aggregate complexity metrics ar 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. -Existing formatting, lint, and analyzer findings are left for a separate cleanup. -There is no baseline, vendor type patch, or diagnostic suppression. The CI quality -job runs `composer check` and will fail until those findings are addressed. -Composer stops at the first failing command, so run `composer lint` and -`composer analyze` separately to inspect findings while formatting still fails. +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 diff --git a/src/CodeTransformerKernel.php b/src/CodeTransformerKernel.php index 05db27a..78bf60d 100644 --- a/src/CodeTransformerKernel.php +++ b/src/CodeTransformerKernel.php @@ -4,6 +4,7 @@ use Closure; use DI\Attribute\Inject; +use LogicException; use Okapi\CodeTransformer\Core\AutoloadInterceptor; use Okapi\CodeTransformer\Core\Cache\CacheStateManager; use Okapi\CodeTransformer\Core\CachedStreamFilter; @@ -41,18 +42,6 @@ abstract class CodeTransformerKernel #[Inject] protected TransformerManager $transformerManager; - #[Inject] - private CacheStateManager $cacheStateManager; - - #[Inject] - private StreamFilter $streamFilter; - - #[Inject] - private CachedStreamFilter $cachedStreamFilter; - - #[Inject] - private AutoloadInterceptor $autoloadInterceptor; - /** * Make the constructor public to allow the DI container to instantiate the * class. @@ -76,7 +65,7 @@ public function __construct() {} /** * The exclude paths. Paths/directories in this array will be excluded * - * @var array + * @var string[] */ protected array $excludePaths = []; @@ -125,7 +114,7 @@ public function __construct() {} /** * List of transformers to be applied. * - * @var class-string[] + * @var array */ protected array $transformers = []; @@ -142,7 +131,13 @@ public static function getInstance(): static static::$instance = DI::get(static::class); } - return static::$instance; + /** @var mixed $instance */ + $instance = static::$instance; + if (!$instance instanceof static) { + throw new LogicException('The container must return the requested kernel class.'); + } + + return $instance; } /** @@ -158,7 +153,8 @@ public static function init(): void if ($instance->throwExceptionOnDoubleInitialization) { $instance->ensureNotInitialized(); - } elseif ($instance->initialized) { + } + if (!$instance->throwExceptionOnDoubleInitialization && $instance->initialized) { return; } @@ -233,10 +229,10 @@ protected function registerServices(): void $this->transformerManager->registerCustomDependencyInjectionHandler($this->dependencyInjectionHandler()); $this->transformerManager->register(); - $this->cacheStateManager->register(); + DI::get(CacheStateManager::class)->register(); - $this->streamFilter->register(); - $this->cachedStreamFilter->register(); + DI::get(StreamFilter::class)->register(); + DI::get(CachedStreamFilter::class)->register(); } /** @@ -247,7 +243,7 @@ protected function registerServices(): void protected function registerAutoloadInterceptor(): void { // Overload the composer class loaders - $this->autoloadInterceptor->register(); + DI::get(AutoloadInterceptor::class)->register(); } /** diff --git a/src/Core/AutoloadInterceptor.php b/src/Core/AutoloadInterceptor.php index e5121b1..6449ffe 100644 --- a/src/Core/AutoloadInterceptor.php +++ b/src/Core/AutoloadInterceptor.php @@ -53,7 +53,7 @@ private function overloadComposerLoaders(): void $loaderToUnregister = $loader; // Skip if not a class loader - if (!is_array($loader) || !isset($loader[0]) || !$loader[0] instanceof ComposerClassLoader) { + if (!is_array($loader) || !$loader[0] instanceof ComposerClassLoader) { // @codeCoverageIgnoreStart continue; @@ -65,7 +65,7 @@ private function overloadComposerLoaders(): void $this->reflectionHelper->setClassLoader($originalClassLoader); // Create the Code Transformer class loader - $loader[0] = DI::make(ClassLoader::class, [ + $classLoader = DI::make(ClassLoader::class, [ 'originalClassLoader' => $originalClassLoader, ]); @@ -73,7 +73,7 @@ private function overloadComposerLoaders(): void spl_autoload_unregister($loaderToUnregister); // Register the Code Transformer class loader - spl_autoload_register($loader); + spl_autoload_register([$classLoader, 'loadClass']); } } } diff --git a/src/Core/AutoloadInterceptor/ClassContainer.php b/src/Core/AutoloadInterceptor/ClassContainer.php index a864883..ceced33 100644 --- a/src/Core/AutoloadInterceptor/ClassContainer.php +++ b/src/Core/AutoloadInterceptor/ClassContainer.php @@ -2,6 +2,8 @@ namespace Okapi\CodeTransformer\Core\AutoloadInterceptor; +use LogicException; + /** * # Class Container * @@ -39,7 +41,7 @@ public function addClassContext(string $path, string $namespacedClass, ?string $ * * @param string $path * - * @return string + * @return class-string */ public function getNamespacedClassByPath(string $path): string { @@ -48,6 +50,11 @@ public function getNamespacedClassByPath(string $path): string public function getCachedFilePath(string $filePath): string { - return $this->classContext[$filePath]['cachedFilePath']; + $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 8e5f593..7bf37ea 100644 --- a/src/Core/AutoloadInterceptor/ClassLoader.php +++ b/src/Core/AutoloadInterceptor/ClassLoader.php @@ -7,7 +7,6 @@ use DI\Attribute\Inject; use Okapi\CodeTransformer\Core\AutoloadInterceptor; use Okapi\CodeTransformer\Core\Cache\CacheStateManager; -use Okapi\CodeTransformer\Core\CachedStreamFilter; use Okapi\CodeTransformer\Core\Matcher\TransformerMatcher; use Okapi\CodeTransformer\Core\Options; use Okapi\CodeTransformer\Core\Options\Environment; @@ -60,39 +59,32 @@ public function __construct( /** * Autoload a class. * - * @param $namespacedClass + * @param string $class * - * @return bool - * - * @noinspection PhpParameterNameChangedDuringInheritanceInspection + * @return true|null */ - public function loadClass($namespacedClass): bool + public function loadClass($class): ?bool { - if ($file = $this->findFile($namespacedClass)) { + $file = $this->findFile($class); + if ($file !== false) { include $file; - return true; } - // @codeCoverageIgnoreStart - // Not sure how to test this - return false; - - // @codeCoverageIgnoreEnd + return null; } /** * Find the path to the file and match and apply the transformers. * - * @param class-string $namespacedClass + * @param string $class * * @return false|string - * - * @noinspection PhpParameterNameChangedDuringInheritanceInspection - * @noinspection PhpStatementHasEmptyBodyInspection */ - public function findFile($namespacedClass): false|string + public function findFile($class): false|string { + /** @var class-string $namespacedClass */ + $namespacedClass = $class; $filePath = $this->originalClassLoader->findFile($namespacedClass); // @codeCoverageIgnoreStart @@ -108,9 +100,13 @@ public function findFile($namespacedClass): false|string } $filePath = Path::resolve($filePath); + if (!is_string($filePath)) { + return false; + } foreach ($this->options->getExcludePaths() as $path) { - if (str_starts_with($filePath, Path::resolve($path))) { + $resolvedPath = Path::resolve($path); + if (is_string($resolvedPath) && str_starts_with($filePath, $resolvedPath)) { return $filePath; } } @@ -118,35 +114,14 @@ public function findFile($namespacedClass): false|string // 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()) { + $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); - - // 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); } diff --git a/src/Core/Cache/CachePaths.php b/src/Core/Cache/CachePaths.php index 9fda4df..7dcdd6d 100644 --- a/src/Core/Cache/CachePaths.php +++ b/src/Core/Cache/CachePaths.php @@ -6,6 +6,7 @@ use DI\Attribute\Inject; use Okapi\CodeTransformer\Core\Options; use Okapi\Path\Path; +use RuntimeException; /** * # Cache Paths @@ -68,7 +69,12 @@ protected function appendToCachePath(string $file, string $append): string // Append the string to the cache dir $newDir = Path::join($cacheDir, $append); - return Path::resolve(str_replace($appDir, $newDir, $file)); + $path = Path::resolve(str_replace($appDir, $newDir, $file)); + if (!is_string($path)) { + throw new RuntimeException('Cannot resolve cache path for ' . $file); + } + + return $path; } /** diff --git a/src/Core/Cache/CacheState.php b/src/Core/Cache/CacheState.php index 8587c15..4686b8b 100644 --- a/src/Core/Cache/CacheState.php +++ b/src/Core/Cache/CacheState.php @@ -3,6 +3,8 @@ /** @noinspection PhpPropertyOnlyWrittenInspection */ namespace Okapi\CodeTransformer\Core\Cache; +use ReflectionProperty; + /** * # Cache State * @@ -24,7 +26,7 @@ abstract class CacheState /** * CacheState constructor. * - * @param array $data + * @param array $data */ public function __construct(array $data = []) { @@ -34,7 +36,7 @@ public function __construct(array $data = []) /** * Get the cache state as an array. * - * @return array + * @return array */ public function toArray(): array { @@ -47,14 +49,17 @@ public function toArray(): array /** * Get the cache state as an array. * - * @return array + * @return array */ private function getAllData(): array { $data = []; foreach ($this->getRequiredKeys() as $key) { - $data[$key] = $this->{$key}; + $property = new ReflectionProperty($this, $key); + /** @var mixed $value */ + $value = $property->getValue($this); + $data[$key] = $value; } return $data; @@ -68,7 +73,8 @@ private function getAllData(): array protected function getType(): string { // Return the class name without the namespace - return substr(static::class, strrpos(static::class, '\\') + 1); + $separator = strrpos(static::class, '\\'); + return $separator === false ? static::class : substr(static::class, $separator + 1); } /** @@ -88,7 +94,7 @@ public function getRequiredKeys(): array /** * Create a cache state if it is valid. * - * @param array $cacheStateArray + * @param array $cacheStateArray * * @return self|null */ @@ -109,7 +115,7 @@ public function createIfValid(array $cacheStateArray): ?CacheState /** * Validate the cache state. * - * @param array $cacheStateArray + * @param array $cacheStateArray * * @return bool */ @@ -131,12 +137,17 @@ private function valid(array $cacheStateArray): bool /** * Set the cache state data. * - * @param array $cacheStateArray + * @param array $cacheStateArray */ private function setData(array $cacheStateArray): void { - foreach ($cacheStateArray as $key => $value) { - $this->{$key} = $value; + 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); } } @@ -154,7 +165,8 @@ public function isFresh(): bool // @codeCoverageIgnoreEnd } - if (filemtime($this->originalFilePath) > $this->modificationTime) { + $modified = filemtime($this->originalFilePath); + if ($modified === false || $modified > $this->modificationTime) { return false; } diff --git a/src/Core/Cache/CacheState/TransformedCacheState.php b/src/Core/Cache/CacheState/TransformedCacheState.php index 81a8efc..ad75cf4 100644 --- a/src/Core/Cache/CacheState/TransformedCacheState.php +++ b/src/Core/Cache/CacheState/TransformedCacheState.php @@ -16,6 +16,10 @@ class TransformedCacheState extends CacheState public const TRANSFORMER_FILE_PATHS_KEY = 'transformerFilePaths'; public string $transformedFilePath; + + /** + * @var string[] + */ public array $transformerFilePaths; /** @@ -52,7 +56,8 @@ public function isFresh(): bool // @codeCoverageIgnoreEnd } - if (filemtime($transformerFilePath) > $this->modificationTime) { + $modified = filemtime($transformerFilePath); + if ($modified === false || $modified > $this->modificationTime) { // @codeCoverageIgnoreStart return false; diff --git a/src/Core/Cache/CacheStateFactory.php b/src/Core/Cache/CacheStateFactory.php index 3cf190b..7f928a0 100644 --- a/src/Core/Cache/CacheStateFactory.php +++ b/src/Core/Cache/CacheStateFactory.php @@ -6,7 +6,6 @@ use Okapi\CodeTransformer\Core\Cache\CacheState\NoTransformationsCacheState; use Okapi\CodeTransformer\Core\Cache\CacheState\TransformedCacheState; use Okapi\CodeTransformer\Core\DI; -use TypeError; /** * # Cache State Factory @@ -27,37 +26,29 @@ class CacheStateFactory /** * Create cache states from the cache state file. * - * @param array> $cacheStatesArray + * @param array $cacheStatesArray * - * @return CacheState[] + * @return array */ public function createCacheStates(array $cacheStatesArray): array { $cacheStateObjects = []; - foreach ($cacheStatesArray as $cacheStateArray) { - // Skip cache states without a type - if (!isset($cacheStateArray[CacheState::TYPE])) { - // @codeCoverageIgnoreStart + foreach (array_keys($cacheStatesArray) as $cacheKey) { + /** @var mixed $cacheStateArray */ + $cacheStateArray = $cacheStatesArray[$cacheKey]; + if (!is_array($cacheStateArray)) { 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) { + /** @var mixed $type */ + $type = $cacheStateArray[CacheState::TYPE] ?? null; + if (!is_string($type) || !isset(static::CACHE_STATE_MAP[$type])) { continue; } - // @codeCoverageIgnoreEnd + + unset($cacheStateArray[CacheState::TYPE]); + $cacheState = DI::make(static::CACHE_STATE_MAP[$type]); // Create if valid $cacheState = $cacheState->createIfValid($cacheStateArray); diff --git a/src/Core/Cache/CacheStateManager.php b/src/Core/Cache/CacheStateManager.php index 6a8fabf..87bf550 100644 --- a/src/Core/Cache/CacheStateManager.php +++ b/src/Core/Cache/CacheStateManager.php @@ -58,14 +58,14 @@ class CacheStateManager implements ServiceInterface /** * Cached metadata for the transformation state of a file. * - * @var array + * @var array */ private array $cacheState = []; /** * New metadata for the transformation state of a file. * - * @var array + * @var array */ private array $newCacheState = []; @@ -112,24 +112,24 @@ private function loadCacheState(): void return; } - // Read file - $cacheFileContent = Filesystem::readFile($cacheFilePath); + // 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(); - - // 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); + 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(); @@ -174,7 +174,7 @@ public function __destruct() */ private function saveCacheState(): void { - if (empty($this->newCacheState)) { + if ($this->newCacheState === []) { // @codeCoverageIgnoreStart return; @@ -186,7 +186,7 @@ private function saveCacheState(): void // Create the cache state array $cacheStateArray = array_map( - fn(CacheState $cacheState) => $cacheState->toArray(), + static fn(CacheState $cacheState) => $cacheState->toArray(), array_merge($this->cacheState, $this->newCacheState), ); diff --git a/src/Core/CachedStreamFilter.php b/src/Core/CachedStreamFilter.php index b4e1b83..bcbfaee 100644 --- a/src/Core/CachedStreamFilter.php +++ b/src/Core/CachedStreamFilter.php @@ -3,6 +3,7 @@ namespace Okapi\CodeTransformer\Core; use Okapi\CodeTransformer\Core\AutoloadInterceptor\ClassContainer; +use Okapi\CodeTransformer\Core\Exception\StreamFilter\InvalidStreamException; use Okapi\CodeTransformer\Core\StreamFilter\Metadata; use Okapi\Filesystem\Filesystem; use php_user_filter as PhpStreamFilter; @@ -28,13 +29,23 @@ public function register(): void public function filter($in, $out, &$consumed, bool $closing): int { + /** @var mixed $stream */ + $stream = $this->stream; + if (!is_resource($stream)) { + throw new InvalidStreamException(); + } + // Read stream until EOF - while ($bucket = stream_bucket_make_writeable($in)) { + 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($this->stream)) { + if ($closing || feof($stream)) { $consumed = strlen($this->data); $metadata = DI::make(Metadata::class, [ @@ -47,7 +58,7 @@ public function filter($in, $out, &$consumed, bool $closing): int $source = Filesystem::readFile($cachedFilePath); - $bucket = stream_bucket_new($this->stream, $source); + $bucket = stream_bucket_new($stream, $source); stream_bucket_append($out, $bucket); // Pass the (cached) source code to the next filter diff --git a/src/Core/Container/TransformerManager.php b/src/Core/Container/TransformerManager.php index 55de8c7..fa1d576 100644 --- a/src/Core/Container/TransformerManager.php +++ b/src/Core/Container/TransformerManager.php @@ -4,8 +4,7 @@ namespace Okapi\CodeTransformer\Core\Container; use Closure; -use Error; -use Exception; +use LogicException; use Okapi\CodeTransformer\Core\DI; use Okapi\CodeTransformer\Core\Exception\Transformer\InvalidTransformerClassException; use Okapi\CodeTransformer\Core\Exception\Transformer\InvalidTransformerClassNameException; @@ -13,6 +12,7 @@ use Okapi\CodeTransformer\Core\ServiceInterface; use Okapi\CodeTransformer\Transformer; use ReflectionClass as BaseReflectionClass; +use Throwable; /** * # Transformer Manager @@ -24,7 +24,7 @@ class TransformerManager implements ServiceInterface /** * The list of transformer class strings. * - * @var class-string[] + * @var array */ private array $transformers = []; @@ -45,7 +45,7 @@ class TransformerManager implements ServiceInterface /** * Add transformers. * - * @param class-string[] $transformers + * @param array $transformers * * @return void */ @@ -73,46 +73,34 @@ public function register(): void private function loadTransformers(): void { - foreach ($this->transformers as $transformer) { + foreach (array_keys($this->transformers) as $transformerKey) { + /** @var mixed $transformer */ + $transformer = $this->transformers[$transformerKey]; $this->loadTransformer($transformer); } } /** - * @param class-string $transformerClassName + * @param mixed $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') { + if (!is_string($transformerClassName)) { 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); - } + 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) { @@ -128,9 +116,27 @@ private function loadTransformer(mixed $transformerClassName): void $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 []; @@ -141,7 +147,7 @@ protected function getAdditionalDependencyInjectionParams(): array /** * Get the transformers. * - * @return class-string[] + * @return array */ public function getTransformers(): array { diff --git a/src/Core/DI.php b/src/Core/DI.php index 12ddba9..558d419 100644 --- a/src/Core/DI.php +++ b/src/Core/DI.php @@ -4,6 +4,7 @@ use DI\Container; use DI\ContainerBuilder; +use LogicException; use Okapi\Singleton\Singleton; /** @@ -69,7 +70,7 @@ public static function getContainerBuilder(): ContainerBuilder /** * Get an (already initialized) instance of the given class. * - * @template T + * @template T of object * * @param class-string $class * @@ -77,26 +78,32 @@ public static function getContainerBuilder(): ContainerBuilder * * @noinspection PhpDocMissingThrowsInspection */ - public static function get(string $class) + public static function get(string $class): mixed { $instance = static::getInstance(); $instance->ensureInitialized(); /** @noinspection PhpUnhandledExceptionInspection */ - return $instance->container->get($class); + /** @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 $value + * @param mixed $value * * @return void * * @codeCoverageIgnore */ - public static function set(string $class, $value): void + public static function set(string $class, mixed $value): void { $instance = static::getInstance(); $instance->ensureInitialized(); @@ -109,21 +116,27 @@ public static function set(string $class, $value): void * * This method behaves like a factory. * - * @template T + * @template T of object * * @param class-string $class - * @param array $parameters + * @param array $parameters * * @return T * * @noinspection PhpDocMissingThrowsInspection */ - public static function make(string $class, array $parameters = []) + public static function make(string $class, array $parameters = []): mixed { $instance = static::getInstance(); $instance->ensureInitialized(); /** @noinspection PhpUnhandledExceptionInspection */ - return $instance->container->make($class, $parameters); + /** @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/Transformer/SyntaxError.php b/src/Core/Exception/Transformer/SyntaxError.php index 3ef1f5e..1f602d9 100644 --- a/src/Core/Exception/Transformer/SyntaxError.php +++ b/src/Core/Exception/Transformer/SyntaxError.php @@ -21,9 +21,15 @@ class SyntaxError extends TransformerException */ public function __construct(Diagnostic $diagnostic, string $code, ?SyntaxError $previous = null) { - parent::__construct( - message: "Syntax error in transformed code: $diagnostic->message\n\nFull code:\n```php\n$code\n```", - previous: $previous, - ); + $message = <<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 3511945..e1400fd 100644 --- a/src/Core/Exception/Transformer/TransformerNotFoundException.php +++ b/src/Core/Exception/Transformer/TransformerNotFoundException.php @@ -14,7 +14,7 @@ class TransformerNotFoundException extends TransformerException /** * TransformerNotFoundException constructor. * - * @param class-string $transformerClass + * @param string $transformerClass */ public function __construct(string $transformerClass) { diff --git a/src/Core/Matcher/TransformerMatcher.php b/src/Core/Matcher/TransformerMatcher.php index 5113d3f..bb2c76a 100644 --- a/src/Core/Matcher/TransformerMatcher.php +++ b/src/Core/Matcher/TransformerMatcher.php @@ -13,6 +13,7 @@ use Okapi\CodeTransformer\Transformer; use Okapi\Path\Path; use Okapi\Wildcards\Regex; +use RuntimeException; /** * # Transformer Matcher @@ -34,7 +35,7 @@ class TransformerMatcher /** * Cache for the query result of the transformer matching. * - * @var array + * @var array */ private array $matchedTransformerContainers = []; @@ -62,10 +63,11 @@ public function matchAndStore(string $namespacedClass, string $filePath): bool // Check if the transformer has already been matched $alreadyMatched = array_reduce( $matchedTransformerContainers, - function (bool $carry, TransformerContainer $container) use ($transformerContainer) { - return $carry || $container === $transformerContainer; - }, - false, + static fn(bool $carry, TransformerContainer $container) => ( + $carry + || $container === $transformerContainer + ), + initial: false, ); if ($alreadyMatched) { @@ -91,6 +93,10 @@ function (bool $carry, TransformerContainer $container) use ($transformerContain 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, diff --git a/src/Core/Options.php b/src/Core/Options.php index 3c8b70a..d6b038c 100644 --- a/src/Core/Options.php +++ b/src/Core/Options.php @@ -3,10 +3,12 @@ namespace Okapi\CodeTransformer\Core; use Composer\Autoload\ClassLoader; +use LogicException; use Okapi\CodeTransformer\CodeTransformerKernel; use Okapi\CodeTransformer\Core\Options\Environment; use Okapi\Path\Path; use ReflectionClass; +use RuntimeException; /** * # Options @@ -35,7 +37,7 @@ class Options implements ServiceInterface /** * The exclude paths. * - * @var array + * @var string[] */ private array $excludePaths; @@ -80,6 +82,7 @@ class Options implements ServiceInterface * @param int|null $cacheFileMode * @param bool $debug * @param Environment $environment + * @param string[] $excludePaths */ public function setOptions( ?string $cacheDir, @@ -90,11 +93,18 @@ public function setOptions( ): void { $composerRef = new ReflectionClass(ClassLoader::class); $composerDir = $composerRef->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 ?? 0777 & ~umask(); + $this->cacheFileMode = $cacheFileMode ?? 0o777 & ~umask(); $this->debug = $debug; $this->environment = $environment; $this->excludePaths = $excludePaths; @@ -132,6 +142,8 @@ public function getCacheDir(): string /** * Get the exclude paths. + * + * @return string[] */ public function getExcludePaths(): array { diff --git a/src/Core/Processor/TransformerProcessor.php b/src/Core/Processor/TransformerProcessor.php index 0345075..08d2933 100644 --- a/src/Core/Processor/TransformerProcessor.php +++ b/src/Core/Processor/TransformerProcessor.php @@ -4,6 +4,7 @@ namespace Okapi\CodeTransformer\Core\Processor; use DI\Attribute\Inject; +use LogicException; use Okapi\CodeTransformer\Core\Cache\CachePaths; use Okapi\CodeTransformer\Core\Cache\CacheState; use Okapi\CodeTransformer\Core\Cache\CacheState\NoTransformationsCacheState; @@ -62,28 +63,21 @@ public function transform(Metadata $metadata): void // 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) { - $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, - ], - ]); + $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); } @@ -98,9 +92,12 @@ public function transform(Metadata $metadata): 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; - }); + usort( + $transformerContainers, + static fn(TransformerContainer $a, TransformerContainer $b) => ( + $a->transformerInstance->order <=> $b->transformerInstance->order + ), + ); foreach ($transformerContainers as $transformerContainer) { $transformerContainer->transformerInstance->transform($metadata->code); @@ -119,10 +116,15 @@ protected function processTransformers(Metadata $metadata, array $transformerCon protected function getTransformerFilePaths(array $transformerContainers): array { return array_map( - function (TransformerContainer $transformerContainer) { + static function (TransformerContainer $transformerContainer) { /** @noinspection PhpUnhandledExceptionInspection Handled by TransformerNotFoundException */ $reflection = new BaseReflectionClass($transformerContainer->transformerInstance); - return $reflection->getFileName(); + $file = $reflection->getFileName(); + if ($file === false) { + throw new LogicException('A transformer must have a source file.'); + } + + return $file; }, $transformerContainers, ); diff --git a/src/Core/StreamFilter.php b/src/Core/StreamFilter.php index ef526cf..4201251 100644 --- a/src/Core/StreamFilter.php +++ b/src/Core/StreamFilter.php @@ -2,6 +2,7 @@ namespace Okapi\CodeTransformer\Core; +use Okapi\CodeTransformer\Core\Exception\StreamFilter\InvalidStreamException; use Okapi\CodeTransformer\Core\Processor\TransformerProcessor; use Okapi\CodeTransformer\Core\StreamFilter\Metadata; use php_user_filter as PhpStreamFilter; @@ -50,13 +51,23 @@ public function register(): void */ public function filter($in, $out, &$consumed, bool $closing): int { + /** @var mixed $stream */ + $stream = $this->stream; + if (!is_resource($stream)) { + throw new InvalidStreamException(); + } + // Read the stream until EOF - while ($bucket = stream_bucket_make_writeable($in)) { + 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($this->stream)) { + if ($closing || feof($stream)) { $consumed = strlen($this->data); // Store the metadata @@ -72,7 +83,7 @@ public function filter($in, $out, &$consumed, bool $closing): int // Set the new source code $source = $metadata->code->getNewSource(); - $bucket = stream_bucket_new($this->stream, $source); + $bucket = stream_bucket_new($stream, $source); stream_bucket_append($out, $bucket); // Pass the (transformed) source code to the next filter diff --git a/src/Core/StreamFilter/Metadata.php b/src/Core/StreamFilter/Metadata.php index 5716c4e..d112bf2 100644 --- a/src/Core/StreamFilter/Metadata.php +++ b/src/Core/StreamFilter/Metadata.php @@ -16,6 +16,9 @@ * It converts {@link stream_get_meta_data()} output into a more convenient * format. * + * The public fields mirror PHP stream metadata and remain available to transformers. + * + * @mago-expect lint:too-many-properties * @see https://www.php.net/manual/function.stream-get-meta-data.php */ class Metadata @@ -37,6 +40,7 @@ class Metadata public string $mode; public bool $seekable; public string $uri; + /** @var array|null */ public ?array $crypto; public ?string $mediatype; @@ -56,10 +60,21 @@ public function __construct(mixed $stream, string $originalSource) } // 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 - $metadata['uri'] = Path::resolve($matches[1]); + $uri = Path::resolve($matches[1]); + if (!is_string($uri)) { + throw new InvalidStreamException(); + } + + $metadata['uri'] = $uri; } $this->timed_out = $metadata['timed_out']; @@ -67,7 +82,7 @@ public function __construct(mixed $stream, string $originalSource) $this->eof = $metadata['eof']; $this->unread_bytes = $metadata['unread_bytes']; $this->stream_type = $metadata['stream_type']; - $this->wrapper_type = $metadata['wrapper_type']; + $this->wrapper_type = $metadata['wrapper_type'] ?? ''; $this->wrapper_data = $metadata['wrapper_data'] ?? null; $this->mode = $metadata['mode']; $this->seekable = $metadata['seekable']; diff --git a/src/Core/Util/CodeChecker.php b/src/Core/Util/CodeChecker.php index 4a35a76..f48b70d 100644 --- a/src/Core/Util/CodeChecker.php +++ b/src/Core/Util/CodeChecker.php @@ -17,11 +17,11 @@ class CodeChecker */ public function isValidPhpCode(string $code): void { - static $parser; - - if (!isset($parser)) { + static $parser = null; + if (!$parser instanceof Parser) { $parser = new Parser(); } + $sourceFileNode = $parser->parseSourceFile($code); $errors = DiagnosticsProvider::getDiagnostics($sourceFileNode); @@ -34,7 +34,9 @@ public function isValidPhpCode(string $code): void $error = new SyntaxError($e, $code, $error); } - throw $error; + if ($error !== null) { + throw $error; + } } } } diff --git a/src/Core/Util/StringMutator.php b/src/Core/Util/StringMutator.php index 21706d8..e3909b7 100644 --- a/src/Core/Util/StringMutator.php +++ b/src/Core/Util/StringMutator.php @@ -2,6 +2,8 @@ namespace Okapi\CodeTransformer\Core\Util; +use InvalidArgumentException; + /** * A utility class for mutating strings. * @@ -21,7 +23,7 @@ class StringMutator /** * The edits to apply to the string. * - * @var array{int, int, string}[] Start position, length, replacement + * @var list Start position, length, replacement */ public array $edits = []; @@ -46,7 +48,12 @@ public function __construct(string $string) */ 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; } @@ -58,9 +65,7 @@ public function edit(int $start, int $length, string $replacement): self public function getMutatedString(): string { // Sort the edits by start position. - usort($this->edits, function ($a, $b) { - return $a[0] <=> $b[0]; - }); + usort($this->edits, static fn($a, $b) => $a[0] <=> $b[0]); // Apply the edits. $result = $this->string; diff --git a/src/Transformer.php b/src/Transformer.php index 2b76c0f..1ccd779 100644 --- a/src/Transformer.php +++ b/src/Transformer.php @@ -27,7 +27,7 @@ abstract class Transformer * * Wildcards are supported. See Okapi/Wildcards for more information. * - * @return class-string|class-string[] + * @return string|string[] Class names or wildcard patterns. */ abstract public function getTargetClass(): string|array; diff --git a/src/Transformer/Code.php b/src/Transformer/Code.php index 7c7af62..75bc01c 100644 --- a/src/Transformer/Code.php +++ b/src/Transformer/Code.php @@ -39,7 +39,7 @@ class Code /** * List of strings to be appended to the source code. * - * @var array + * @var list */ private array $appendList = []; @@ -207,6 +207,7 @@ public function getNamespacedClass(): string */ public function getClassName(): string { - return substr($this->namespacedClass, strrpos($this->namespacedClass, '\\') + 1); + $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 0286232..fb22277 100644 --- a/src/functions.php +++ b/src/functions.php @@ -8,9 +8,9 @@ * but not with any of the provided negative needles. * * @param string $haystack The string to search in. - * @param array $needles An array of strings to search for at the + * @param string[] $needles An array of strings to search for at the * beginning of the $haystack. - * @param array $negativeNeedles An array of strings to ensure are not at + * @param string[] $negativeNeedles An array of strings to ensure are not at * the beginning of $haystack. * * @return bool Returns {@link true} if $haystack starts with any string in diff --git a/tests/ClassLoaderMockTrait.php b/tests/ClassLoaderMockTrait.php index 1121157..247077e 100644 --- a/tests/ClassLoaderMockTrait.php +++ b/tests/ClassLoaderMockTrait.php @@ -20,7 +20,10 @@ private function findClassMock(string $class): string $this->findClassLoader(); } - return $this->classLoader->findFile($class); + Assert::assertInstanceOf(ClassLoader::class, $this->classLoader); + $file = $this->classLoader->findFile($class); + Assert::assertIsString($file); + return $file; } private function findOriginalClassMock(string $class): string @@ -30,34 +33,43 @@ private function findOriginalClassMock(string $class): string } $original = new ReflectionProperty(ClassLoader::class, 'originalClassLoader'); - $original = $original->getValue($this->classLoader); - return $original->findFile($class); + 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) { - $this->classLoader = $function[0]; - break; + 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"); + 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; @@ -69,6 +81,7 @@ public function assertTransformerLoadedFromCache(string $className): void 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 719b3f2..c5c0598 100644 --- a/tests/Functional/Cache/CachedFileAndDestructor/CachedFileAndDestructorTest.php +++ b/tests/Functional/Cache/CachedFileAndDestructor/CachedFileAndDestructorTest.php @@ -25,13 +25,13 @@ public function testReplaceStringInClass(): void $class = StringClass::class; $this->assertWillBeTransformed($class); - $stringClass = new $class(); - $this->assertSame('Hello from Code Transformer!', $stringClass->test()); + $stringClass = new StringClass(); + static::assertSame('Hello from Code Transformer!', $stringClass->test()); $file = Util::getFilePath(StringClass::class); $content = Filesystem::readFile($file); - $this->assertEquals($content, StringTransformer::$originalSourceCode); + static::assertEquals($content, StringTransformer::$originalSourceCode); } public function testCachedReplaceStringClass(): void @@ -41,20 +41,20 @@ public function testCachedReplaceStringClass(): void $class = StringClass::class; $this->assertTransformerLoadedFromCache($class); - $stringClass = new $class(); - $this->assertSame('Hello from Code Transformer!', $stringClass->test()); + $stringClass = new StringClass(); + static::assertSame('Hello from Code Transformer!', $stringClass->test()); } public function testCachedFile(): void { $cachedFilePath = Util::getTransformedFilePath(StringClass::class); - $this->assertFileExists($cachedFilePath); + static::assertFileExists($cachedFilePath); $file = Filesystem::readFile($cachedFilePath); - $this->assertStringContainsString('Hello from Code Transformer!', $file); + static::assertStringContainsString('Hello from Code Transformer!', $file); - $this->assertStringContainsString('$iAmAppended = true;', $file); + static::assertStringContainsString('$iAmAppended = true;', $file); } public function testDestructor(): void @@ -63,18 +63,20 @@ public function testDestructor(): void Kernel::init(); $class = StringClass::class; - $stringClass = new $class(); + $stringClass = new StringClass(); $cacheStateManager = DI::get(CacheStateManager::class); - $this->assertFileDoesNotExist(Util::CACHE_STATES_FILE); + static::assertFileDoesNotExist(Util::CACHE_STATES_FILE); $cacheStateManager->__destruct(); - $this->assertFileExists(Util::CACHE_STATES_FILE); + 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); - $this->assertArrayHasKey($key, $file); + static::assertArrayHasKey($key, $file); } } diff --git a/tests/Functional/Cache/CachedFileAndDestructor/Transformer/StringTransformer.php b/tests/Functional/Cache/CachedFileAndDestructor/Transformer/StringTransformer.php index 00f235b..14ea17e 100644 --- a/tests/Functional/Cache/CachedFileAndDestructor/Transformer/StringTransformer.php +++ b/tests/Functional/Cache/CachedFileAndDestructor/Transformer/StringTransformer.php @@ -21,14 +21,18 @@ 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 && $node->getStringContentsText() === 'Hello World!') { - // Replace it with 'Hello from Code Transformer!' - $code->edit($node->children, "'Hello from Code Transformer!'"); - - $code->append('$iAmAppended = true;'); + 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 bbce738..9e7a5c5 100644 --- a/tests/Functional/Cache/DeleteCacheFile/DeleteCacheFileTest.php +++ b/tests/Functional/Cache/DeleteCacheFile/DeleteCacheFileTest.php @@ -21,8 +21,8 @@ public function testDeleteCacheFileClass(): void $class = Target::class; $this->assertWillBeTransformed($class); - $deleteCacheFileClass = new $class(); - $this->assertSame('Hello World!', $deleteCacheFileClass->test()); + $deleteCacheFileClass = new Target(); + static::assertSame('Hello World!', $deleteCacheFileClass->test()); } public function testCachedDeleteCacheFileClass(): void @@ -31,16 +31,16 @@ public function testCachedDeleteCacheFileClass(): void $cachedFilePath = Util::getTransformedFilePath(Target::class); - $this->assertFileExists($cachedFilePath); + static::assertFileExists($cachedFilePath); Filesystem::rm($cachedFilePath); - $this->assertFileDoesNotExist($cachedFilePath); + static::assertFileDoesNotExist($cachedFilePath); $class = Target::class; $this->assertWillBeTransformed($class); - $deleteCacheFileClass = new $class(); - $this->assertSame('Hello World!', $deleteCacheFileClass->test()); + $deleteCacheFileClass = new Target(); + static::assertSame('Hello World!', $deleteCacheFileClass->test()); - $this->assertFileExists($cachedFilePath); + static::assertFileExists($cachedFilePath); } } diff --git a/tests/Functional/Kernel/AddedTransformer/AddedTransformerTest.php b/tests/Functional/Kernel/AddedTransformer/AddedTransformerTest.php index c126967..34c5ff6 100644 --- a/tests/Functional/Kernel/AddedTransformer/AddedTransformerTest.php +++ b/tests/Functional/Kernel/AddedTransformer/AddedTransformerTest.php @@ -22,9 +22,9 @@ public function testAddedTransformer(): void $class = Target::class; $this->assertWillBeTransformed($class); - $addedTransformerClass = new $class(); + $addedTransformerClass = new Target(); - $this->assertSame('Hello Code Transformer!', $addedTransformerClass->test()); + static::assertSame('Hello Code Transformer!', $addedTransformerClass->test()); } public function testCachedAddedTransformer(): void @@ -34,7 +34,7 @@ public function testCachedAddedTransformer(): void $class = Target::class; $this->assertWillBeTransformed($class); - $addedTransformerClass = new $class(); - $this->assertSame('Hello from Code Transformer!', $addedTransformerClass->test()); + $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 a448b9f..f86bad7 100644 --- a/tests/Functional/Kernel/AddedTransformer/Kernel/AddedTransformerKernel.php +++ b/tests/Functional/Kernel/AddedTransformer/Kernel/AddedTransformerKernel.php @@ -6,6 +6,7 @@ class AddedTransformerKernel extends BeforeAddedTransformerKernel { + /** @var array */ protected array $addedTransformers = [ AddedTransformer2::class, ]; diff --git a/tests/Functional/Kernel/AddedTransformer/Target.php b/tests/Functional/Kernel/AddedTransformer/Target.php index e5f61fc..ec9406d 100644 --- a/tests/Functional/Kernel/AddedTransformer/Target.php +++ b/tests/Functional/Kernel/AddedTransformer/Target.php @@ -9,6 +9,6 @@ public function test(): string $hello = 'Hello'; $world = 'World'; - return "$hello $world!"; + return "{$hello} {$world}!"; } } diff --git a/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer1.php b/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer1.php index fd931f9..90e73e7 100644 --- a/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer1.php +++ b/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer1.php @@ -10,6 +10,7 @@ use Okapi\CodeTransformer\Tests\Functional\Kernel\AddedTransformer\Target; use Okapi\CodeTransformer\Transformer; use Okapi\CodeTransformer\Transformer\Code; +use PHPUnit\Framework\Assert; class AddedTransformer1 extends Transformer { @@ -22,22 +23,27 @@ public function transform(Code $code): void { $sourceFileNode = $code->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); + /** @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', - ); - } + 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 9462edf..265657a 100644 --- a/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer2.php +++ b/tests/Functional/Kernel/AddedTransformer/Transformer/AddedTransformer2.php @@ -9,6 +9,7 @@ use Okapi\CodeTransformer\Tests\Functional\Kernel\AddedTransformer\Target; use Okapi\CodeTransformer\Transformer; use Okapi\CodeTransformer\Transformer\Code; +use PHPUnit\Framework\Assert; class AddedTransformer2 extends Transformer { @@ -21,18 +22,27 @@ public function transform(Code $code): void { $sourceFileNode = $code->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); + /** @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'); - } + 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/CustomDependencyInjectionHandler/CustomDependencyInjectionHandlerTest.php b/tests/Functional/Kernel/CustomDependencyInjectionHandler/CustomDependencyInjectionHandlerTest.php index 1e40002..556f334 100644 --- a/tests/Functional/Kernel/CustomDependencyInjectionHandler/CustomDependencyInjectionHandlerTest.php +++ b/tests/Functional/Kernel/CustomDependencyInjectionHandler/CustomDependencyInjectionHandlerTest.php @@ -23,11 +23,12 @@ public function testCustomDependencyInjectionHandler(): void Kernel::init(); $output = ob_get_clean(); + static::assertIsString($output); - $this->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/Environment/EnvironmentTest.php b/tests/Functional/Kernel/Environment/EnvironmentTest.php index 4d14b48..eca9058 100644 --- a/tests/Functional/Kernel/Environment/EnvironmentTest.php +++ b/tests/Functional/Kernel/Environment/EnvironmentTest.php @@ -29,9 +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()); } /** @@ -44,9 +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()); } /** @@ -70,8 +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; } @@ -96,9 +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()); } /** @@ -111,9 +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()); } /** @@ -137,8 +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 70ae918..f7d11eb 100644 --- a/tests/Functional/Kernel/Environment/Transformer/StringTransformer.php +++ b/tests/Functional/Kernel/Environment/Transformer/StringTransformer.php @@ -18,16 +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 bc21d5d..e3017dc 100644 --- a/tests/Functional/Kernel/KernelTest.php +++ b/tests/Functional/Kernel/KernelTest.php @@ -14,19 +14,19 @@ public function testKernel(): void { Util::clearCache(); - $this->assertFalse(EmptyKernel::isInitialized()); + static::assertFalse(EmptyKernel::isInitialized()); EmptyKernel::init(); - $this->assertTrue(EmptyKernel::isInitialized()); + static::assertTrue(EmptyKernel::isInitialized()); - $this->assertFileDoesNotExist(Util::CACHE_STATES_FILE); + static::assertFileDoesNotExist(Util::CACHE_STATES_FILE); } public function testCachedKernel(): void { - $this->assertFalse(EmptyKernel::isInitialized()); + static::assertFalse(EmptyKernel::isInitialized()); EmptyKernel::init(); - $this->assertTrue(EmptyKernel::isInitialized()); + static::assertTrue(EmptyKernel::isInitialized()); - $this->assertFileExists(Util::CACHE_STATES_FILE); + static::assertFileExists(Util::CACHE_STATES_FILE); } } diff --git a/tests/Functional/Target/ChangedClass/ChangedClassTest.php b/tests/Functional/Target/ChangedClass/ChangedClassTest.php index c86f749..92d3572 100644 --- a/tests/Functional/Target/ChangedClass/ChangedClassTest.php +++ b/tests/Functional/Target/ChangedClass/ChangedClassTest.php @@ -14,8 +14,6 @@ class ChangedClassTest extends TestCase { use ClassLoaderMockTrait; - private static string $classFileContent; - public function testChangedClass(): void { Util::clearCache(); @@ -24,8 +22,8 @@ public function testChangedClass(): void $class = Target::class; $this->assertWillBeTransformed($class); - $changedClass = new $class(); - $this->assertSame('Hello World from Code Transformer!', $changedClass->test()); + $changedClass = new Target(); + static::assertSame('Hello World from Code Transformer!', $changedClass->test()); } public function testCachedChangedClass(): void @@ -46,8 +44,8 @@ public function testCachedChangedClass(): void $class = Target::class; $this->assertWillBeTransformed($class); - $classInstance = new $class(); - $this->assertSame('Hello Changed World from Code Transformer!', $classInstance->test()); + $classInstance = new Target(); + static::assertSame('Hello Changed World from Code Transformer!', $classInstance->test()); } catch (Throwable $e) { $exception = $e; } diff --git a/tests/Functional/Target/ChangedClass/Transformer.php b/tests/Functional/Target/ChangedClass/Transformer.php index 00b13ca..6729afe 100644 --- a/tests/Functional/Target/ChangedClass/Transformer.php +++ b/tests/Functional/Target/ChangedClass/Transformer.php @@ -17,16 +17,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 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!'"); - } + 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 ea7bf5c..6716320 100644 --- a/tests/Functional/Target/NoChanges/NoChangesTest.php +++ b/tests/Functional/Target/NoChanges/NoChangesTest.php @@ -20,7 +20,7 @@ public function testNoChangesClass(): void $class = Target::class; $this->assertWillBeTransformed($class); - new $class(); + new Target(); } public function testCachedNoChangesClass(): void @@ -30,11 +30,11 @@ public function testCachedNoChangesClass(): void $class = Target::class; $this->assertTransformerNotApplied($class); - new $class(); + new Target(); $originalFilePath = Util::getFilePath(Target::class); $cachedFilePath = Util::getTransformedFilePath(Target::class); - $this->assertFileExists($originalFilePath); - $this->assertFileDoesNotExist($cachedFilePath); + static::assertFileExists($originalFilePath); + static::assertFileDoesNotExist($cachedFilePath); } } diff --git a/tests/Functional/Transformer/InvalidTransformerClass/InvalidTransformer.php b/tests/Functional/Transformer/InvalidTransformerClass/InvalidTransformer.php index 0e4c89c..e3cf564 100644 --- a/tests/Functional/Transformer/InvalidTransformerClass/InvalidTransformer.php +++ b/tests/Functional/Transformer/InvalidTransformerClass/InvalidTransformer.php @@ -7,6 +7,7 @@ class InvalidTransformer { + /** @return string|string[] */ public function getTargetClass(): string|array { return StringClass::class; diff --git a/tests/Functional/Transformer/MultipleTransformer/MultipleTransformersTest.php b/tests/Functional/Transformer/MultipleTransformer/MultipleTransformersTest.php index c7c28d8..47d32e9 100644 --- a/tests/Functional/Transformer/MultipleTransformer/MultipleTransformersTest.php +++ b/tests/Functional/Transformer/MultipleTransformer/MultipleTransformersTest.php @@ -6,6 +6,8 @@ use Okapi\CodeTransformer\Tests\Util; use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses; use PHPUnit\Framework\TestCase; +use ReflectionMethod; +use ReflectionProperty; #[RunTestsInSeparateProcesses] class MultipleTransformersTest extends TestCase @@ -20,11 +22,9 @@ public function testMultipleTransformers(): void $class = TargetClass::class; $this->assertWillBeTransformed($class); - $multipleTransformersClass = new $class(); + $multipleTransformersClass = new TargetClass(); - $this->assertSame('Hello from Code Transformer!', $multipleTransformersClass->test()); - - $this->assertSame("You can't get me!", $multipleTransformersClass->privateProperty); + $this->assertTransformedMembers($multipleTransformersClass); } public function testCachedMultipleTransformers(): void @@ -34,10 +34,20 @@ public function testCachedMultipleTransformers(): void $class = TargetClass::class; $this->assertTransformerLoadedFromCache($class); - $multipleTransformersClass = new $class(); + $multipleTransformersClass = new TargetClass(); - $this->assertSame('Hello from Code Transformer!', $multipleTransformersClass->test()); + $this->assertTransformedMembers($multipleTransformersClass); + } - $this->assertSame("You can't get me!", $multipleTransformersClass->privateProperty); + 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 d44b819..d8e3356 100644 --- a/tests/Functional/Transformer/MultipleTransformer/TargetClass.php +++ b/tests/Functional/Transformer/MultipleTransformer/TargetClass.php @@ -7,6 +7,12 @@ class TargetClass { private string $privateProperty = "You can't get me!"; + /** @return array{string, string} */ + public function snapshot(): array + { + return [$this->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 472399f..b63119f 100644 --- a/tests/Functional/Transformer/MultipleTransformer/Transformer/UnPrivateTransformer.php +++ b/tests/Functional/Transformer/MultipleTransformer/Transformer/UnPrivateTransformer.php @@ -18,10 +18,14 @@ public function transform(Code $code): void { $sourceFileNode = $code->getSourceFileNode(); - foreach ($sourceFileNode->getDescendantTokens() as $token) { - if ($token->kind === TokenKind::PrivateKeyword) { - $code->edit($token, 'public'); + /** @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/Transformer.php b/tests/Functional/Transformer/SyntaxErrorInTransformedClass/Transformer.php index 8576333..d5c4d3b 100644 --- a/tests/Functional/Transformer/SyntaxErrorInTransformedClass/Transformer.php +++ b/tests/Functional/Transformer/SyntaxErrorInTransformedClass/Transformer.php @@ -4,6 +4,7 @@ use Okapi\CodeTransformer\Transformer as TransformerClass; use Okapi\CodeTransformer\Transformer\Code; +use PHPUnit\Framework\Assert; class Transformer extends TransformerClass { @@ -17,9 +18,9 @@ public function transform(Code $code): void $code->append('}'); $refClass = $code->getReflectionClass(); - assert($refClass->getName() === Target::class); + Assert::assertSame(Target::class, $refClass->getName(), 'The reflected member must match this fixture.'); $className = $code->getNewSource(); - assert($className === 'SyntaxErrorClass'); + 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'); + } +} From 515012386ccc1c55fc8a360393a513918ed9a09b Mon Sep 17 00:00:00 2001 From: WalterWoshid Date: Fri, 13 Nov 2026 23:31:39 +0100 Subject: [PATCH 6/6] chore: forbid native assertions in Mago --- mago.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/mago.toml b/mago.toml index ec31e2d..0222421 100644 --- a/mago.toml +++ b/mago.toml @@ -8,6 +8,11 @@ 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