Skip to content
Snippets Groups Projects

Add a trait for autowiring properties in tests

Open Michael Strelan requested to merge issue/drupal-3464357:3464357-autosetup into 11.x
1 unresolved thread

Closes #3464357

Merge request reports

Loading
Loading

Activity

Filter activity
  • Approvals
  • Assignees & reviewers
  • Comments (from bots)
  • Comments (from users)
  • Commits & branches
  • Edits
  • Labels
  • Lock status
  • Mentions
  • Merge request status
  • Tracking
  • 19 parent::setUp();
    20 $class = new \ReflectionClass($this);
    21 foreach ($class->getProperties() as $property) {
    22 if ($property->isInitialized($this) || !$property->hasType()) {
    23 continue;
    24 }
    25 $service = ltrim((string) $property->getType(), '?');
    26 foreach ($property->getAttributes(Autowire::class) as $attribute) {
    27 $service = (string) $attribute->newInstance()->value;
    28 }
    29
    30 if (!$this->container->has($service)) {
    31 throw new AutowiringFailedException($service, sprintf('Cannot autowire service "%s": property "$%s" of class "%s", you should configure its value explicitly.', $service, $property->getName(), static::class));
    32 }
    33
    34 $property->setValue($this, $this->container->get($service));
    • Comment on lines +25 to +34

      I think we should always explicitly require the autowire attribute in this case. Both for readibility, and because assuming that any typehinted property is a service instance seems a bit too much.

      Edited by mondrake
    • AFAIK the autowire attribute only works for constructor parameters. In this case we don't have a constructor. Perhaps we could have add a separate attribute for this however.

      Agree we shouldn't assume all properties are services, maybe we can just silently carry on if it's not found. The test will fail anyway in that case.

    • Please register or sign in to reply
  • added 1 commit

    • 5edef401 - Split up setup function to avoid calling parent::setup twice

    Compare with previous version

  • Please register or sign in to reply
    Loading