|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace GrumPHP\Task; |
| 6 | + |
| 7 | +use GrumPHP\Formatter\ProcessFormatterInterface; |
| 8 | +use GrumPHP\Runner\TaskResult; |
| 9 | +use GrumPHP\Runner\TaskResultInterface; |
| 10 | +use GrumPHP\Task\Config\ConfigOptionsResolver; |
| 11 | +use GrumPHP\Task\Context\ContextInterface; |
| 12 | +use GrumPHP\Task\Context\GitPreCommitContext; |
| 13 | +use GrumPHP\Task\Context\RunContext; |
| 14 | +use Symfony\Component\OptionsResolver\OptionsResolver; |
| 15 | + |
| 16 | +/** |
| 17 | + * @extends AbstractExternalTask<ProcessFormatterInterface> |
| 18 | + */ |
| 19 | +class ComposerValidateAutoload extends AbstractExternalTask |
| 20 | +{ |
| 21 | + public function canRunInContext(ContextInterface $context): bool |
| 22 | + { |
| 23 | + return $context instanceof GitPreCommitContext || $context instanceof RunContext; |
| 24 | + } |
| 25 | + |
| 26 | + public static function getConfigurableOptions(): ConfigOptionsResolver |
| 27 | + { |
| 28 | + $resolver = new OptionsResolver(); |
| 29 | + $resolver->setDefaults([ |
| 30 | + 'file' => './composer.json', |
| 31 | + 'strict_ambiguous' => false, |
| 32 | + ]); |
| 33 | + |
| 34 | + $resolver->addAllowedTypes('file', ['string']); |
| 35 | + $resolver->addAllowedTypes('strict_ambiguous', ['bool']); |
| 36 | + |
| 37 | + return ConfigOptionsResolver::fromOptionsResolver($resolver); |
| 38 | + } |
| 39 | + |
| 40 | + public function run(ContextInterface $context): TaskResultInterface |
| 41 | + { |
| 42 | + $config = $this->getConfig()->getOptions(); |
| 43 | + $composerDir = pathinfo($config['file'], PATHINFO_DIRNAME); |
| 44 | + $composerFile = pathinfo($config['file'], PATHINFO_BASENAME); |
| 45 | + $files = $context->getFiles() |
| 46 | + ->path($composerDir) |
| 47 | + ->name($composerFile); |
| 48 | + if (0 === \count($files)) { |
| 49 | + return TaskResult::createSkipped($this, $context); |
| 50 | + } |
| 51 | + |
| 52 | + $config = $this->getConfig()->getOptions(); |
| 53 | + |
| 54 | + $arguments = $this->processBuilder->createArgumentsForCommand('composer'); |
| 55 | + $arguments->add('dump-autoload'); |
| 56 | + $arguments->add('--optimize'); |
| 57 | + $arguments->add('--dry-run'); |
| 58 | + $arguments->add('--strict-psr'); |
| 59 | + $arguments->addOptionalArgument('--strict-ambiguous', $config['strict_ambiguous']); |
| 60 | + |
| 61 | + $process = $this->processBuilder->buildProcess($arguments); |
| 62 | + $process->run(); |
| 63 | + |
| 64 | + if (!$process->isSuccessful()) { |
| 65 | + return TaskResult::createFailed($this, $context, $process->getErrorOutput()); |
| 66 | + } |
| 67 | + |
| 68 | + return TaskResult::createPassed($this, $context); |
| 69 | + } |
| 70 | +} |
0 commit comments