GenericFixedWidthReader.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /*
  3. * This file is part of SwiftMailer.
  4. * (c) 2004-2009 Chris Corbyn
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * Provides fixed-width byte sizes for reading fixed-width character sets.
  11. *
  12. * @author Chris Corbyn
  13. * @author Xavier De Cock <xdecock@gmail.com>
  14. */
  15. class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterReader
  16. {
  17. /**
  18. * The number of bytes in a single character.
  19. *
  20. * @var int
  21. */
  22. private $_width;
  23. /**
  24. * Creates a new GenericFixedWidthReader using $width bytes per character.
  25. *
  26. * @param int $width
  27. */
  28. public function __construct($width)
  29. {
  30. $this->_width = $width;
  31. }
  32. /**
  33. * Returns the complete character map.
  34. *
  35. * @param string $string
  36. * @param int $startOffset
  37. * @param array $currentMap
  38. * @param mixed $ignoredChars
  39. *
  40. * @return int
  41. */
  42. public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars)
  43. {
  44. $strlen = strlen($string);
  45. // % and / are CPU intensive, so, maybe find a better way
  46. $ignored = $strlen % $this->_width;
  47. $ignoredChars = substr($string, - $ignored);
  48. $currentMap = $this->_width;
  49. return ($strlen - $ignored) / $this->_width;
  50. }
  51. /**
  52. * Returns the mapType.
  53. *
  54. * @return int
  55. */
  56. public function getMapType()
  57. {
  58. return self::MAP_TYPE_FIXED_LEN;
  59. }
  60. /**
  61. * Returns an integer which specifies how many more bytes to read.
  62. *
  63. * A positive integer indicates the number of more bytes to fetch before invoking
  64. * this method again.
  65. *
  66. * A value of zero means this is already a valid character.
  67. * A value of -1 means this cannot possibly be a valid character.
  68. *
  69. * @param string $bytes
  70. * @param int $size
  71. *
  72. * @return int
  73. */
  74. public function validateByteSequence($bytes, $size)
  75. {
  76. $needed = $this->_width - $size;
  77. return ($needed > -1) ? $needed : -1;
  78. }
  79. /**
  80. * Returns the number of bytes which should be read to start each character.
  81. *
  82. * @return int
  83. */
  84. public function getInitialByteSize()
  85. {
  86. return $this->_width;
  87. }
  88. }