JsonBlueprintDenormalizer.php 6.09 KB
Newer Older
Mateu Aguiló Bosch's avatar
Mateu Aguiló Bosch committed
1
2
3
4
<?php

namespace Drupal\subrequests\Normalizer;

5
6
7
8
9
10
11
use Drupal\Component\Serialization\Json;
use Drupal\Component\Uuid\Php;
use Drupal\subrequests\Subrequest;
use Drupal\subrequests\SubrequestsTree;
use JsonSchema\Validator;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
Mateu Aguiló Bosch's avatar
Mateu Aguiló Bosch committed
12
13
14
15
16
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Serializer;

17
18
19
/**
 * Denormalizer that builds the blueprint based on the incoming blueprint.
 */
Mateu Aguiló Bosch's avatar
Mateu Aguiló Bosch committed
20
21
22
23
24
25
26
class JsonBlueprintDenormalizer implements DenormalizerInterface, SerializerAwareInterface {

  /**
   * @var \Symfony\Component\Serializer\Serializer
   */
  protected $serializer;

27
28
29
30
31
32
33
34
35
36
37
38
  /**
   * The Subrequests logger channel.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

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


Mateu Aguiló Bosch's avatar
Mateu Aguiló Bosch committed
39
40
41
42
43
44
45
46
47
48
49
50
51
  /**
   * {@inheritdoc}
   */
  public function setSerializer(SerializerInterface $serializer) {
    if (!is_a($serializer, Serializer::class)) {
      throw new \ErrorException('Serializer is unable to normalize or denormalize.');
    }
    $this->serializer = $serializer;
  }

  /**
   * {@inheritdoc}
   */
Mateu Aguiló Bosch's avatar
Mateu Aguiló Bosch committed
52
  public function denormalize($data, $class, $format = NULL, array $context = []) {
53
54
55
56
57
58
59
    assert(
      '$this->validateInput($data)',
      'The input blueprint failed validation (see the logs for details). Please report this in the issue queue on drupal.org'
    );
    $data = array_map([$this, 'fillDefaults'], $data);
    $subrequests = array_map(function ($item) {
      return new Subrequest($item);
Mateu Aguiló Bosch's avatar
Mateu Aguiló Bosch committed
60
    }, $data);
61
    return $this->buildExecutionSequence($subrequests);
Mateu Aguiló Bosch's avatar
Mateu Aguiló Bosch committed
62
63
64
65
66
67
68
  }

  /**
   * {@inheritdoc}
   */
  public function supportsDenormalization($data, $type, $format = NULL) {
    return $format === 'json'
69
      && $type === SubrequestsTree::class
Mateu Aguiló Bosch's avatar
Mateu Aguiló Bosch committed
70
71
72
73
74
75
76
77
78
79
80
81
82
      && is_array($data)
      && !static::arrayIsKeyed($data);
  }

