Completed
Pull Request — 8.x-3.x (#409)
by Sebastian
02:31
created

UpdateEntityBase::resolve()   C

Complexity

Conditions 10
Paths 10

Size

Total Lines 55
Code Lines 28

Duplication

Lines 15
Ratio 27.27 %

Importance

Changes 0
Metric Value
cc 10
eloc 28
nc 10
nop 3
dl 15
loc 55
rs 6.8372
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Drupal\graphql_core\Plugin\GraphQL\Mutations\Entity;
4
5
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
6
use Drupal\Core\Entity\EntityTypeManagerInterface;
7
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
8
use Drupal\Core\StringTranslation\StringTranslationTrait;
9
use Drupal\graphql\Plugin\GraphQL\InputTypes\InputTypePluginBase;
10
use Drupal\graphql_core\GraphQL\EntityCrudOutputWrapper;
11
use Drupal\graphql\Plugin\GraphQL\Mutations\MutationPluginBase;
12
use Symfony\Component\DependencyInjection\ContainerInterface;
13
use Youshido\GraphQL\Execution\ResolveInfo;
14
15
abstract class UpdateEntityBase extends MutationPluginBase implements ContainerFactoryPluginInterface {
16
  use DependencySerializationTrait;
17
  use StringTranslationTrait;
18
19
  /**
20
   * The entity type manager.
21
   *
22
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
23
   */
24
  protected $entityTypeManager;
25
26
  /**
27
   * {@inheritdoc}
28
   */
29
  public function __construct(array $configuration, $pluginId, $pluginDefinition, EntityTypeManagerInterface $entityTypeManager) {
30
    $this->entityTypeManager = $entityTypeManager;
31
    parent::__construct($configuration, $pluginId, $pluginDefinition);
32
  }
33
34
  /**
35
   * {@inheritdoc}
36
   */
37
  public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
38
    return new static(
39
      $configuration,
40
      $pluginId,
41
      $pluginDefinition,
42
      $container->get('entity_type.manager')
43
    );
44
  }
45
46
  /**
47
   * {@inheritdoc}
48
   */
49
  public function resolve($value, array $args, ResolveInfo $info) {
50
    $entityTypeId = $this->pluginDefinition['entity_type'];
51
    $bundleName = $this->pluginDefinition['entity_bundle'];
52
    $storage = $this->entityTypeManager->getStorage($entityTypeId);
53
54
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
55 View Code Duplication
    if (!$entity = $storage->load($args['id'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
56
      return new EntityCrudOutputWrapper(NULL, NULL, [
57
        $this->t('The requested @bundle could not be loaded.', ['@bundle' => $bundleName]),
58
      ]);
59
    }
60
61 View Code Duplication
    if (!$entity->bundle() === $bundleName) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
62
      return new EntityCrudOutputWrapper(NULL, NULL, [
63
        $this->t('The requested entity is not of the expected type @bundle.', ['@bundle' => $bundleName]),
64
      ]);
65
    }
66
67 View Code Duplication
    if (!$entity->access('update')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
68
      return new EntityCrudOutputWrapper(NULL, NULL, [
69
        $this->t('You do not have the necessary permissions to update this @bundle.', ['@bundle' => $bundleName]),
70
      ]);
71
    }
72
73
    // The raw input needs to be converted to use the proper field and property
74
    // keys because we usually convert them to camel case when adding them to
75
    // the schema.
76
    $inputArgs = $args['input'];
77
    /** @var \Youshido\GraphQL\Type\Object\AbstractObjectType $type */
78
    $type = $this->config->getArgument('input')->getType();
0 ignored issues
show
Bug introduced by
The method getArgument does only exist in Youshido\GraphQL\Config\Field\FieldConfig, but not in Youshido\GraphQL\Config\...Object\ObjectTypeConfig.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
79
    /** @var \Drupal\graphql\Plugin\GraphQL\InputTypes\InputTypePluginBase $inputType */
80
    $inputType = $type->getNamedType();
81
    $input = $this->extractEntityInput($inputArgs, $inputType);
82
83
    try {
84
      foreach ($input as $key => $value) {
85
        $entity->get($key)->setValue($value);
86
      }
87
    }
88
    catch (\InvalidArgumentException $exception) {
89
      return new EntityCrudOutputWrapper(NULL, NULL, [
90
        $this->t('The entity update failed with exception: @exception.', ['@exception' => $exception->getMessage()]),
91
      ]);
92
    }
93
94
    if (($violations = $entity->validate()) && $violations->count()) {
95
      return new EntityCrudOutputWrapper(NULL, $violations);
96
    }
97
98
    if (($status = $entity->save()) && $status === SAVED_UPDATED) {
99
      return new EntityCrudOutputWrapper($entity);
100
    }
101
102
    return NULL;
103
  }
104
105
  /**
106
   * Extract entity values from the resolver args.
107
   *
108
   * Loops over all input values and assigns them to their original field names.
109
   *
110
   * @param array $inputArgs
111
   *   The entity values provided through the resolver args.
112
   * @param \Drupal\graphql\Plugin\GraphQL\InputTypes\InputTypePluginBase $inputType
113
   *   The input type.
114
   *
115
   * @return array
116
   *   The extracted entity values with their proper, internal field names.
117
   */
118
  abstract protected function extractEntityInput(array $inputArgs, InputTypePluginBase $inputType);
119
120
}
121