2
0

DefaultExtraField.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace PhpZip\Extra;
  3. use PhpZip\Exception\ZipException;
  4. /**
  5. * Default implementation for an Extra Field in a Local or Central Header of a
  6. * ZIP file.
  7. *
  8. * @author Ne-Lexa alexey@nelexa.ru
  9. * @license MIT
  10. */
  11. class DefaultExtraField extends ExtraField
  12. {
  13. /**
  14. * @var int
  15. */
  16. private static $headerId;
  17. /**
  18. * @var string
  19. */
  20. private $data;
  21. /**
  22. * Constructs a new Extra Field.
  23. *
  24. * @param int $headerId an unsigned short integer (two bytes) indicating the
  25. * type of the Extra Field.
  26. * @throws ZipException
  27. */
  28. public function __construct($headerId)
  29. {
  30. if (0x0000 > $headerId || $headerId > 0xffff) {
  31. throw new ZipException('headerId out of range');
  32. }
  33. self::$headerId = $headerId;
  34. }
  35. /**
  36. * Returns the Header ID (type) of this Extra Field.
  37. * The Header ID is an unsigned short integer (two bytes)
  38. * which must be constant during the life cycle of this object.
  39. *
  40. * @return int
  41. */
  42. public static function getHeaderId()
  43. {
  44. return self::$headerId & 0xffff;
  45. }
  46. /**
  47. * Returns the Data Size of this Extra Field.
  48. * The Data Size is an unsigned short integer (two bytes)
  49. * which indicates the length of the Data Block in bytes and does not
  50. * include its own size in this Extra Field.
  51. * This property may be initialized by calling ExtraField::readFrom.
  52. *
  53. * @return int The size of the Data Block in bytes
  54. * or 0 if unknown.
  55. */
  56. public function getDataSize()
  57. {
  58. return null !== $this->data ? strlen($this->data) : 0;
  59. }
  60. /**
  61. * Initializes this Extra Field by deserializing a Data Block of
  62. * size bytes $size from the resource $handle at the zero based offset $off.
  63. *
  64. * @param resource $handle
  65. * @param int $off Offset bytes
  66. * @param int $size Size
  67. * @throws ZipException
  68. */
  69. public function readFrom($handle, $off, $size)
  70. {
  71. if (0x0000 > $size || $size > 0xffff) {
  72. throw new ZipException('size out of range');
  73. }
  74. if ($size > 0) {
  75. fseek($handle, $off, SEEK_SET);
  76. $this->data = fread($handle, $size);
  77. }
  78. }
  79. /**
  80. * @param resource $handle
  81. * @param int $off
  82. */
  83. public function writeTo($handle, $off)
  84. {
  85. if (null !== $this->data) {
  86. fseek($handle, $off, SEEK_SET);
  87. fwrite($handle, $this->data);
  88. }
  89. }
  90. }