Completed
Pull Request — 8.x-1.x (#35)
by
unknown
01:12
created

SubViewDeriver::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
1
<?php
2
3
namespace Drupal\graphql_views\Plugin\Deriver\Fields;
4
5
use Drupal\Component\Plugin\PluginManagerInterface;
6
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
7
use Drupal\Core\Entity\EntityTypeManagerInterface;
8
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
9
use Drupal\graphql\Utility\StringHelper;
10
use Drupal\graphql_views\Plugin\Deriver\ViewDeriverBase;
11
use Drupal\views\Views;
12
use Symfony\Component\DependencyInjection\ContainerInterface;
13
14
/**
15
 * Derive fields from configured views.
16
 */
17
class SubViewDeriver extends ViewDeriverBase implements ContainerDeriverInterface {
18
19
  protected $entityTypeBundleInfo;
20
21
  /**
22
   * {@inheritdoc}
23
   */
24
  public static function create(ContainerInterface $container, $basePluginId) {
25
    return new static(
26
      $container->get('entity_type.manager'),
27
      $container->get('plugin.manager.graphql.interface'),
28
      $container->get('entity_type.bundle.info')
29
    );
30
  }
31
32
  /**
33
   * {@inheritdoc}
34
   */
35
  public function __construct(EntityTypeManagerInterface $entityTypeManager, PluginManagerInterface $interfacePluginManager, EntityTypeBundleInfoInterface $entityTypeBundleInfo) {
36
    parent::__construct($entityTypeManager, $interfacePluginManager);
37
    $this->entityTypeBundleInfo = $entityTypeBundleInfo;
38
  }
39
40
  /**
41
   * {@inheritdoc}
42
   */
43
  public function getDerivativeDefinitions($basePluginDefinition) {
44
    if ($this->entityTypeManager->hasDefinition('view')) {
45
      $viewStorage = $this->entityTypeManager->getStorage('view');
46
47
      foreach (Views::getApplicableViews('graphql_display') as [$viewId, $displayId]) {
48
        /** @var \Drupal\views\ViewEntityInterface $view */
49
        $view = $viewStorage->load($viewId);
0 ignored issues
show
Bug introduced by
The variable $viewId does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
50
        if (!$this->getRowResolveType($view, $displayId)) {
0 ignored issues
show
Bug introduced by
The variable $displayId does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug Best Practice introduced by
The expression $this->getRowResolveType($view, $displayId) of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
51
          continue;
52
        }
53
54
        /** @var \Drupal\graphql_views\Plugin\views\display\GraphQL $display */
55
        $display = $this->getViewDisplay($view, $displayId);
56
        $arg_options = $display->getOption('arguments');
57
58
        if (count($arg_options) == 1) {
59
          $arg_option = reset($arg_options);
60
61
          if (!empty($arg_option['validate']['type']) && strpos($arg_option['validate']['type'], ':') !== FALSE) {
62
            [$type, $entityTypeId] = explode(':', $arg_option['validate']['type']);
0 ignored issues
show
Bug introduced by
The variable $type does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $entityTypeId does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
63
            if ($type == 'entity' && isset($entityTypeId)) {
64
              $entityType = $this->entityTypeManager->getDefinition($entityTypeId);
65
              $supportsBundles = $entityType->hasKey('bundle');
66
              $bundles = $supportsBundles && isset($arg_option['validate_options']['bundles']) ? array_values($arg_option['validate_options']['bundles']) : [];
67
              $id = implode('-', [$viewId, $displayId, 'sub-view']);
68
              $arguments = [];
69
              $arguments += $this->getPagerArguments($display);
70
              $arguments += $this->getSortArguments($display, $id);
71
              $arguments += $this->getFilterArguments($display, $id);
72
73
              $parents = [];
74
              if (empty($bundles)) {
75
                $parents[] = StringHelper::camelCase($entityTypeId);
76
77
                if ($supportsBundles) {
78
                  $bundleInfo = array_keys($this->entityTypeBundleInfo->getBundleInfo($entityTypeId));
79
                  foreach ($bundleInfo as $bundle) {
80
                    $parents[] = StringHelper::camelCase($entityTypeId, $bundle);
81
                  }
82
                }
83
              }
84
              else {
85
                foreach ($bundles as $bundle) {
86
                  $parents[] = StringHelper::camelCase($entityTypeId, $bundle);
87
                }
88
              }
89
90
              $this->derivatives[$id] = [
91
                  'id' => $id,
92
                  'name' => $display->getGraphQLQueryName(),
93
                  'type' => $display->getGraphQLResultName(),
94
                  'parents' => $parents,
95
                  'arguments' => $arguments,
96
                  'view' => $viewId,
97
                  'display' => $displayId,
98
                  'paged' => $this->isPaged($display),
99
              ] + $this->getCacheMetadataDefinition($view, $display) + $basePluginDefinition;
100
            }
101
          }
102
        }
103
      }
104
    }
105
106
    return parent::getDerivativeDefinitions($basePluginDefinition);
107
  }
108
109
}
110