PdfName.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\StreamReader;
  11. use Fpdi\PdfParser\Tokenizer;
  12. /**
  13. * Class representing a PDF name object
  14. */
  15. class PdfName extends PdfType
  16. {
  17. /**
  18. * Parses a name object from the passed tokenizer and stream-reader.
  19. *
  20. * @param Tokenizer $tokenizer
  21. * @param StreamReader $streamReader
  22. * @return self
  23. */
  24. public static function parse(Tokenizer $tokenizer, StreamReader $streamReader)
  25. {
  26. $v = new self();
  27. if (\strspn($streamReader->getByte(), "\x00\x09\x0A\x0C\x0D\x20()<>[]{}/%") === 0) {
  28. $v->value = (string) $tokenizer->getNextToken();
  29. return $v;
  30. }
  31. $v->value = '';
  32. return $v;
  33. }
  34. /**
  35. * Unescapes a name string.
  36. *
  37. * @param string $value
  38. * @return string
  39. */
  40. public static function unescape($value)
  41. {
  42. if (strpos($value, '#') === false) {
  43. return $value;
  44. }
  45. return preg_replace_callback('/#([a-fA-F\d]{2})/', function ($matches) {
  46. return chr(hexdec($matches[1]));
  47. }, $value);
  48. }
  49. /**
  50. * Helper method to create an instance.
  51. *
  52. * @param string $string
  53. * @return self
  54. */
  55. public static function create($string)
  56. {
  57. $v = new self();
  58. $v->value = $string;
  59. return $v;
  60. }
  61. /**
  62. * Ensures that the passed value is a PdfName instance.
  63. *
  64. * @param mixed $name
  65. * @return self
  66. * @throws PdfTypeException
  67. */
  68. public static function ensure($name)
  69. {
  70. return PdfType::ensureType(self::class, $name, 'Name value expected.');
  71. }
  72. }