| 1 |
<?php |
| 2 |
/* |
| 3 |
* This file is part of the PHPASN1 library. |
| 4 |
* |
| 5 |
* Copyright © Friedrich Große <[email protected]> |
| 6 |
* |
| 7 |
* For the full copyright and license information, please view the LICENSE |
| 8 |
* file that was distributed with this source code. |
| 9 |
*/ |
| 10 |
|
| 11 |
namespace WP_DEFENDER_VENDOR\FG\ASN1; |
| 12 |
|
| 13 |
use Exception; |
| 14 |
use WP_DEFENDER_VENDOR\FG\ASN1\Exception\ParserException; |
| 15 |
use WP_DEFENDER_VENDOR\FG\ASN1\Universal\Sequence; |
| 16 |
|
| 17 |
class TemplateParser |
| 18 |
{ |
| 19 |
/** |
| 20 |
* @param string $data |
| 21 |
* @param array $template |
| 22 |
* @return \WP_DEFENDER_VENDOR\FG\ASN1\ASNObject|Sequence |
| 23 |
* @throws ParserException if there was an issue parsing |
| 24 |
*/ |
| 25 |
public function parseBase64($data, array $template) |
| 26 |
{ |
| 27 |
// TODO test with invalid data |
| 28 |
return $this->parseBinary(base64_decode($data), $template); |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* @param string $binary |
| 33 |
* @param array $template |
| 34 |
* @return \WP_DEFENDER_VENDOR\FG\ASN1\ASNObject|Sequence |
| 35 |
* @throws ParserException if there was an issue parsing |
| 36 |
*/ |
| 37 |
public function parseBinary($binary, array $template) |
| 38 |
{ |
| 39 |
$parsedObject = ASNObject::fromBinary($binary); |
| 40 |
|
| 41 |
foreach ($template as $key => $value) { |
| 42 |
$this->validate($parsedObject, $key, $value); |
| 43 |
} |
| 44 |
|
| 45 |
return $parsedObject; |
| 46 |
} |
| 47 |
|
| 48 |
private function validate(ASNObject $object, $key, $value) |
| 49 |
{ |
| 50 |
if (is_array($value)) { |
| 51 |
$this->assertTypeId($key, $object); |
| 52 |
|
| 53 |
/* @var Construct $object */ |
| 54 |
foreach ($value as $key => $child) { |
| 55 |
$this->validate($object->current(), $key, $child); |
| 56 |
$object->next(); |
| 57 |
} |
| 58 |
} else { |
| 59 |
$this->assertTypeId($value, $object); |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
private function assertTypeId($expectedTypeId, ASNObject $object) |
| 64 |
{ |
| 65 |
$actualType = $object->getType(); |
| 66 |
if ($expectedTypeId != $actualType) { |
| 67 |
throw new Exception("Expected type ($expectedTypeId) does not match actual type ($actualType"); |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
|