Descriptor.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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\Bundle\FrameworkBundle\Console\Descriptor;
  11. use Symfony\Component\Config\Resource\ClassExistenceResource;
  12. use Symfony\Component\Console\Descriptor\DescriptorInterface;
  13. use Symfony\Component\Console\Output\OutputInterface;
  14. use Symfony\Component\DependencyInjection\Alias;
  15. use Symfony\Component\DependencyInjection\ContainerBuilder;
  16. use Symfony\Component\DependencyInjection\ContainerInterface;
  17. use Symfony\Component\DependencyInjection\Definition;
  18. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  19. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  20. use Symfony\Component\Routing\Route;
  21. use Symfony\Component\Routing\RouteCollection;
  22. /**
  23. * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
  24. *
  25. * @internal
  26. */
  27. abstract class Descriptor implements DescriptorInterface
  28. {
  29. /**
  30. * @var OutputInterface
  31. */
  32. protected $output;
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function describe(OutputInterface $output, $object, array $options = [])
  37. {
  38. $this->output = $output;
  39. switch (true) {
  40. case $object instanceof RouteCollection:
  41. $this->describeRouteCollection($object, $options);
  42. break;
  43. case $object instanceof Route:
  44. $this->describeRoute($object, $options);
  45. break;
  46. case $object instanceof ParameterBag:
  47. $this->describeContainerParameters($object, $options);
  48. break;
  49. case $object instanceof ContainerBuilder && !empty($options['env-vars']):
  50. $this->describeContainerEnvVars($this->getContainerEnvVars($object), $options);
  51. break;
  52. case $object instanceof ContainerBuilder && isset($options['group_by']) && 'tags' === $options['group_by']:
  53. $this->describeContainerTags($object, $options);
  54. break;
  55. case $object instanceof ContainerBuilder && isset($options['id']):
  56. $this->describeContainerService($this->resolveServiceDefinition($object, $options['id']), $options, $object);
  57. break;
  58. case $object instanceof ContainerBuilder && isset($options['parameter']):
  59. $this->describeContainerParameter($object->resolveEnvPlaceholders($object->getParameter($options['parameter'])), $options);
  60. break;
  61. case $object instanceof ContainerBuilder && isset($options['deprecations']):
  62. $this->describeContainerDeprecations($object, $options);
  63. break;
  64. case $object instanceof ContainerBuilder:
  65. $this->describeContainerServices($object, $options);
  66. break;
  67. case $object instanceof Definition:
  68. $this->describeContainerDefinition($object, $options);
  69. break;
  70. case $object instanceof Alias:
  71. $this->describeContainerAlias($object, $options);
  72. break;
  73. case $object instanceof EventDispatcherInterface:
  74. $this->describeEventDispatcherListeners($object, $options);
  75. break;
  76. case \is_callable($object):
  77. $this->describeCallable($object, $options);
  78. break;
  79. default:
  80. throw new \InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object)));
  81. }
  82. }
  83. protected function getOutput(): OutputInterface
  84. {
  85. return $this->output;
  86. }
  87. protected function write(string $content, bool $decorated = false)
  88. {
  89. $this->output->write($content, false, $decorated ? OutputInterface::OUTPUT_NORMAL : OutputInterface::OUTPUT_RAW);
  90. }
  91. abstract protected function describeRouteCollection(RouteCollection $routes, array $options = []);
  92. abstract protected function describeRoute(Route $route, array $options = []);
  93. abstract protected function describeContainerParameters(ParameterBag $parameters, array $options = []);
  94. abstract protected function describeContainerTags(ContainerBuilder $builder, array $options = []);
  95. /**
  96. * Describes a container service by its name.
  97. *
  98. * Common options are:
  99. * * name: name of described service
  100. *
  101. * @param Definition|Alias|object $service
  102. */
  103. abstract protected function describeContainerService($service, array $options = [], ContainerBuilder $builder = null);
  104. /**
  105. * Describes container services.
  106. *
  107. * Common options are:
  108. * * tag: filters described services by given tag
  109. */
  110. abstract protected function describeContainerServices(ContainerBuilder $builder, array $options = []);
  111. abstract protected function describeContainerDeprecations(ContainerBuilder $builder, array $options = []): void;
  112. abstract protected function describeContainerDefinition(Definition $definition, array $options = []);
  113. abstract protected function describeContainerAlias(Alias $alias, array $options = [], ContainerBuilder $builder = null);
  114. abstract protected function describeContainerParameter($parameter, array $options = []);
  115. abstract protected function describeContainerEnvVars(array $envs, array $options = []);
  116. /**
  117. * Describes event dispatcher listeners.
  118. *
  119. * Common options are:
  120. * * name: name of listened event
  121. */
  122. abstract protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = []);
  123. /**
  124. * Describes a callable.
  125. *
  126. * @param mixed $callable
  127. */
  128. abstract protected function describeCallable($callable, array $options = []);
  129. /**
  130. * Formats a value as string.
  131. *
  132. * @param mixed $value
  133. */
  134. protected function formatValue($value): string
  135. {
  136. if (\is_object($value)) {
  137. return sprintf('object(%s)', \get_class($value));
  138. }
  139. if (\is_string($value)) {
  140. return $value;
  141. }
  142. return preg_replace("/\n\s*/s", '', var_export($value, true));
  143. }
  144. /**
  145. * Formats a parameter.
  146. *
  147. * @param mixed $value
  148. */
  149. protected function formatParameter($value): string
  150. {
  151. if (\is_bool($value) || \is_array($value) || (null === $value)) {
  152. $jsonString = json_encode($value);
  153. if (preg_match('/^(.{60})./us', $jsonString, $matches)) {
  154. return $matches[1].'...';
  155. }
  156. return $jsonString;
  157. }
  158. return (string) $value;
  159. }
  160. /**
  161. * @return mixed
  162. */
  163. protected function resolveServiceDefinition(ContainerBuilder $builder, string $serviceId)
  164. {
  165. if ($builder->hasDefinition($serviceId)) {
  166. return $builder->getDefinition($serviceId);
  167. }
  168. // Some service IDs don't have a Definition, they're aliases
  169. if ($builder->hasAlias($serviceId)) {
  170. return $builder->getAlias($serviceId);
  171. }
  172. if ('service_container' === $serviceId) {
  173. return (new Definition(ContainerInterface::class))->setPublic(true)->setSynthetic(true);
  174. }
  175. // the service has been injected in some special way, just return the service
  176. return $builder->get($serviceId);
  177. }
  178. protected function findDefinitionsByTag(ContainerBuilder $builder, bool $showHidden): array
  179. {
  180. $definitions = [];
  181. $tags = $builder->findTags();
  182. asort($tags);
  183. foreach ($tags as $tag) {
  184. foreach ($builder->findTaggedServiceIds($tag) as $serviceId => $attributes) {
  185. $definition = $this->resolveServiceDefinition($builder, $serviceId);
  186. if ($showHidden xor '.' === ($serviceId[0] ?? null)) {
  187. continue;
  188. }
  189. if (!isset($definitions[$tag])) {
  190. $definitions[$tag] = [];
  191. }
  192. $definitions[$tag][$serviceId] = $definition;
  193. }
  194. }
  195. return $definitions;
  196. }
  197. protected function sortParameters(ParameterBag $parameters)
  198. {
  199. $parameters = $parameters->all();
  200. ksort($parameters);
  201. return $parameters;
  202. }
  203. protected function sortServiceIds(array $serviceIds)
  204. {
  205. asort($serviceIds);
  206. return $serviceIds;
  207. }
  208. protected function sortTaggedServicesByPriority(array $services): array
  209. {
  210. $maxPriority = [];
  211. foreach ($services as $service => $tags) {
  212. $maxPriority[$service] = 0;
  213. foreach ($tags as $tag) {
  214. $currentPriority = $tag['priority'] ?? 0;
  215. if ($maxPriority[$service] < $currentPriority) {
  216. $maxPriority[$service] = $currentPriority;
  217. }
  218. }
  219. }
  220. uasort($maxPriority, function ($a, $b) {
  221. return $b <=> $a;
  222. });
  223. return array_keys($maxPriority);
  224. }
  225. protected function sortTagsByPriority(array $tags): array
  226. {
  227. $sortedTags = [];
  228. foreach ($tags as $tagName => $tag) {
  229. $sortedTags[$tagName] = $this->sortByPriority($tag);
  230. }
  231. return $sortedTags;
  232. }
  233. protected function sortByPriority(array $tag): array
  234. {
  235. usort($tag, function ($a, $b) {
  236. return ($b['priority'] ?? 0) <=> ($a['priority'] ?? 0);
  237. });
  238. return $tag;
  239. }
  240. public static function getClassDescription(string $class, string &$resolvedClass = null): string
  241. {
  242. $resolvedClass = $class;
  243. try {
  244. $resource = new ClassExistenceResource($class, false);
  245. // isFresh() will explode ONLY if a parent class/trait does not exist
  246. $resource->isFresh(0);
  247. $r = new \ReflectionClass($class);
  248. $resolvedClass = $r->name;
  249. if ($docComment = $r->getDocComment()) {
  250. $docComment = preg_split('#\n\s*\*\s*[\n@]#', substr($docComment, 3, -2), 2)[0];
  251. return trim(preg_replace('#\s*\n\s*\*\s*#', ' ', $docComment));
  252. }
  253. } catch (\ReflectionException $e) {
  254. }
  255. return '';
  256. }
  257. private function getContainerEnvVars(ContainerBuilder $container): array
  258. {
  259. if (!$container->hasParameter('debug.container.dump')) {
  260. return [];
  261. }
  262. if (!is_file($container->getParameter('debug.container.dump'))) {
  263. return [];
  264. }
  265. $file = file_get_contents($container->getParameter('debug.container.dump'));
  266. preg_match_all('{%env\(((?:\w++:)*+\w++)\)%}', $file, $envVars);
  267. $envVars = array_unique($envVars[1]);
  268. $bag = $container->getParameterBag();
  269. $getDefaultParameter = function (string $name) {
  270. return parent::get($name);
  271. };
  272. $getDefaultParameter = $getDefaultParameter->bindTo($bag, \get_class($bag));
  273. $getEnvReflection = new \ReflectionMethod($container, 'getEnv');
  274. $getEnvReflection->setAccessible(true);
  275. $envs = [];
  276. foreach ($envVars as $env) {
  277. $processor = 'string';
  278. if (false !== $i = strrpos($name = $env, ':')) {
  279. $name = substr($env, $i + 1);
  280. $processor = substr($env, 0, $i);
  281. }
  282. $defaultValue = ($hasDefault = $container->hasParameter("env($name)")) ? $getDefaultParameter("env($name)") : null;
  283. if (false === ($runtimeValue = $_ENV[$name] ?? $_SERVER[$name] ?? getenv($name))) {
  284. $runtimeValue = null;
  285. }
  286. $processedValue = ($hasRuntime = null !== $runtimeValue) || $hasDefault ? $getEnvReflection->invoke($container, $env) : null;
  287. $envs["$name$processor"] = [
  288. 'name' => $name,
  289. 'processor' => $processor,
  290. 'default_available' => $hasDefault,
  291. 'default_value' => $defaultValue,
  292. 'runtime_available' => $hasRuntime,
  293. 'runtime_value' => $runtimeValue,
  294. 'processed_value' => $processedValue,
  295. ];
  296. }
  297. ksort($envs);
  298. return array_values($envs);
  299. }
  300. }