InteractsWithInject.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace think\annotation;
  3. use ReflectionObject;
  4. use think\App;
  5. /**
  6. * Trait InteractsWithInject
  7. * @package think\annotation\traits
  8. * @property App $app
  9. */
  10. trait InteractsWithInject
  11. {
  12. protected function autoInject()
  13. {
  14. if ($this->app->config->get('annotation.inject.enable', true)) {
  15. $this->app->resolving(function ($object, $app) {
  16. if ($this->isInjectClass(get_class($object))) {
  17. $refObject = new ReflectionObject($object);
  18. foreach ($refObject->getProperties() as $refProperty) {
  19. if ($refProperty->isDefault() && !$refProperty->isStatic()) {
  20. $attrs = $refProperty->getAttributes(Inject::class);
  21. if (!empty($attrs)) {
  22. if (!empty($attrs[0]->getArguments()[0])) {
  23. $type = $attrs[0]->getArguments()[0];
  24. } elseif ($refProperty->getType() && !$refProperty->getType()->isBuiltin()) {
  25. $type = $refProperty->getType()->getName();
  26. }
  27. if (isset($type)) {
  28. $value = $app->make($type);
  29. if (!$refProperty->isPublic()) {
  30. $refProperty->setAccessible(true);
  31. }
  32. $refProperty->setValue($object, $value);
  33. }
  34. }
  35. }
  36. }
  37. if ($refObject->hasMethod('__injected')) {
  38. $app->invokeMethod([$object, '__injected']);
  39. }
  40. }
  41. });
  42. }
  43. }
  44. protected function isInjectClass($name)
  45. {
  46. $namespaces = ['app\\'] + $this->app->config->get('annotation.inject.namespaces', []);
  47. foreach ($namespaces as $namespace) {
  48. $namespace = rtrim($namespace, '\\') . '\\';
  49. if (0 === stripos(rtrim($name, '\\') . '\\', $namespace)) {
  50. return true;
  51. }
  52. }
  53. }
  54. }