GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

QuickEditImageBrowserController::existing()   B
last analyzed

Complexity

Conditions 10
Paths 11

Size

Total Lines 80
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 45
dl 0
loc 80
rs 7.3333
c 0
b 0
f 0
cc 10
nc 11
nop 5

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\df_tools_frontend\Controller;
4
5
use Drupal\Core\Entity\EntityInterface;
6
use Drupal\Core\Render\Element\StatusMessages;
7
use Drupal\image\Controller\QuickEditImageController;
8
use Drupal\media\Entity\Media;
9
use Symfony\Component\HttpFoundation\JsonResponse;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
12
13
/**
14
 * Returns responses for custom Quickedit Image module routes.
15
 */
16
class QuickEditImageBrowserController extends QuickEditImageController {
17
18
  /**
19
   * Returns a JSON object representing the existing file, or validation
20
   * errors.
21
   *
22
   * @param \Drupal\Core\Entity\EntityInterface $entity
23
   *   The entity of which an image field is being rendered.
24
   * @param string $field_name
25
   *   The name of the (image) field that is being rendered
26
   * @param string $langcode
27
   *   The language code of the field that is being rendered.
28
   * @param string $view_mode_id
29
   *   The view mode of the field that is being rendered.
30
   * @param \Symfony\Component\HttpFoundation\Request $request
31
   *   The current request object.
32
   *
33
   * @return \Symfony\Component\HttpFoundation\JsonResponse
34
   *   The Ajax response.
35
   *
36
   * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
37
   *   Throws an exception if the request is invalid.
38
   */
39
  public function existing(EntityInterface $entity, $field_name, $langcode, $view_mode_id, Request $request) {
40
    $mid = $request->request->get('mid');
41
    if (!$mid || !is_numeric($mid)) {
42
      throw new BadRequestHttpException('MID missing or invalid.');
43
    }
44
45
    $field = $this->getField($entity, $field_name, $langcode);
46
    $field_validators = $field->getUploadValidators();
47
    $field_settings = $field->getFieldDefinition()->getSettings();
48
49
    // Add upload resolution validation.
50
    if ($field_settings['max_resolution'] || $field_settings['min_resolution']) {
51
      $field_validators['file_validate_image_resolution'] = [$field_settings['max_resolution'], $field_settings['min_resolution']];
52
    }
53
54
    // Attempt to load the image given the field's constraints.
55
    $media = Media::load($mid);
56
    if (!$media || !$media->bundle() == 'image') {
0 ignored issues
show
introduced by
$media is of type Drupal\media\Entity\Media, thus it always evaluated to true.
Loading history...
57
      throw new BadRequestHttpException('Media Entity not found or not of bundle "Image".');
58
    }
59
60
    /** @var \Drupal\file\Entity\file $file */
61
    $file = $media->get('image')->first()->get('entity')->getTarget()->getValue();
0 ignored issues
show
Bug introduced by
The method get() does not exist on Drupal\Core\TypedData\TypedDataInterface. It seems like you code against a sub-type of Drupal\Core\TypedData\TypedDataInterface such as Drupal\Core\TypedData\Plugin\DataType\Map or Drupal\Core\Entity\Plugin\DataType\EntityAdapter or Drupal\Core\TypedData\Plugin\DataType\ItemList or Drupal\Core\Config\Schema\ArrayElement or Drupal\Core\TypedData\ListInterface or Drupal\Core\Config\Schema\TypedConfigInterface or Drupal\Core\TypedData\ComplexDataInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

61
    $file = $media->get('image')->first()->/** @scrutinizer ignore-call */ get('entity')->getTarget()->getValue();
Loading history...
62
    if ($file) {
0 ignored issues
show
introduced by
$file is of type Drupal\file\Entity\file, thus it always evaluated to true.
Loading history...
63
      // Call the validation functions specified by this function's caller.
64
      $errors = file_validate($file, $field_validators);
65
66
      // Check for errors.
67
      if (!empty($errors)) {
68
        $message = array(
69
          'error' => array(
70
            '#markup' => $this->t('The specified file %name could not be uploaded.', array('%name' => $file->getFilename())),
71
          ),
72
          'item_list' => array(
73
            '#theme' => 'item_list',
74
            '#items' => $errors,
75
          ),
76
        );
77
        // Return a JSON object containing the errors from Drupal and our
78
        // "main_error", which is displayed inside the dropzone area.
79
        drupal_set_message(\Drupal::service('renderer')->renderPlain($message), 'error');
0 ignored issues
show
Deprecated Code introduced by
The function drupal_set_message() has been deprecated: in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

79
        /** @scrutinizer ignore-deprecated */ drupal_set_message(\Drupal::service('renderer')->renderPlain($message), 'error');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
80
        $messages = StatusMessages::renderMessages('error');
81
        return new JsonResponse(['errors' => $this->renderer->render($messages), 'main_error' => $this->t('The requested image failed validation.')]);
82
      }
83
84
      $image = $this->imageFactory->get($file->getFileUri());
85
86
      // Set the value in the Entity to the new file.
87
      /** @var \Drupal\file\Plugin\Field\FieldType\FileFieldItemList $field_list */
88
      $value = $entity->$field_name->getValue();
89
      $value[0]['target_id'] = $file->id();
90
      $value[0]['width'] = $image->getWidth();
91
      $value[0]['height'] = $image->getHeight();
92
      $entity->$field_name->setValue($value);
93
94
      // Render the new image using the correct formatter settings.
95
      $entity_view_mode_ids = array_keys($this->entityManager()->getViewModes($entity->getEntityTypeId()));
0 ignored issues
show
Deprecated Code introduced by
The function Drupal\Core\Controller\C...erBase::entityManager() has been deprecated: in Drupal 8.0.0, will be removed before Drupal 9.0.0. Most of the time static::entityTypeManager() is supposed to be used instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

95
      $entity_view_mode_ids = array_keys(/** @scrutinizer ignore-deprecated */ $this->entityManager()->getViewModes($entity->getEntityTypeId()));

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
96
      if (in_array($view_mode_id, $entity_view_mode_ids)) {
97
        $output = $entity->$field_name->view($view_mode_id);
98
      }
99
      else {
100
        // Each part of a custom (non-Entity Display) view mode ID is separated
101
        // by a dash; the first part must be the module name.
102
        $mode_id_parts = explode('-', $view_mode_id, 2);
103
        $module = reset($mode_id_parts);
104
        $args = [$entity, $field_name, $view_mode_id, $langcode];
105
        $output = $this->moduleHandler()->invoke($module, 'quickedit_render_field', $args);
106
      }
107
108
      // Save the Entity to tempstore.
109
      $this->tempStore->set($entity->uuid(), $entity);
110
111
      $data = [
112
        'fid' => $file->id(),
113
        'html' => $this->renderer->renderRoot($output),
114
      ];
115
      return new JsonResponse($data);
116
    }
117
    else {
118
      return new JsonResponse(['main_error' => $this->t('File does not exist.')]);
119
    }
120
  }
121
122
}
123