ReplacementArray.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. /**
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License along
  14. * with this program; if not, write to the Free Software Foundation, Inc.,
  15. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. * http://www.gnu.org/copyleft/gpl.html
  17. *
  18. * @file
  19. */
  20. /**
  21. * Wrapper around strtr() that holds replacements
  22. */
  23. class ReplacementArray {
  24. private $data = [];
  25. /**
  26. * Create an object with the specified replacement array
  27. * The array should have the same form as the replacement array for strtr()
  28. * @param array $data
  29. */
  30. public function __construct( array $data = [] ) {
  31. $this->data = $data;
  32. }
  33. /**
  34. * @return array
  35. */
  36. public function __sleep() {
  37. return [ 'data' ];
  38. }
  39. /**
  40. * Set the whole replacement array at once
  41. * @param array $data
  42. */
  43. public function setArray( array $data ) {
  44. $this->data = $data;
  45. }
  46. /**
  47. * @return array
  48. */
  49. public function getArray() {
  50. return $this->data;
  51. }
  52. /**
  53. * Set an element of the replacement array
  54. * @param string $from
  55. * @param string $to
  56. */
  57. public function setPair( $from, $to ) {
  58. $this->data[$from] = $to;
  59. }
  60. /**
  61. * @param array $data
  62. */
  63. public function mergeArray( $data ) {
  64. $this->data = $data + $this->data;
  65. }
  66. /**
  67. * @param ReplacementArray $other
  68. */
  69. public function merge( ReplacementArray $other ) {
  70. $this->data = $other->data + $this->data;
  71. }
  72. /**
  73. * @param string $from
  74. */
  75. public function removePair( $from ) {
  76. unset( $this->data[$from] );
  77. }
  78. /**
  79. * @param array $data
  80. */
  81. public function removeArray( $data ) {
  82. foreach ( $data as $from => $to ) {
  83. $this->removePair( $from );
  84. }
  85. }
  86. /**
  87. * @param string $subject
  88. * @return string
  89. */
  90. public function replace( $subject ) {
  91. return strtr( $subject, $this->data );
  92. }
  93. }