DebugCommand.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Form\Command;
  11. use Symfony\Component\Console\Command\Command;
  12. use Symfony\Component\Console\Exception\InvalidArgumentException;
  13. use Symfony\Component\Console\Input\InputArgument;
  14. use Symfony\Component\Console\Input\InputInterface;
  15. use Symfony\Component\Console\Input\InputOption;
  16. use Symfony\Component\Console\Output\OutputInterface;
  17. use Symfony\Component\Console\Style\SymfonyStyle;
  18. use Symfony\Component\Form\Console\Helper\DescriptorHelper;
  19. use Symfony\Component\Form\Extension\Core\CoreExtension;
  20. use Symfony\Component\Form\FormRegistryInterface;
  21. use Symfony\Component\Form\FormTypeInterface;
  22. use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
  23. /**
  24. * A console command for retrieving information about form types.
  25. *
  26. * @author Yonel Ceruto <yonelceruto@gmail.com>
  27. */
  28. class DebugCommand extends Command
  29. {
  30. protected static $defaultName = 'debug:form';
  31. private $formRegistry;
  32. private $namespaces;
  33. private $types;
  34. private $extensions;
  35. private $guessers;
  36. private $fileLinkFormatter;
  37. public function __construct(FormRegistryInterface $formRegistry, array $namespaces = ['Symfony\Component\Form\Extension\Core\Type'], array $types = [], array $extensions = [], array $guessers = [], FileLinkFormatter $fileLinkFormatter = null)
  38. {
  39. parent::__construct();
  40. $this->formRegistry = $formRegistry;
  41. $this->namespaces = $namespaces;
  42. $this->types = $types;
  43. $this->extensions = $extensions;
  44. $this->guessers = $guessers;
  45. $this->fileLinkFormatter = $fileLinkFormatter;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. protected function configure()
  51. {
  52. $this
  53. ->setDefinition([
  54. new InputArgument('class', InputArgument::OPTIONAL, 'The form type class'),
  55. new InputArgument('option', InputArgument::OPTIONAL, 'The form type option'),
  56. new InputOption('show-deprecated', null, InputOption::VALUE_NONE, 'Display deprecated options in form types'),
  57. new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt or json)', 'txt'),
  58. ])
  59. ->setDescription('Display form type information')
  60. ->setHelp(<<<'EOF'
  61. The <info>%command.name%</info> command displays information about form types.
  62. <info>php %command.full_name%</info>
  63. The command lists all built-in types, services types, type extensions and
  64. guessers currently available.
  65. <info>php %command.full_name% Symfony\Component\Form\Extension\Core\Type\ChoiceType</info>
  66. <info>php %command.full_name% ChoiceType</info>
  67. The command lists all defined options that contains the given form type,
  68. as well as their parents and type extensions.
  69. <info>php %command.full_name% ChoiceType choice_value</info>
  70. Use the <info>--show-deprecated</info> option to display form types with
  71. deprecated options or the deprecated options of the given form type:
  72. <info>php %command.full_name% --show-deprecated</info>
  73. <info>php %command.full_name% ChoiceType --show-deprecated</info>
  74. The command displays the definition of the given option name.
  75. <info>php %command.full_name% --format=json</info>
  76. The command lists everything in a machine readable json format.
  77. EOF
  78. )
  79. ;
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. protected function execute(InputInterface $input, OutputInterface $output)
  85. {
  86. $io = new SymfonyStyle($input, $output);
  87. if (null === $class = $input->getArgument('class')) {
  88. $object = null;
  89. $options['core_types'] = $this->getCoreTypes();
  90. $options['service_types'] = array_values(array_diff($this->types, $options['core_types']));
  91. if ($input->getOption('show-deprecated')) {
  92. $options['core_types'] = $this->filterTypesByDeprecated($options['core_types']);
  93. $options['service_types'] = $this->filterTypesByDeprecated($options['service_types']);
  94. }
  95. $options['extensions'] = $this->extensions;
  96. $options['guessers'] = $this->guessers;
  97. foreach ($options as $k => $list) {
  98. sort($options[$k]);
  99. }
  100. } else {
  101. if (!class_exists($class) || !is_subclass_of($class, FormTypeInterface::class)) {
  102. $class = $this->getFqcnTypeClass($input, $io, $class);
  103. }
  104. $resolvedType = $this->formRegistry->getType($class);
  105. if ($option = $input->getArgument('option')) {
  106. $object = $resolvedType->getOptionsResolver();
  107. if (!$object->isDefined($option)) {
  108. $message = sprintf('Option "%s" is not defined in "%s".', $option, \get_class($resolvedType->getInnerType()));
  109. if ($alternatives = $this->findAlternatives($option, $object->getDefinedOptions())) {
  110. if (1 === \count($alternatives)) {
  111. $message .= "\n\nDid you mean this?\n ";
  112. } else {
  113. $message .= "\n\nDid you mean one of these?\n ";
  114. }
  115. $message .= implode("\n ", $alternatives);
  116. }
  117. throw new InvalidArgumentException($message);
  118. }
  119. $options['type'] = $resolvedType->getInnerType();
  120. $options['option'] = $option;
  121. } else {
  122. $object = $resolvedType;
  123. }
  124. }
  125. $helper = new DescriptorHelper($this->fileLinkFormatter);
  126. $options['format'] = $input->getOption('format');
  127. $options['show_deprecated'] = $input->getOption('show-deprecated');
  128. $helper->describe($io, $object, $options);
  129. return 0;
  130. }
  131. private function getFqcnTypeClass(InputInterface $input, SymfonyStyle $io, string $shortClassName): string
  132. {
  133. $classes = [];
  134. sort($this->namespaces);
  135. foreach ($this->namespaces as $namespace) {
  136. if (class_exists($fqcn = $namespace.'\\'.$shortClassName)) {
  137. $classes[] = $fqcn;
  138. } elseif (class_exists($fqcn = $namespace.'\\'.ucfirst($shortClassName))) {
  139. $classes[] = $fqcn;
  140. } elseif (class_exists($fqcn = $namespace.'\\'.ucfirst($shortClassName).'Type')) {
  141. $classes[] = $fqcn;
  142. } elseif ('type' === substr($shortClassName, -4) && class_exists($fqcn = $namespace.'\\'.ucfirst(substr($shortClassName, 0, -4).'Type'))) {
  143. $classes[] = $fqcn;
  144. }
  145. }
  146. if (0 === $count = \count($classes)) {
  147. $message = sprintf("Could not find type \"%s\" into the following namespaces:\n %s", $shortClassName, implode("\n ", $this->namespaces));
  148. $allTypes = array_merge($this->getCoreTypes(), $this->types);
  149. if ($alternatives = $this->findAlternatives($shortClassName, $allTypes)) {
  150. if (1 === \count($alternatives)) {
  151. $message .= "\n\nDid you mean this?\n ";
  152. } else {
  153. $message .= "\n\nDid you mean one of these?\n ";
  154. }
  155. $message .= implode("\n ", $alternatives);
  156. }
  157. throw new InvalidArgumentException($message);
  158. }
  159. if (1 === $count) {
  160. return $classes[0];
  161. }
  162. if (!$input->isInteractive()) {
  163. throw new InvalidArgumentException(sprintf("The type \"%s\" is ambiguous.\n\nDid you mean one of these?\n %s.", $shortClassName, implode("\n ", $classes)));
  164. }
  165. return $io->choice(sprintf("The type \"%s\" is ambiguous.\n\nSelect one of the following form types to display its information:", $shortClassName), $classes, $classes[0]);
  166. }
  167. private function getCoreTypes(): array
  168. {
  169. $coreExtension = new CoreExtension();
  170. $loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes');
  171. $loadTypesRefMethod->setAccessible(true);
  172. $coreTypes = $loadTypesRefMethod->invoke($coreExtension);
  173. $coreTypes = array_map(function (FormTypeInterface $type) { return \get_class($type); }, $coreTypes);
  174. sort($coreTypes);
  175. return $coreTypes;
  176. }
  177. private function filterTypesByDeprecated(array $types): array
  178. {
  179. $typesWithDeprecatedOptions = [];
  180. foreach ($types as $class) {
  181. $optionsResolver = $this->formRegistry->getType($class)->getOptionsResolver();
  182. foreach ($optionsResolver->getDefinedOptions() as $option) {
  183. if ($optionsResolver->isDeprecated($option)) {
  184. $typesWithDeprecatedOptions[] = $class;
  185. break;
  186. }
  187. }
  188. }
  189. return $typesWithDeprecatedOptions;
  190. }
  191. private function findAlternatives(string $name, array $collection): array
  192. {
  193. $alternatives = [];
  194. foreach ($collection as $item) {
  195. $lev = levenshtein($name, $item);
  196. if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) {
  197. $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
  198. }
  199. }
  200. $threshold = 1e3;
  201. $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; });
  202. ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE);
  203. return array_keys($alternatives);
  204. }
  205. }