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.
Completed
Push — master ( 91a2ce...662af5 )
by Joni
03:10 queued 11s
created
lib/ASN1/Element.php 2 patches
Indentation   +478 added lines, -478 removed lines patch added patch discarded remove patch
@@ -24,482 +24,482 @@
 block discarded – undo
24 24
  */
25 25
 abstract class Element implements ElementBase
26 26
 {
27
-    // Universal type tags
28
-    const TYPE_EOC = 0x00;
29
-    const TYPE_BOOLEAN = 0x01;
30
-    const TYPE_INTEGER = 0x02;
31
-    const TYPE_BIT_STRING = 0x03;
32
-    const TYPE_OCTET_STRING = 0x04;
33
-    const TYPE_NULL = 0x05;
34
-    const TYPE_OBJECT_IDENTIFIER = 0x06;
35
-    const TYPE_OBJECT_DESCRIPTOR = 0x07;
36
-    const TYPE_EXTERNAL = 0x08;
37
-    const TYPE_REAL = 0x09;
38
-    const TYPE_ENUMERATED = 0x0a;
39
-    const TYPE_EMBEDDED_PDV = 0x0b;
40
-    const TYPE_UTF8_STRING = 0x0c;
41
-    const TYPE_RELATIVE_OID = 0x0d;
42
-    const TYPE_SEQUENCE = 0x10;
43
-    const TYPE_SET = 0x11;
44
-    const TYPE_NUMERIC_STRING = 0x12;
45
-    const TYPE_PRINTABLE_STRING = 0x13;
46
-    const TYPE_T61_STRING = 0x14;
47
-    const TYPE_VIDEOTEX_STRING = 0x15;
48
-    const TYPE_IA5_STRING = 0x16;
49
-    const TYPE_UTC_TIME = 0x17;
50
-    const TYPE_GENERALIZED_TIME = 0x18;
51
-    const TYPE_GRAPHIC_STRING = 0x19;
52
-    const TYPE_VISIBLE_STRING = 0x1a;
53
-    const TYPE_GENERAL_STRING = 0x1b;
54
-    const TYPE_UNIVERSAL_STRING = 0x1c;
55
-    const TYPE_CHARACTER_STRING = 0x1d;
56
-    const TYPE_BMP_STRING = 0x1e;
57
-
58
-    /**
59
-     * Mapping from universal type tag to implementation class name.
60
-     *
61
-     * @internal
62
-     *
63
-     * @var array
64
-     */
65
-    const MAP_TAG_TO_CLASS = [
66
-        self::TYPE_EOC => Primitive\EOC::class,
67
-        self::TYPE_BOOLEAN => Primitive\Boolean::class,
68
-        self::TYPE_INTEGER => Primitive\Integer::class,
69
-        self::TYPE_BIT_STRING => Primitive\BitString::class,
70
-        self::TYPE_OCTET_STRING => Primitive\OctetString::class,
71
-        self::TYPE_NULL => Primitive\NullType::class,
72
-        self::TYPE_OBJECT_IDENTIFIER => Primitive\ObjectIdentifier::class,
73
-        self::TYPE_OBJECT_DESCRIPTOR => Primitive\ObjectDescriptor::class,
74
-        self::TYPE_REAL => Primitive\Real::class,
75
-        self::TYPE_ENUMERATED => Primitive\Enumerated::class,
76
-        self::TYPE_UTF8_STRING => Primitive\UTF8String::class,
77
-        self::TYPE_RELATIVE_OID => Primitive\RelativeOID::class,
78
-        self::TYPE_SEQUENCE => Constructed\Sequence::class,
79
-        self::TYPE_SET => Constructed\Set::class,
80
-        self::TYPE_NUMERIC_STRING => Primitive\NumericString::class,
81
-        self::TYPE_PRINTABLE_STRING => Primitive\PrintableString::class,
82
-        self::TYPE_T61_STRING => Primitive\T61String::class,
83
-        self::TYPE_VIDEOTEX_STRING => Primitive\VideotexString::class,
84
-        self::TYPE_IA5_STRING => Primitive\IA5String::class,
85
-        self::TYPE_UTC_TIME => Primitive\UTCTime::class,
86
-        self::TYPE_GENERALIZED_TIME => Primitive\GeneralizedTime::class,
87
-        self::TYPE_GRAPHIC_STRING => Primitive\GraphicString::class,
88
-        self::TYPE_VISIBLE_STRING => Primitive\VisibleString::class,
89
-        self::TYPE_GENERAL_STRING => Primitive\GeneralString::class,
90
-        self::TYPE_UNIVERSAL_STRING => Primitive\UniversalString::class,
91
-        self::TYPE_CHARACTER_STRING => Primitive\CharacterString::class,
92
-        self::TYPE_BMP_STRING => Primitive\BMPString::class,
93
-    ];
94
-
95
-    /**
96
-     * Pseudotype for all string types.
97
-     *
98
-     * May be used as an expectation parameter.
99
-     *
100
-     * @var int
101
-     */
102
-    const TYPE_STRING = -1;
103
-
104
-    /**
105
-     * Pseudotype for all time types.
106
-     *
107
-     * May be used as an expectation parameter.
108
-     *
109
-     * @var int
110
-     */
111
-    const TYPE_TIME = -2;
112
-
113
-    /**
114
-     * Pseudotype for constructed strings.
115
-     *
116
-     * May be used as an expectation parameter.
117
-     *
118
-     * @var int
119
-     */
120
-    const TYPE_CONSTRUCTED_STRING = -3;
121
-
122
-    /**
123
-     * Mapping from universal type tag to human readable name.
124
-     *
125
-     * @internal
126
-     *
127
-     * @var array
128
-     */
129
-    const MAP_TYPE_TO_NAME = [
130
-        self::TYPE_EOC => 'EOC',
131
-        self::TYPE_BOOLEAN => 'BOOLEAN',
132
-        self::TYPE_INTEGER => 'INTEGER',
133
-        self::TYPE_BIT_STRING => 'BIT STRING',
134
-        self::TYPE_OCTET_STRING => 'OCTET STRING',
135
-        self::TYPE_NULL => 'NULL',
136
-        self::TYPE_OBJECT_IDENTIFIER => 'OBJECT IDENTIFIER',
137
-        self::TYPE_OBJECT_DESCRIPTOR => 'ObjectDescriptor',
138
-        self::TYPE_EXTERNAL => 'EXTERNAL',
139
-        self::TYPE_REAL => 'REAL',
140
-        self::TYPE_ENUMERATED => 'ENUMERATED',
141
-        self::TYPE_EMBEDDED_PDV => 'EMBEDDED PDV',
142
-        self::TYPE_UTF8_STRING => 'UTF8String',
143
-        self::TYPE_RELATIVE_OID => 'RELATIVE-OID',
144
-        self::TYPE_SEQUENCE => 'SEQUENCE',
145
-        self::TYPE_SET => 'SET',
146
-        self::TYPE_NUMERIC_STRING => 'NumericString',
147
-        self::TYPE_PRINTABLE_STRING => 'PrintableString',
148
-        self::TYPE_T61_STRING => 'T61String',
149
-        self::TYPE_VIDEOTEX_STRING => 'VideotexString',
150
-        self::TYPE_IA5_STRING => 'IA5String',
151
-        self::TYPE_UTC_TIME => 'UTCTime',
152
-        self::TYPE_GENERALIZED_TIME => 'GeneralizedTime',
153
-        self::TYPE_GRAPHIC_STRING => 'GraphicString',
154
-        self::TYPE_VISIBLE_STRING => 'VisibleString',
155
-        self::TYPE_GENERAL_STRING => 'GeneralString',
156
-        self::TYPE_UNIVERSAL_STRING => 'UniversalString',
157
-        self::TYPE_CHARACTER_STRING => 'CHARACTER STRING',
158
-        self::TYPE_BMP_STRING => 'BMPString',
159
-        self::TYPE_STRING => 'Any String',
160
-        self::TYPE_TIME => 'Any Time',
161
-        self::TYPE_CONSTRUCTED_STRING => 'Constructed String',
162
-    ];
163
-
164
-    /**
165
-     * Element's type tag.
166
-     *
167
-     * @var int
168
-     */
169
-    protected $_typeTag;
170
-
171
-    /**
172
-     * Whether type shall be encoded with indefinite length.
173
-     *
174
-     * @var bool
175
-     */
176
-    protected $_indefiniteLength = false;
177
-
178
-    /**
179
-     * {@inheritdoc}
180
-     */
181
-    abstract public function typeClass(): int;
182
-
183
-    /**
184
-     * {@inheritdoc}
185
-     */
186
-    abstract public function isConstructed(): bool;
187
-
188
-    /**
189
-     * Decode element from DER data.
190
-     *
191
-     * @param string   $data   DER encoded data
192
-     * @param null|int $offset Reference to the variable that contains offset
193
-     *                         into the data where to start parsing.
194
-     *                         Variable is updated to the offset next to the
195
-     *                         parsed element. If null, start from offset 0.
196
-     *
197
-     * @throws DecodeException           If decoding fails
198
-     * @throws \UnexpectedValueException If called in the context of an expected
199
-     *                                   type, but decoding yields another type
200
-     *
201
-     * @return ElementBase
202
-     */
203
-    public static function fromDER(string $data, int &$offset = null): ElementBase
204
-    {
205
-        $idx = $offset ?? 0;
206
-        // decode identifier
207
-        $identifier = Identifier::fromDER($data, $idx);
208
-        // determine class that implements type specific decoding
209
-        $cls = self::_determineImplClass($identifier);
210
-        try {
211
-            // decode remaining element
212
-            $element = $cls::_decodeFromDER($identifier, $data, $idx);
213
-        } catch (\LogicException $e) {
214
-            // rethrow as a RuntimeException for unified exception handling
215
-            throw new DecodeException(
216
-                sprintf('Error while decoding %s.',
217
-                    self::tagToName($identifier->intTag())), 0, $e);
218
-        }
219
-        // if called in the context of a concrete class, check
220
-        // that decoded type matches the type of a calling class
221
-        $called_class = get_called_class();
222
-        if (self::class !== $called_class) {
223
-            if (!$element instanceof $called_class) {
224
-                throw new \UnexpectedValueException(
225
-                    sprintf('%s expected, got %s.', $called_class,
226
-                        get_class($element)));
227
-            }
228
-        }
229
-        // update offset for the caller
230
-        if (isset($offset)) {
231
-            $offset = $idx;
232
-        }
233
-        return $element;
234
-    }
235
-
236
-    /**
237
-     * {@inheritdoc}
238
-     */
239
-    public function toDER(): string
240
-    {
241
-        $identifier = new Identifier($this->typeClass(),
242
-            $this->isConstructed() ? Identifier::CONSTRUCTED : Identifier::PRIMITIVE,
243
-            $this->_typeTag);
244
-        $content = $this->_encodedContentDER();
245
-        if ($this->_indefiniteLength) {
246
-            $length = new Length(0, true);
247
-            $eoc = new Primitive\EOC();
248
-            return $identifier->toDER() . $length->toDER() . $content . $eoc->toDER();
249
-        }
250
-        $length = new Length(strlen($content));
251
-        return $identifier->toDER() . $length->toDER() . $content;
252
-    }
253
-
254
-    /**
255
-     * {@inheritdoc}
256
-     */
257
-    public function tag(): int
258
-    {
259
-        return $this->_typeTag;
260
-    }
261
-
262
-    /**
263
-     * {@inheritdoc}
264
-     */
265
-    public function isType(int $tag): bool
266
-    {
267
-        // if element is context specific
268
-        if (Identifier::CLASS_CONTEXT_SPECIFIC === $this->typeClass()) {
269
-            return false;
270
-        }
271
-        // negative tags identify an abstract pseudotype
272
-        if ($tag < 0) {
273
-            return $this->_isPseudoType($tag);
274
-        }
275
-        return $this->_isConcreteType($tag);
276
-    }
277
-
278
-    /**
279
-     * {@inheritdoc}
280
-     */
281
-    public function expectType(int $tag): ElementBase
282
-    {
283
-        if (!$this->isType($tag)) {
284
-            throw new \UnexpectedValueException(
285
-                sprintf('%s expected, got %s.', self::tagToName($tag),
286
-                    $this->_typeDescriptorString()));
287
-        }
288
-        return $this;
289
-    }
290
-
291
-    /**
292
-     * {@inheritdoc}
293
-     */
294
-    public function isTagged(): bool
295
-    {
296
-        return $this instanceof TaggedType;
297
-    }
298
-
299
-    /**
300
-     * {@inheritdoc}
301
-     */
302
-    public function expectTagged(?int $tag = null): TaggedType
303
-    {
304
-        if (!$this->isTagged()) {
305
-            throw new \UnexpectedValueException(
306
-                sprintf('Context specific element expected, got %s.',
307
-                    Identifier::classToName($this->typeClass())));
308
-        }
309
-        if (isset($tag) && $this->tag() !== $tag) {
310
-            throw new \UnexpectedValueException(
311
-                sprintf('Tag %d expected, got %d.', $tag, $this->tag()));
312
-        }
313
-        return $this;
314
-    }
315
-
316
-    /**
317
-     * Whether element has indefinite length.
318
-     *
319
-     * @return bool
320
-     */
321
-    public function hasIndefiniteLength(): bool
322
-    {
323
-        return $this->_indefiniteLength;
324
-    }
325
-
326
-    /**
327
-     * Get self with indefinite length encoding set.
328
-     *
329
-     * @param bool $indefinite True for indefinite length, false for definite length
330
-     *
331
-     * @return self
332
-     */
333
-    public function withIndefiniteLength(bool $indefinite = true): self
334
-    {
335
-        $obj = clone $this;
336
-        $obj->_indefiniteLength = $indefinite;
337
-        return $obj;
338
-    }
339
-
340
-    /**
341
-     * {@inheritdoc}
342
-     */
343
-    final public function asElement(): Element
344
-    {
345
-        return $this;
346
-    }
347
-
348
-    /**
349
-     * Get element decorated with UnspecifiedType object.
350
-     *
351
-     * @return UnspecifiedType
352
-     */
353
-    public function asUnspecified(): UnspecifiedType
354
-    {
355
-        return new UnspecifiedType($this);
356
-    }
357
-
358
-    /**
359
-     * Get human readable name for an universal tag.
360
-     *
361
-     * @param int $tag
362
-     *
363
-     * @return string
364
-     */
365
-    public static function tagToName(int $tag): string
366
-    {
367
-        if (!array_key_exists($tag, self::MAP_TYPE_TO_NAME)) {
368
-            return "TAG {$tag}";
369
-        }
370
-        return self::MAP_TYPE_TO_NAME[$tag];
371
-    }
372
-
373
-    /**
374
-     * Get the content encoded in DER.
375
-     *
376
-     * Returns the DER encoded content without identifier and length header octets.
377
-     *
378
-     * @return string
379
-     */
380
-    abstract protected function _encodedContentDER(): string;
381
-
382
-    /**
383
-     * Decode type-specific element from DER.
384
-     *
385
-     * @param Identifier $identifier Pre-parsed identifier
386
-     * @param string     $data       DER data
387
-     * @param int        $offset     Offset in data to the next byte after identifier
388
-     *
389
-     * @throws DecodeException If decoding fails
390
-     *
391
-     * @return ElementBase
392
-     */
393
-    protected static function _decodeFromDER(Identifier $identifier,
394
-        string $data, int &$offset): ElementBase
395
-    {
396
-        throw new \BadMethodCallException(
397
-            __METHOD__ . ' must be implemented in derived class.');
398
-    }
399
-
400
-    /**
401
-     * Determine the class that implements the type.
402
-     *
403
-     * @param Identifier $identifier
404
-     *
405
-     * @return string Class name
406
-     */
407
-    protected static function _determineImplClass(Identifier $identifier): string
408
-    {
409
-        switch ($identifier->typeClass()) {
410
-            case Identifier::CLASS_UNIVERSAL:
411
-                $cls = self::_determineUniversalImplClass($identifier->intTag());
412
-                // constructed strings may be present in BER
413
-                if ($identifier->isConstructed() &&
414
-                    is_subclass_of($cls, StringType::class)) {
415
-                    $cls = ConstructedString::class;
416
-                }
417
-                return $cls;
418
-            case Identifier::CLASS_CONTEXT_SPECIFIC:
419
-                return ContextSpecificType::class;
420
-            case Identifier::CLASS_APPLICATION:
421
-                return ApplicationType::class;
422
-            case Identifier::CLASS_PRIVATE:
423
-                return PrivateType::class;
424
-        }
425
-        throw new \UnexpectedValueException(
426
-            sprintf('%s %d not implemented.',
427
-                Identifier::classToName($identifier->typeClass()),
428
-                $identifier->tag()));
429
-    }
430
-
431
-    /**
432
-     * Determine the class that implements an universal type of the given tag.
433
-     *
434
-     * @param int $tag
435
-     *
436
-     * @throws \UnexpectedValueException
437
-     *
438
-     * @return string Class name
439
-     */
440
-    protected static function _determineUniversalImplClass(int $tag): string
441
-    {
442
-        if (!array_key_exists($tag, self::MAP_TAG_TO_CLASS)) {
443
-            throw new \UnexpectedValueException(
444
-                "Universal tag {$tag} not implemented.");
445
-        }
446
-        return self::MAP_TAG_TO_CLASS[$tag];
447
-    }
448
-
449
-    /**
450
-     * Get textual description of the type for debugging purposes.
451
-     *
452
-     * @return string
453
-     */
454
-    protected function _typeDescriptorString(): string
455
-    {
456
-        if (Identifier::CLASS_UNIVERSAL === $this->typeClass()) {
457
-            return self::tagToName($this->_typeTag);
458
-        }
459
-        return sprintf('%s TAG %d', Identifier::classToName($this->typeClass()),
460
-            $this->_typeTag);
461
-    }
462
-
463
-    /**
464
-     * Check whether the element is a concrete type of a given tag.
465
-     *
466
-     * @param int $tag
467
-     *
468
-     * @return bool
469
-     */
470
-    private function _isConcreteType(int $tag): bool
471
-    {
472
-        // if tag doesn't match
473
-        if ($this->tag() !== $tag) {
474
-            return false;
475
-        }
476
-        // if type is universal check that instance is of a correct class
477
-        if (Identifier::CLASS_UNIVERSAL === $this->typeClass()) {
478
-            $cls = self::_determineUniversalImplClass($tag);
479
-            if (!$this instanceof $cls) {
480
-                return false;
481
-            }
482
-        }
483
-        return true;
484
-    }
485
-
486
-    /**
487
-     * Check whether the element is a pseudotype.
488
-     *
489
-     * @param int $tag
490
-     *
491
-     * @return bool
492
-     */
493
-    private function _isPseudoType(int $tag): bool
494
-    {
495
-        switch ($tag) {
496
-            case self::TYPE_STRING:
497
-                return $this instanceof StringType;
498
-            case self::TYPE_TIME:
499
-                return $this instanceof TimeType;
500
-            case self::TYPE_CONSTRUCTED_STRING:
501
-                return $this instanceof ConstructedString;
502
-        }
503
-        return false;
504
-    }
27
+	// Universal type tags
28
+	const TYPE_EOC = 0x00;
29
+	const TYPE_BOOLEAN = 0x01;
30
+	const TYPE_INTEGER = 0x02;
31
+	const TYPE_BIT_STRING = 0x03;
32
+	const TYPE_OCTET_STRING = 0x04;
33
+	const TYPE_NULL = 0x05;
34
+	const TYPE_OBJECT_IDENTIFIER = 0x06;
35
+	const TYPE_OBJECT_DESCRIPTOR = 0x07;
36
+	const TYPE_EXTERNAL = 0x08;
37
+	const TYPE_REAL = 0x09;
38
+	const TYPE_ENUMERATED = 0x0a;
39
+	const TYPE_EMBEDDED_PDV = 0x0b;
40
+	const TYPE_UTF8_STRING = 0x0c;
41
+	const TYPE_RELATIVE_OID = 0x0d;
42
+	const TYPE_SEQUENCE = 0x10;
43
+	const TYPE_SET = 0x11;
44
+	const TYPE_NUMERIC_STRING = 0x12;
45
+	const TYPE_PRINTABLE_STRING = 0x13;
46
+	const TYPE_T61_STRING = 0x14;
47
+	const TYPE_VIDEOTEX_STRING = 0x15;
48
+	const TYPE_IA5_STRING = 0x16;
49
+	const TYPE_UTC_TIME = 0x17;
50
+	const TYPE_GENERALIZED_TIME = 0x18;
51
+	const TYPE_GRAPHIC_STRING = 0x19;
52
+	const TYPE_VISIBLE_STRING = 0x1a;
53
+	const TYPE_GENERAL_STRING = 0x1b;
54
+	const TYPE_UNIVERSAL_STRING = 0x1c;
55
+	const TYPE_CHARACTER_STRING = 0x1d;
56
+	const TYPE_BMP_STRING = 0x1e;
57
+
58
+	/**
59
+	 * Mapping from universal type tag to implementation class name.
60
+	 *
61
+	 * @internal
62
+	 *
63
+	 * @var array
64
+	 */
65
+	const MAP_TAG_TO_CLASS = [
66
+		self::TYPE_EOC => Primitive\EOC::class,
67
+		self::TYPE_BOOLEAN => Primitive\Boolean::class,
68
+		self::TYPE_INTEGER => Primitive\Integer::class,
69
+		self::TYPE_BIT_STRING => Primitive\BitString::class,
70
+		self::TYPE_OCTET_STRING => Primitive\OctetString::class,
71
+		self::TYPE_NULL => Primitive\NullType::class,
72
+		self::TYPE_OBJECT_IDENTIFIER => Primitive\ObjectIdentifier::class,
73
+		self::TYPE_OBJECT_DESCRIPTOR => Primitive\ObjectDescriptor::class,
74
+		self::TYPE_REAL => Primitive\Real::class,
75
+		self::TYPE_ENUMERATED => Primitive\Enumerated::class,
76
+		self::TYPE_UTF8_STRING => Primitive\UTF8String::class,
77
+		self::TYPE_RELATIVE_OID => Primitive\RelativeOID::class,
78
+		self::TYPE_SEQUENCE => Constructed\Sequence::class,
79
+		self::TYPE_SET => Constructed\Set::class,
80
+		self::TYPE_NUMERIC_STRING => Primitive\NumericString::class,
81
+		self::TYPE_PRINTABLE_STRING => Primitive\PrintableString::class,
82
+		self::TYPE_T61_STRING => Primitive\T61String::class,
83
+		self::TYPE_VIDEOTEX_STRING => Primitive\VideotexString::class,
84
+		self::TYPE_IA5_STRING => Primitive\IA5String::class,
85
+		self::TYPE_UTC_TIME => Primitive\UTCTime::class,
86
+		self::TYPE_GENERALIZED_TIME => Primitive\GeneralizedTime::class,
87
+		self::TYPE_GRAPHIC_STRING => Primitive\GraphicString::class,
88
+		self::TYPE_VISIBLE_STRING => Primitive\VisibleString::class,
89
+		self::TYPE_GENERAL_STRING => Primitive\GeneralString::class,
90
+		self::TYPE_UNIVERSAL_STRING => Primitive\UniversalString::class,
91
+		self::TYPE_CHARACTER_STRING => Primitive\CharacterString::class,
92
+		self::TYPE_BMP_STRING => Primitive\BMPString::class,
93
+	];
94
+
95
+	/**
96
+	 * Pseudotype for all string types.
97
+	 *
98
+	 * May be used as an expectation parameter.
99
+	 *
100
+	 * @var int
101
+	 */
102
+	const TYPE_STRING = -1;
103
+
104
+	/**
105
+	 * Pseudotype for all time types.
106
+	 *
107
+	 * May be used as an expectation parameter.
108
+	 *
109
+	 * @var int
110
+	 */
111
+	const TYPE_TIME = -2;
112
+
113
+	/**
114
+	 * Pseudotype for constructed strings.
115
+	 *
116
+	 * May be used as an expectation parameter.
117
+	 *
118
+	 * @var int
119
+	 */
120
+	const TYPE_CONSTRUCTED_STRING = -3;
121
+
122
+	/**
123
+	 * Mapping from universal type tag to human readable name.
124
+	 *
125
+	 * @internal
126
+	 *
127
+	 * @var array
128
+	 */
129
+	const MAP_TYPE_TO_NAME = [
130
+		self::TYPE_EOC => 'EOC',
131
+		self::TYPE_BOOLEAN => 'BOOLEAN',
132
+		self::TYPE_INTEGER => 'INTEGER',
133
+		self::TYPE_BIT_STRING => 'BIT STRING',
134
+		self::TYPE_OCTET_STRING => 'OCTET STRING',
135
+		self::TYPE_NULL => 'NULL',
136
+		self::TYPE_OBJECT_IDENTIFIER => 'OBJECT IDENTIFIER',
137
+		self::TYPE_OBJECT_DESCRIPTOR => 'ObjectDescriptor',
138
+		self::TYPE_EXTERNAL => 'EXTERNAL',
139
+		self::TYPE_REAL => 'REAL',
140
+		self::TYPE_ENUMERATED => 'ENUMERATED',
141
+		self::TYPE_EMBEDDED_PDV => 'EMBEDDED PDV',
142
+		self::TYPE_UTF8_STRING => 'UTF8String',
143
+		self::TYPE_RELATIVE_OID => 'RELATIVE-OID',
144
+		self::TYPE_SEQUENCE => 'SEQUENCE',
145
+		self::TYPE_SET => 'SET',
146
+		self::TYPE_NUMERIC_STRING => 'NumericString',
147
+		self::TYPE_PRINTABLE_STRING => 'PrintableString',
148
+		self::TYPE_T61_STRING => 'T61String',
149
+		self::TYPE_VIDEOTEX_STRING => 'VideotexString',
150
+		self::TYPE_IA5_STRING => 'IA5String',
151
+		self::TYPE_UTC_TIME => 'UTCTime',
152
+		self::TYPE_GENERALIZED_TIME => 'GeneralizedTime',
153
+		self::TYPE_GRAPHIC_STRING => 'GraphicString',
154
+		self::TYPE_VISIBLE_STRING => 'VisibleString',
155
+		self::TYPE_GENERAL_STRING => 'GeneralString',
156
+		self::TYPE_UNIVERSAL_STRING => 'UniversalString',
157
+		self::TYPE_CHARACTER_STRING => 'CHARACTER STRING',
158
+		self::TYPE_BMP_STRING => 'BMPString',
159
+		self::TYPE_STRING => 'Any String',
160
+		self::TYPE_TIME => 'Any Time',
161
+		self::TYPE_CONSTRUCTED_STRING => 'Constructed String',
162
+	];
163
+
164
+	/**
165
+	 * Element's type tag.
166
+	 *
167
+	 * @var int
168
+	 */
169
+	protected $_typeTag;
170
+
171
+	/**
172
+	 * Whether type shall be encoded with indefinite length.
173
+	 *
174
+	 * @var bool
175
+	 */
176
+	protected $_indefiniteLength = false;
177
+
178
+	/**
179
+	 * {@inheritdoc}
180
+	 */
181
+	abstract public function typeClass(): int;
182
+
183
+	/**
184
+	 * {@inheritdoc}
185
+	 */
186
+	abstract public function isConstructed(): bool;
187
+
188
+	/**
189
+	 * Decode element from DER data.
190
+	 *
191
+	 * @param string   $data   DER encoded data
192
+	 * @param null|int $offset Reference to the variable that contains offset
193
+	 *                         into the data where to start parsing.
194
+	 *                         Variable is updated to the offset next to the
195
+	 *                         parsed element. If null, start from offset 0.
196
+	 *
197
+	 * @throws DecodeException           If decoding fails
198
+	 * @throws \UnexpectedValueException If called in the context of an expected
199
+	 *                                   type, but decoding yields another type
200
+	 *
201
+	 * @return ElementBase
202
+	 */
203
+	public static function fromDER(string $data, int &$offset = null): ElementBase
204
+	{
205
+		$idx = $offset ?? 0;
206
+		// decode identifier
207
+		$identifier = Identifier::fromDER($data, $idx);
208
+		// determine class that implements type specific decoding
209
+		$cls = self::_determineImplClass($identifier);
210
+		try {
211
+			// decode remaining element
212
+			$element = $cls::_decodeFromDER($identifier, $data, $idx);
213
+		} catch (\LogicException $e) {
214
+			// rethrow as a RuntimeException for unified exception handling
215
+			throw new DecodeException(
216
+				sprintf('Error while decoding %s.',
217
+					self::tagToName($identifier->intTag())), 0, $e);
218
+		}
219
+		// if called in the context of a concrete class, check
220
+		// that decoded type matches the type of a calling class
221
+		$called_class = get_called_class();
222
+		if (self::class !== $called_class) {
223
+			if (!$element instanceof $called_class) {
224
+				throw new \UnexpectedValueException(
225
+					sprintf('%s expected, got %s.', $called_class,
226
+						get_class($element)));
227
+			}
228
+		}
229
+		// update offset for the caller
230
+		if (isset($offset)) {
231
+			$offset = $idx;
232
+		}
233
+		return $element;
234
+	}
235
+
236
+	/**
237
+	 * {@inheritdoc}
238
+	 */
239
+	public function toDER(): string
240
+	{
241
+		$identifier = new Identifier($this->typeClass(),
242
+			$this->isConstructed() ? Identifier::CONSTRUCTED : Identifier::PRIMITIVE,
243
+			$this->_typeTag);
244
+		$content = $this->_encodedContentDER();
245
+		if ($this->_indefiniteLength) {
246
+			$length = new Length(0, true);
247
+			$eoc = new Primitive\EOC();
248
+			return $identifier->toDER() . $length->toDER() . $content . $eoc->toDER();
249
+		}
250
+		$length = new Length(strlen($content));
251
+		return $identifier->toDER() . $length->toDER() . $content;
252
+	}
253
+
254
+	/**
255
+	 * {@inheritdoc}
256
+	 */
257
+	public function tag(): int
258
+	{
259
+		return $this->_typeTag;
260
+	}
261
+
262
+	/**
263
+	 * {@inheritdoc}
264
+	 */
265
+	public function isType(int $tag): bool
266
+	{
267
+		// if element is context specific
268
+		if (Identifier::CLASS_CONTEXT_SPECIFIC === $this->typeClass()) {
269
+			return false;
270
+		}
271
+		// negative tags identify an abstract pseudotype
272
+		if ($tag < 0) {
273
+			return $this->_isPseudoType($tag);
274
+		}
275
+		return $this->_isConcreteType($tag);
276
+	}
277
+
278
+	/**
279
+	 * {@inheritdoc}
280
+	 */
281
+	public function expectType(int $tag): ElementBase
282
+	{
283
+		if (!$this->isType($tag)) {
284
+			throw new \UnexpectedValueException(
285
+				sprintf('%s expected, got %s.', self::tagToName($tag),
286
+					$this->_typeDescriptorString()));
287
+		}
288
+		return $this;
289
+	}
290
+
291
+	/**
292
+	 * {@inheritdoc}
293
+	 */
294
+	public function isTagged(): bool
295
+	{
296
+		return $this instanceof TaggedType;
297
+	}
298
+
299
+	/**
300
+	 * {@inheritdoc}
301
+	 */
302
+	public function expectTagged(?int $tag = null): TaggedType
303
+	{
304
+		if (!$this->isTagged()) {
305
+			throw new \UnexpectedValueException(
306
+				sprintf('Context specific element expected, got %s.',
307
+					Identifier::classToName($this->typeClass())));
308
+		}
309
+		if (isset($tag) && $this->tag() !== $tag) {
310
+			throw new \UnexpectedValueException(
311
+				sprintf('Tag %d expected, got %d.', $tag, $this->tag()));
312
+		}
313
+		return $this;
314
+	}
315
+
316
+	/**
317
+	 * Whether element has indefinite length.
318
+	 *
319
+	 * @return bool
320
+	 */
321
+	public function hasIndefiniteLength(): bool
322
+	{
323
+		return $this->_indefiniteLength;
324
+	}
325
+
326
+	/**
327
+	 * Get self with indefinite length encoding set.
328
+	 *
329
+	 * @param bool $indefinite True for indefinite length, false for definite length
330
+	 *
331
+	 * @return self
332
+	 */
333
+	public function withIndefiniteLength(bool $indefinite = true): self
334
+	{
335
+		$obj = clone $this;
336
+		$obj->_indefiniteLength = $indefinite;
337
+		return $obj;
338
+	}
339
+
340
+	/**
341
+	 * {@inheritdoc}
342
+	 */
343
+	final public function asElement(): Element
344
+	{
345
+		return $this;
346
+	}
347
+
348
+	/**
349
+	 * Get element decorated with UnspecifiedType object.
350
+	 *
351
+	 * @return UnspecifiedType
352
+	 */
353
+	public function asUnspecified(): UnspecifiedType
354
+	{
355
+		return new UnspecifiedType($this);
356
+	}
357
+
358
+	/**
359
+	 * Get human readable name for an universal tag.
360
+	 *
361
+	 * @param int $tag
362
+	 *
363
+	 * @return string
364
+	 */
365
+	public static function tagToName(int $tag): string
366
+	{
367
+		if (!array_key_exists($tag, self::MAP_TYPE_TO_NAME)) {
368
+			return "TAG {$tag}";
369
+		}
370
+		return self::MAP_TYPE_TO_NAME[$tag];
371
+	}
372
+
373
+	/**
374
+	 * Get the content encoded in DER.
375
+	 *
376
+	 * Returns the DER encoded content without identifier and length header octets.
377
+	 *
378
+	 * @return string
379
+	 */
380
+	abstract protected function _encodedContentDER(): string;
381
+
382
+	/**
383
+	 * Decode type-specific element from DER.
384
+	 *
385
+	 * @param Identifier $identifier Pre-parsed identifier
386
+	 * @param string     $data       DER data
387
+	 * @param int        $offset     Offset in data to the next byte after identifier
388
+	 *
389
+	 * @throws DecodeException If decoding fails
390
+	 *
391
+	 * @return ElementBase
392
+	 */
393
+	protected static function _decodeFromDER(Identifier $identifier,
394
+		string $data, int &$offset): ElementBase
395
+	{
396
+		throw new \BadMethodCallException(
397
+			__METHOD__ . ' must be implemented in derived class.');
398
+	}
399
+
400
+	/**
401
+	 * Determine the class that implements the type.
402
+	 *
403
+	 * @param Identifier $identifier
404
+	 *
405
+	 * @return string Class name
406
+	 */
407
+	protected static function _determineImplClass(Identifier $identifier): string
408
+	{
409
+		switch ($identifier->typeClass()) {
410
+			case Identifier::CLASS_UNIVERSAL:
411
+				$cls = self::_determineUniversalImplClass($identifier->intTag());
412
+				// constructed strings may be present in BER
413
+				if ($identifier->isConstructed() &&
414
+					is_subclass_of($cls, StringType::class)) {
415
+					$cls = ConstructedString::class;
416
+				}
417
+				return $cls;
418
+			case Identifier::CLASS_CONTEXT_SPECIFIC:
419
+				return ContextSpecificType::class;
420
+			case Identifier::CLASS_APPLICATION:
421
+				return ApplicationType::class;
422
+			case Identifier::CLASS_PRIVATE:
423
+				return PrivateType::class;
424
+		}
425
+		throw new \UnexpectedValueException(
426
+			sprintf('%s %d not implemented.',
427
+				Identifier::classToName($identifier->typeClass()),
428
+				$identifier->tag()));
429
+	}
430
+
431
+	/**
432
+	 * Determine the class that implements an universal type of the given tag.
433
+	 *
434
+	 * @param int $tag
435
+	 *
436
+	 * @throws \UnexpectedValueException
437
+	 *
438
+	 * @return string Class name
439
+	 */
440
+	protected static function _determineUniversalImplClass(int $tag): string
441
+	{
442
+		if (!array_key_exists($tag, self::MAP_TAG_TO_CLASS)) {
443
+			throw new \UnexpectedValueException(
444
+				"Universal tag {$tag} not implemented.");
445
+		}
446
+		return self::MAP_TAG_TO_CLASS[$tag];
447
+	}
448
+
449
+	/**
450
+	 * Get textual description of the type for debugging purposes.
451
+	 *
452
+	 * @return string
453
+	 */
454
+	protected function _typeDescriptorString(): string
455
+	{
456
+		if (Identifier::CLASS_UNIVERSAL === $this->typeClass()) {
457
+			return self::tagToName($this->_typeTag);
458
+		}
459
+		return sprintf('%s TAG %d', Identifier::classToName($this->typeClass()),
460
+			$this->_typeTag);
461
+	}
462
+
463
+	/**
464
+	 * Check whether the element is a concrete type of a given tag.
465
+	 *
466
+	 * @param int $tag
467
+	 *
468
+	 * @return bool
469
+	 */
470
+	private function _isConcreteType(int $tag): bool
471
+	{
472
+		// if tag doesn't match
473
+		if ($this->tag() !== $tag) {
474
+			return false;
475
+		}
476
+		// if type is universal check that instance is of a correct class
477
+		if (Identifier::CLASS_UNIVERSAL === $this->typeClass()) {
478
+			$cls = self::_determineUniversalImplClass($tag);
479
+			if (!$this instanceof $cls) {
480
+				return false;
481
+			}
482
+		}
483
+		return true;
484
+	}
485
+
486
+	/**
487
+	 * Check whether the element is a pseudotype.
488
+	 *
489
+	 * @param int $tag
490
+	 *
491
+	 * @return bool
492
+	 */
493
+	private function _isPseudoType(int $tag): bool
494
+	{
495
+		switch ($tag) {
496
+			case self::TYPE_STRING:
497
+				return $this instanceof StringType;
498
+			case self::TYPE_TIME:
499
+				return $this instanceof TimeType;
500
+			case self::TYPE_CONSTRUCTED_STRING:
501
+				return $this instanceof ConstructedString;
502
+		}
503
+		return false;
504
+	}
505 505
 }
