AutowireRequiredMethodsPass.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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\DependencyInjection\Compiler;
  11. use Symfony\Component\DependencyInjection\Definition;
  12. /**
  13. * Looks for definitions with autowiring enabled and registers their corresponding "@required" methods as setters.
  14. *
  15. * @author Nicolas Grekas <p@tchwork.com>
  16. */
  17. class AutowireRequiredMethodsPass extends AbstractRecursivePass
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. protected function processValue($value, $isRoot = false)
  23. {
  24. $value = parent::processValue($value, $isRoot);
  25. if (!$value instanceof Definition || !$value->isAutowired() || $value->isAbstract() || !$value->getClass()) {
  26. return $value;
  27. }
  28. if (!$reflectionClass = $this->container->getReflectionClass($value->getClass(), false)) {
  29. return $value;
  30. }
  31. $alreadyCalledMethods = array();
  32. foreach ($value->getMethodCalls() as list($method)) {
  33. $alreadyCalledMethods[strtolower($method)] = true;
  34. }
  35. foreach ($reflectionClass->getMethods() as $reflectionMethod) {
  36. $r = $reflectionMethod;
  37. if ($r->isConstructor() || isset($alreadyCalledMethods[strtolower($r->name)])) {
  38. continue;
  39. }
  40. while (true) {
  41. if (false !== $doc = $r->getDocComment()) {
  42. if (false !== stripos($doc, '@required') && preg_match('#(?:^/\*\*|\n\s*+\*)\s*+@required(?:\s|\*/$)#i', $doc)) {
  43. $value->addMethodCall($reflectionMethod->name);
  44. break;
  45. }
  46. if (false === stripos($doc, '@inheritdoc') || !preg_match('#(?:^/\*\*|\n\s*+\*)\s*+(?:\{@inheritdoc\}|@inheritdoc)(?:\s|\*/$)#i', $doc)) {
  47. break;
  48. }
  49. }
  50. try {
  51. $r = $r->getPrototype();
  52. } catch (\ReflectionException $e) {
  53. break; // method has no prototype
  54. }
  55. }
  56. }
  57. return $value;
  58. }
  59. }