  /**
   * Check if an array is keyed.
   *
   * @param array $input
   *   The input array to check.
   *
   * @return bool
   *   True if the array is keyed.
   */
83
  protected static function arrayIsKeyed(array $input) {
Mateu Aguiló Bosch's avatar
Mateu Aguiló Bosch committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
    $keys = array_keys($input);
    // If the array does not start at 0, it is not numeric.
    if ($keys[0] !== 0) {
      return TRUE;
    }
    // If there is a non-numeric key, the array is not numeric.
    $numeric_keys = array_filter($keys, 'is_numeric');
    if (count($keys) != count($numeric_keys)) {
      return TRUE;
    }
    // If the keys are not following the natural numbers sequence, then it is
    // not numeric.
    for ($index = 1; $index < count($keys); $index++) {
      if ($keys[$index] - $keys[$index - 1] !== 1) {
        return TRUE;
      }
    }
    return FALSE;
  }

104
105
106
107
108
109
110
111
112
113
114
115
116
117
  /**
   * Fill the defaults.
   *
   * @param array $raw_item
   *   The object to turn into a Subrequest input.
   *
   * @return array
   *   The complete Subrequest.
   */
  protected function fillDefaults($raw_item) {
    if (empty($raw_item['requestId'])) {
      $uuid = new Php();
      $raw_item['requestId'] = $uuid->generate();
    }
118
119
120
121
    if (!isset($raw_item['body'])) {
      $raw_item['body'] = NULL;
    }
    elseif (!empty($raw_item['body'])) {
122
123
      $raw_item['body'] = Json::decode($raw_item['body']);
    }
124

125
    $raw_item['headers'] = !empty($raw_item['headers']) ? $raw_item['headers'] : [];
126
    $raw_item['waitFor'] = !empty($raw_item['waitFor']) ? $raw_item['waitFor'] : ['<ROOT>'];
127
128
    $raw_item['_resolved'] = FALSE;

129
130
131
132
133
134
135
136
137
    // Detect if there is an encoded token. If so, then decode the URI.
    if (
      !empty($raw_item['uri']) &&
      strpos($raw_item['uri'], '%7B%7B') !== FALSE &&
      strpos($raw_item['uri'], '%7D%7D') !== FALSE
    ) {
      $raw_item['uri'] = urldecode($raw_item['uri']);
    }

138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
    return $raw_item;
  }

  /**
   * Validates a response against the JSON API specification.
   *
   * @param mixed $input
   *   The blueprint sent by the consumer.
   *
   * @return bool
   *   FALSE if the input failed validation, otherwise TRUE.
   */
  protected function validateInput($input) {
    if (!class_exists("\\JsonSchema\\Validator")) {
      return TRUE;
    }

    $validator = new Validator();
    $schema_path = dirname(dirname(__DIR__)) . '/schema.json';

    $validator->check($input, (object) ['$ref' => 'file://' . $schema_path]);

    if (!$validator->isValid()) {
      // Log any potential errors.
      $this->logger->debug('Response failed validation: @data', [
        '@data' => Json::encode($input),
      ]);
      $this->logger->debug('Validation errors: @errors', [
        '@errors' => Json::encode($validator->getErrors()),
      ]);
    }

    return $validator->isValid();
  }

  /**
   * Builds the execution sequence.
   *
   * Builds an array where each position contains the IDs of the requests to be
   * executed. All the IDs in the same position in the sequence can be executed
   * in parallel.
   *
   * @param \Drupal\subrequests\Subrequest[] $parsed
   *   The parsed requests.
   *
   * @return SubrequestsTree
   *   The sequence of IDs grouped by execution order.
   */
  public function buildExecutionSequence(array $parsed) {
    $sequence = new SubrequestsTree();
    $rooted_reqs = array_filter($parsed, function (Subrequest $item) {
189
      return $item->waitFor === ['<ROOT>'];
190
191
192
193
    });
    $sequence->stack($rooted_reqs);
    $subreqs_with_unresolved_deps = array_values(
      array_filter($parsed, function (Subrequest $item) {
194
        return $item->waitFor !== ['<ROOT>'];
195
196
197
      })
    );
    $dependency_is_resolved = function (Subrequest $item) use ($sequence) {
198
      return empty(array_diff($item->waitFor, $sequence->allIds()));
199
200
201
202
203
204
    };
    while (count($subreqs_with_unresolved_deps)) {
      $no_deps = array_filter($subreqs_with_unresolved_deps, $dependency_is_resolved);
      if (empty($no_deps)) {
        throw new BadRequestHttpException('Waiting for unresolvable request. Abort.');
      }
205
206
      $sequence->stack($no_deps);
      $subreqs_with_unresolved_deps = array_diff($subreqs_with_unresolved_deps, $no_deps);
207
208
209
210
    }
    return $sequence;
  }

Mateu Aguiló Bosch's avatar
Mateu Aguiló Bosch committed
211
}