Please login to merge, or discard this patch.
Switch Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -407,20 +407,20 @@  discard block
 block discarded – undo
407 407
     protected static function _determineImplClass(Identifier $identifier): string
408 408
     {
409 409
         switch ($identifier->typeClass()) {
410
-            case Identifier::CLASS_UNIVERSAL:
411
-                $cls = self::_determineUniversalImplClass($identifier->intTag());
412
-                // constructed strings may be present in BER
413
-                if ($identifier->isConstructed() &&
414
-                    is_subclass_of($cls, StringType::class)) {
415
-                    $cls = ConstructedString::class;
416
-                }
417
-                return $cls;
418
-            case Identifier::CLASS_CONTEXT_SPECIFIC:
419
-                return ContextSpecificType::class;
420
-            case Identifier::CLASS_APPLICATION:
421
-                return ApplicationType::class;
422
-            case Identifier::CLASS_PRIVATE:
423
-                return PrivateType::class;
410
+        case Identifier::CLASS_UNIVERSAL:
411
+            $cls = self::_determineUniversalImplClass($identifier->intTag());
412
+            // constructed strings may be present in BER
413
+            if ($identifier->isConstructed() &&
414
+                is_subclass_of($cls, StringType::class)) {
415
+                $cls = ConstructedString::class;
416
+            }
417
+            return $cls;
418
+        case Identifier::CLASS_CONTEXT_SPECIFIC:
419
+            return ContextSpecificType::class;
420
+        case Identifier::CLASS_APPLICATION:
421
+            return ApplicationType::class;
422
+        case Identifier::CLASS_PRIVATE:
423
+            return PrivateType::class;
424 424
         }
425 425
         throw new \UnexpectedValueException(
426 426
             sprintf('%s %d not implemented.',
@@ -493,12 +493,12 @@  discard block
 block discarded – undo
493 493
     private function _isPseudoType(int $tag): bool
494 494
     {
495 495
         switch ($tag) {
496
-            case self::TYPE_STRING:
497
-                return $this instanceof StringType;
498
-            case self::TYPE_TIME:
499
-                return $this instanceof TimeType;
500
-            case self::TYPE_CONSTRUCTED_STRING:
501
-                return $this instanceof ConstructedString;
496
+        case self::TYPE_STRING:
497
+            return $this instanceof StringType;
498
+        case self::TYPE_TIME:
499
+            return $this instanceof TimeType;
500
+        case self::TYPE_CONSTRUCTED_STRING:
501
+            return $this instanceof ConstructedString;
502 502
         }
503 503
         return false;
504 504
     }
Please login to merge, or discard this patch.