XPathToEntity::create()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
nop 4
1
<?php
2
3
namespace Drupal\graphql_xml\Plugin\GraphQL\Fields;
4
5
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
6
use Drupal\Core\Entity\EntityRepositoryInterface;
7
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
8
use Drupal\graphql\GraphQL\Execution\ResolveContext;
9
use GraphQL\Type\Definition\ResolveInfo;
10
use Symfony\Component\DependencyInjection\ContainerInterface;
11
12
/**
13
 * Extract entities from xpath values.
14
 *
15
 * @GraphQLField(
16
 *   id = "xml_xpath_entity",
17
 *   name = "xpathToEntity",
18
 *   secure = true,
19
 *   type = "Entity",
20
 *   parents = {"XMLElement"},
21
 *   multi = true,
22
 *   arguments = {
23
 *     "type" = "String",
24
 *     "query" = "String"
25
 *   }
26
 * )
27
 */
28
class XPathToEntity extends XMLXPath implements ContainerFactoryPluginInterface {
29
  use DependencySerializationTrait;
30
31
  /**
32
   * The entity repository service.
33
   *
34
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
35
   */
36
  protected $entityRepository;
37
38
  /**
39
   * {@inheritdoc}
40
   */
41
  public static function create(
42
    ContainerInterface $container,
43
    array $configuration,
44
    $pluginId,
45
    $pluginDefinition
46
  ) {
47
    return new static(
48
      $configuration,
49
      $pluginId,
50
      $pluginDefinition,
51
      $container->get('entity.repository')
52
    );
53
  }
54
55
  /**
56
   * {@inheritdoc}
57
   */
58
  public function __construct(
59
    array $configuration,
60
    $pluginId,
61
    $pluginDefinition,
62
    EntityRepositoryInterface $entityRepository
63
  ) {
64
    $this->entityRepository = $entityRepository;
65
    parent::__construct($configuration, $pluginId, $pluginDefinition);
66
  }
67
68
  /**
69
   * {@inheritdoc}
70
   */
71
  public function resolveValues($value, array $args, ResolveContext $context, ResolveInfo $info) {
72
    foreach (parent::resolveValues($value, $args, $context, $info) as $item) {
73
      /** @var \DOMElement $item */
74
      if ($entity = $this->entityRepository->loadEntityByUuid($args['type'], $item->textContent)) {
75
        if ($entity->access('view')) {
76
          yield $entity;
77
        }
78
      }
79
    }
80
  }
81
82
}
83