Completed
Pull Request — 8.x-3.x (#399)
by Philipp
02:23
created

UpdateEntity::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_core\GraphQL\EntityCrudOutputWrapper;
10
use Drupal\graphql\Plugin\GraphQL\Mutations\MutationPluginBase;
11
use Drupal\graphql_core\Plugin\GraphQL\Mutations\Entity\EntityMutationInputTrait;
12
use Symfony\Component\DependencyInjection\ContainerInterface;
13
use Youshido\GraphQL\Execution\ResolveInfo;
14
15
/**
16
 * Update an entity.
17
 *
18
 * TODO: Add revision support.
19
 *
20
 * @GraphQLMutation(
21
 *   id = "update_entity",
22
 *   type = "EntityCrudOutput",
23
 *   secure = true,
24
 *   nullable = false,
25
 *   schema_cache_tags = {"entity_types", "entity_bundles"},
26
 *   deriver = "Drupal\graphql_core\Plugin\Deriver\Mutations\UpdateEntityDeriver"
27
 * )
28
 */
29
class UpdateEntity extends MutationPluginBase implements ContainerFactoryPluginInterface {
30
  use DependencySerializationTrait;
31
  use StringTranslationTrait;
32
  use EntityMutationInputTrait;
33
34
  /**
35
   * The entity type manager.
36
   *
37
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
38
   */
39
  protected $entityTypeManager;
40
41
  /**
42
   * {@inheritdoc}
43
   */
44
  public function __construct(array $configuration, $pluginId, $pluginDefinition, EntityTypeManagerInterface $entityTypeManager) {
45
    $this->entityTypeManager = $entityTypeManager;
46
    parent::__construct($configuration, $pluginId, $pluginDefinition);
47
  }
48
49
  /**
50
   * {@inheritdoc}
51
   */
52
  public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
53
    return new static(
54
      $configuration,
55
      $pluginId,
56
      $pluginDefinition,
57
      $container->get('entity_type.manager')
58
    );
59
  }
60
61
  /**
62
   * {@inheritdoc}
63
   */
64
  public function resolve($value, array $args, ResolveInfo $info) {
65
    $entityTypeId = $this->pluginDefinition['entity_type'];
66
    $bundleName = $this->pluginDefinition['entity_bundle'];
67
    $storage = $this->entityTypeManager->getStorage($entityTypeId);
68
69
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
70 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...
71
      return new EntityCrudOutputWrapper(NULL, NULL, [
72
        $this->t('The requested @bundle could not be loaded.', ['@bundle' => $bundleName]),
73
      ]);
74
    }
75
76 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...
77
      return new EntityCrudOutputWrapper(NULL, NULL, [
78
        $this->t('The requested entity is not of the expected type @bundle.', ['@bundle' => $bundleName]),
79
      ]);
80
    }
81
82 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...
83
      return new EntityCrudOutputWrapper(NULL, NULL, [
84
        $this->t('You do not have the necessary permissions to update this @bundle.', ['@bundle' => $bundleName]),
85
      ]);
86
    }
87
88
    // The raw input needs to be converted to use the proper field and property
89
    // keys because we usually convert them to camel case when adding them to
90
    // the schema.
91
    $inputArgs = $args['input'];
92
    /** @var \Youshido\GraphQL\Type\Object\AbstractObjectType $type */
93
    $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...
94
    /** @var \Drupal\graphql_core\Plugin\GraphQL\InputTypes\Mutations\EntityInput $inputType */
95
    $inputType = $type->getNamedType();
96
    $input = $this->extractEntityInput($inputArgs, $inputType);
97
98
    try {
99
      foreach ($input as $key => $value) {
100
        $entity->get($key)->setValue($value);
101
      }
102
    }
103
    catch (\InvalidArgumentException $exception) {
104
      return new EntityCrudOutputWrapper(NULL, NULL, [
105
        $this->t('The entity update failed with exception: @exception.', ['@exception' => $exception->getMessage()]),
106
      ]);
107
    }
108
109
    if (($violations = $entity->validate()) && $violations->count()) {
110
      return new EntityCrudOutputWrapper(NULL, $violations);
111
    }
112
113
    if (($status = $entity->save()) && $status === SAVED_UPDATED) {
114
      return new EntityCrudOutputWrapper($entity);
115
    }
116
117
    return NULL;
118
  }
119
120
121
}
122