TemplateParser.php 1.9 KB

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