Completed
Pull Request — 8.x-3.x (#481)
by Sebastian
08:49 queued 04:11
created

BlocksByRegion::resolveValues()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 24
nc 2
nop 3
dl 0
loc 38
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\graphql_core\Plugin\GraphQL\Fields\Blocks;
4
5
use Drupal\block\Entity\Block;
6
use Drupal\block_content\Plugin\Block\BlockContentBlock;
7
use Drupal\Core\Condition\ConditionInterface;
8
use Drupal\Core\Entity\EntityRepositoryInterface;
9
use Drupal\Core\Entity\EntityTypeManagerInterface;
10
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
11
use Drupal\Core\Theme\ThemeManagerInterface;
12
use Drupal\Core\Url;
13
use Drupal\graphql\GraphQL\Buffers\SubRequestBuffer;
14
use Drupal\graphql\Plugin\GraphQL\Fields\FieldPluginBase;
15
use Symfony\Component\DependencyInjection\ContainerInterface;
16
use Youshido\GraphQL\Execution\ResolveInfo;
17
18
/**
19
 * List all blocks within a theme region.
20
 *
21
 * @GraphQLField(
22
 *   id = "blocks_by_region",
23
 *   secure = true,
24
 *   name = "blocksByRegion",
25
 *   type = "Entity",
26
 *   parents = {"InternalUrl"},
27
 *   multi = true,
28
 *   arguments = {
29
 *     "region" = "String"
30
 *   }
31
 * )
32
 */
33
class BlocksByRegion extends FieldPluginBase implements ContainerFactoryPluginInterface {
0 ignored issues
show
Bug introduced by
There is one abstract method getPluginDefinition in this class; you could implement it, or declare this class as abstract.
Loading history...
34
35
  /**
36
   * The theme manager.
37
   *
38
   * @var \Drupal\Core\Theme\ThemeManagerInterface
39
   */
40
  protected $themeManager;
41
42
  /**
43
   * The entity type manager.
44
   *
45
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
46
   */
47
  protected $entityTypeManager;
48
49
  /**
50
   * The entity repository.
51
   *
52
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
53
   */
54
  protected $entityRepository;
55
56
  /**
57
   * The subrequest buffer service.
58
   *
59
   * @var \Drupal\graphql\GraphQL\Buffers\SubRequestBuffer
60
   */
61
  protected $subRequestBuffer;
62
63
  /**
64
   * {@inheritdoc}
65
   */
66
  public static function create(
67
    ContainerInterface $container,
68
    array $configuration,
69
    $pluginId,
70
    $pluginDefinition
71
  ) {
72
    return new static(
73
      $configuration,
74
      $pluginId,
75
      $pluginDefinition,
76
      $container->get('graphql.buffer.subrequest'),
77
      $container->get('theme.manager'),
78
      $container->get('entity_type.manager'),
79
      $container->get('entity.repository')
80
    );
81
  }
82
83
  /**
84
   * {@inheritdoc}
85
   */
86
  public function __construct(
87
    array $configuration,
88
    $pluginId,
89
    $pluginDefinition,
90
    SubRequestBuffer $subRequestBuffer,
91
    ThemeManagerInterface $themeManager,
92
    EntityTypeManagerInterface $entityTypeManager,
93
    EntityRepositoryInterface $entityRepository
94
  ) {
95
    parent::__construct($configuration, $pluginId, $pluginDefinition);
96
    $this->subRequestBuffer = $subRequestBuffer;
97
    $this->themeManager = $themeManager;
98
    $this->entityTypeManager = $entityTypeManager;
99
    $this->entityRepository = $entityRepository;
100
  }
101
102
  /**
103
   * {@inheritdoc}
104
   */
105
  protected function resolveValues($value, array $args, ResolveInfo $info) {
106
    if ($value instanceof Url) {
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Url does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
107
      $activeTheme = $this->themeManager->getActiveTheme();
108
      $blockStorage = $this->entityTypeManager->getStorage('block');
109
      $blocks = $blockStorage->loadByProperties([
110
        'theme' => $activeTheme->getName(),
111
        'region' => $args['region'],
112
      ]);
113
114
      $resolve = $this->subRequestBuffer->add($value, function () use ($blocks) {
115
        $blocks = array_filter($blocks, function (Block $block) {
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $blocks, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
116
          return array_reduce(iterator_to_array($block->getVisibilityConditions()), function($value, ConditionInterface $condition) {
117
            return $value && (!$condition->isNegated() == $condition->evaluate());
118
          }, TRUE);
119
        });
120
121
        uasort($blocks, '\Drupal\Block\Entity\Block::sort');
122
123
        return $blocks;
124
      });
125
126
      return function ($value, array $args, ResolveInfo $info) use ($resolve) {
0 ignored issues
show
Bug Best Practice introduced by
The return type of return function ($value,...yield $block); } }; (Closure) is incompatible with the return type of the parent method Drupal\graphql\Plugin\Gr...uginBase::resolveValues of type Generator.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
Unused Code introduced by
The parameter $value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $info is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
127
        $blocks = array_map(function(Block $block) {
128
          $plugin = $block->getPlugin();
129
          if ($plugin instanceof BlockContentBlock) {
0 ignored issues
show
Bug introduced by
The class Drupal\block_content\Plu...Block\BlockContentBlock does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
130
            return $this->entityRepository->loadEntityByUuid('block_content', $plugin->getDerivativeId());
131
          }
132
          else {
133
            return $block;
134
          }
135
        }, $resolve());
136
137
        foreach ($blocks as $block) {
138
          yield $block;
139
        }
140
      };
141
    }
142
  }
143
}
144