PdfArray.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * This file is part of FPDI
  4. *
  5. * @package Fpdi
  6. * @copyright Copyright (c) 2020 Setasign GmbH & Co. KG (https://www.setasign.com)
  7. * @license http://opensource.org/licenses/mit-license The MIT License
  8. */
  9. namespace Fpdi\PdfParser\Type;
  10. use Fpdi\PdfParser\PdfParser;
  11. use Fpdi\PdfParser\Tokenizer;
  12. /**
  13. * Class representing a PDF array object
  14. *
  15. * @property array $value The value of the PDF type.
  16. */
  17. class PdfArray extends PdfType
  18. {
  19. /**
  20. * Parses an array of the passed tokenizer and parser.
  21. *
  22. * @param Tokenizer $tokenizer
  23. * @param PdfParser $parser
  24. * @return bool|self
  25. * @throws PdfTypeException
  26. */
  27. public static function parse(Tokenizer $tokenizer, PdfParser $parser)
  28. {
  29. $result = [];
  30. // Recurse into this function until we reach the end of the array.
  31. while (($token = $tokenizer->getNextToken()) !== ']') {
  32. if ($token === false || ($value = $parser->readValue($token)) === false) {
  33. return false;
  34. }
  35. $result[] = $value;
  36. }
  37. $v = new self();
  38. $v->value = $result;
  39. return $v;
  40. }
  41. /**
  42. * Helper method to create an instance.
  43. *
  44. * @param PdfType[] $values
  45. * @return self
  46. */
  47. public static function create(array $values = [])
  48. {
  49. $v = new self();
  50. $v->value = $values;
  51. return $v;
  52. }
  53. /**
  54. * Ensures that the passed array is a PdfArray instance with a (optional) specific size.
  55. *
  56. * @param mixed $array
  57. * @param null|int $size
  58. * @return self
  59. * @throws PdfTypeException
  60. */
  61. public static function ensure($array, $size = null)
  62. {
  63. $result = PdfType::ensureType(self::class, $array, 'Array value expected.');
  64. if ($size !== null && \count($array->value) !== $size) {
  65. throw new PdfTypeException(
  66. \sprintf('Array with %s entries expected.', $size),
  67. PdfTypeException::INVALID_DATA_SIZE
  68. );
  69. }
  70. return $result;
  71. }
  72. }