Completed
Push — 8.x-3.x ( 213280...6dfa31 )
by Sebastian
04:12 queued 02:05
created

Route::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 4
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\graphql_core\Plugin\GraphQL\Fields\Routing;
4
5
use Drupal\Component\Utility\UrlHelper;
6
use Drupal\Core\Path\PathValidatorInterface;
7
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
8
use Drupal\Core\Url;
9
use Drupal\graphql\GraphQL\Cache\CacheableValue;
10
use Drupal\graphql\GraphQL\Execution\ResolveContext;
11
use Drupal\graphql\Plugin\GraphQL\Fields\FieldPluginBase;
12
use GraphQL\Type\Definition\ResolveInfo;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
15
/**
16
 * Retrieve a route object based on a path.
17
 *
18
 * @GraphQLField(
19
 *   id = "url_route",
20
 *   secure = true,
21
 *   name = "route",
22
 *   description = @Translation("Loads a route by its path."),
23
 *   type = "Url",
24
 *   arguments = {
25
 *     "path" = "String!"
26
 *   }
27
 * )
28
 */
29
class Route extends FieldPluginBase implements ContainerFactoryPluginInterface {
30
31
  /**
32
   * The path validator service.
33
   *
34
   * @var \Drupal\Core\Path\PathValidatorInterface
35
   */
36
  protected $pathValidator;
37
38
  /**
39
   * {@inheritdoc}
40
   */
41
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
42
    return new static(
43
      $configuration,
44
      $plugin_id,
45
      $plugin_definition,
46
      $container->get('path.validator')
47
    );
48
  }
49
50
  /**
51
   * Route constructor.
52
   *
53
   * @param array $configuration
54
   *   The plugin configuration.
55
   * @param string $pluginId
56
   *   The plugin id.
57
   * @param mixed $pluginDefinition
58
   *   The plugin definition.
59
   * @param \Drupal\Core\Path\PathValidatorInterface $pathValidator
60
   *   The path validator service.
61
   */
62
  public function __construct(array $configuration, $pluginId, $pluginDefinition, PathValidatorInterface $pathValidator) {
63
    parent::__construct($configuration, $pluginId, $pluginDefinition);
64
    $this->pathValidator = $pathValidator;
65
  }
66
67
  /**
68
   * {@inheritdoc}
69
   */
70
  public function resolveValues($value, array $args, ResolveContext $context, ResolveInfo $info) {
71
    if (($url = $this->pathValidator->getUrlIfValidWithoutAccessCheck($args['path'])) && $url->access()) {
72
      yield $url;
73
    }
74
    else {
75
      yield (new CacheableValue(NULL))->addCacheTags(['4xx-response']);
76
    }
77
  }
78
79
}
80