AbstractFixerWithAliasedOptionsTestCase.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 $fixerWithAliasedConfig;
  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. if (!$this->fixerWithAliasedConfig instanceof AbstractFixer) {
  41. throw new \LogicException();
  42. }
  43. $fixer = $this->fixer;
  44. $fixerWithAliasedConfig = $this->fixerWithAliasedConfig;
  45. $this->fixer = $fixerWithAliasedConfig;
  46. $this->fixerWithAliasedConfig = null;
  47. $this->doTest($expected, $input, $file);
  48. $this->fixerWithAliasedConfig = $fixerWithAliasedConfig;
  49. $this->fixer = $fixer;
  50. }
  51. }
  52. /**
  53. * @param array<string, mixed> $configuration
  54. */
  55. protected function configureFixerWithAliasedOptions(array $configuration): void
  56. {
  57. if (!$this->fixer instanceof ConfigurableFixerInterface) {
  58. throw new \LogicException('Fixer is not configurable.');
  59. }
  60. $this->fixer->configure($configuration);
  61. $options = $this->fixer->getConfigurationDefinition()->getOptions();
  62. $hasAliasedOptions = false;
  63. foreach ($options as $option) {
  64. if (!$option instanceof AliasedFixerOption) {
  65. continue;
  66. }
  67. $hasAliasedOptions = true;
  68. $alias = $option->getAlias();
  69. if (\array_key_exists($alias, $configuration)) {
  70. $configuration[$option->getName()] = $configuration[$alias];
  71. unset($configuration[$alias]);
  72. }
  73. }
  74. if (!$hasAliasedOptions) {
  75. throw new \LogicException('Fixer has no aliased options.');
  76. }
  77. $this->fixerWithAliasedConfig = clone $this->fixer;
  78. $this->fixerWithAliasedConfig->configure($configuration);
  79. }
  80. }