AbstractFixerWithAliasedOptionsTestCase.php 2.6 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. * @template TFixer of AbstractFixer
  22. *
  23. * @extends AbstractFixerTestCase<TFixer>
  24. */
  25. abstract class AbstractFixerWithAliasedOptionsTestCase extends AbstractFixerTestCase
  26. {
  27. /**
  28. * @var null|TFixer
  29. */
  30. private ?AbstractFixer $fixerWithAliasedConfig = null;
  31. protected function tearDown(): void
  32. {
  33. parent::tearDown();
  34. $this->fixerWithAliasedConfig = null;
  35. }
  36. protected function doTest(string $expected, ?string $input = null, ?\SplFileInfo $file = null): void
  37. {
  38. parent::doTest($expected, $input, $file);
  39. if (null !== $this->fixerWithAliasedConfig) {
  40. $fixer = $this->fixer;
  41. $fixerWithAliasedConfig = $this->fixerWithAliasedConfig;
  42. $this->fixer = $fixerWithAliasedConfig;
  43. $this->fixerWithAliasedConfig = null;
  44. $this->doTest($expected, $input, $file);
  45. $this->fixerWithAliasedConfig = $fixerWithAliasedConfig;
  46. $this->fixer = $fixer;
  47. }
  48. }
  49. /**
  50. * @param array<string, mixed> $configuration
  51. */
  52. protected function configureFixerWithAliasedOptions(array $configuration): void
  53. {
  54. if (!$this->fixer instanceof ConfigurableFixerInterface) {
  55. throw new \LogicException('Fixer is not configurable.');
  56. }
  57. $this->fixer->configure($configuration);
  58. $options = $this->fixer->getConfigurationDefinition()->getOptions();
  59. $hasAliasedOptions = false;
  60. foreach ($options as $option) {
  61. if (!$option instanceof AliasedFixerOption) {
  62. continue;
  63. }
  64. $hasAliasedOptions = true;
  65. $alias = $option->getAlias();
  66. if (\array_key_exists($alias, $configuration)) {
  67. $configuration[$option->getName()] = $configuration[$alias];
  68. unset($configuration[$alias]);
  69. }
  70. }
  71. if (!$hasAliasedOptions) {
  72. throw new \LogicException('Fixer has no aliased options.');
  73. }
  74. $this->fixerWithAliasedConfig = clone $this->fixer;
  75. $this->fixerWithAliasedConfig->configure($configuration);
  76. }
  77. }