AbstractFixerWithAliasedOptionsTestCase.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Tests\Test;
  13. use PhpCsFixer\AbstractFixer;
  14. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  15. use PhpCsFixer\FixerConfiguration\AliasedFixerOption;
  16. /**
  17. * @author ntzm
  18. *
  19. * @internal
  20. */
  21. abstract class AbstractFixerWithAliasedOptionsTestCase extends AbstractFixerTestCase
  22. {
  23. /**
  24. * @var null|\PhpCsFixer\Fixer\ConfigurableFixerInterface
  25. */
  26. private $fixerWithAliasedConfig;
  27. protected function tearDown(): void
  28. {
  29. parent::tearDown();
  30. $this->fixerWithAliasedConfig = null;
  31. }
  32. protected function doTest(string $expected, ?string $input = null, ?\SplFileInfo $file = null): void
  33. {
  34. parent::doTest($expected, $input, $file);
  35. if (null !== $this->fixerWithAliasedConfig) {
  36. if (!$this->fixerWithAliasedConfig instanceof AbstractFixer) {
  37. throw new \LogicException();
  38. }
  39. $fixer = $this->fixer;
  40. $fixerWithAliasedConfig = $this->fixerWithAliasedConfig;
  41. $this->fixer = $fixerWithAliasedConfig;
  42. $this->fixerWithAliasedConfig = null;
  43. $this->doTest($expected, $input, $file);
  44. $this->fixerWithAliasedConfig = $fixerWithAliasedConfig;
  45. $this->fixer = $fixer;
  46. }
  47. }
  48. /**
  49. * @param array<string, mixed> $configuration
  50. */
  51. protected function configureFixerWithAliasedOptions(array $configuration): void
  52. {
  53. if (!$this->fixer instanceof ConfigurableFixerInterface) {
  54. throw new \LogicException('Fixer is not configurable.');
  55. }
  56. $this->fixer->configure($configuration);
  57. $options = $this->fixer->getConfigurationDefinition()->getOptions();
  58. $hasAliasedOptions = false;
  59. foreach ($options as $option) {
  60. if (!$option instanceof AliasedFixerOption) {
  61. continue;
  62. }
  63. $hasAliasedOptions = true;
  64. $alias = $option->getAlias();
  65. if (\array_key_exists($alias, $configuration)) {
  66. $configuration[$option->getName()] = $configuration[$alias];
  67. unset($configuration[$alias]);
  68. }
  69. }
  70. if (!$hasAliasedOptions) {
  71. throw new \LogicException('Fixer has no aliased options.');
  72. }
  73. $this->fixerWithAliasedConfig = clone $this->fixer;
  74. $this->fixerWithAliasedConfig->configure($configuration);
  75. }
  76. }