encoding_converter.class.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * Convert text from one encoding to another. Usage:
  4. *
  5. * $converter = EncodingConverter::create($from, $to);
  6. * $converter->convert($text);
  7. *
  8. * Note that the create function will returns an identify converter if from and to
  9. * encodings are the same. Reason why the constructor is private.
  10. *
  11. * @copyright (c) 2012 University of Geneva
  12. * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html
  13. * @author Laurent Opprecht <laurent@opprecht.info>
  14. */
  15. class EncodingConverter extends Converter
  16. {
  17. /**
  18. *
  19. * @param string $from_encoding
  20. * @param string $to_encoding
  21. *
  22. * @return EncodingConverter
  23. */
  24. public static function create($from_encoding, $to_encoding)
  25. {
  26. $from_encoding = (string) $from_encoding;
  27. $to_encoding = (string) $to_encoding;
  28. if (strtolower($from_encoding) == strtolower($to_encoding)) {
  29. return Converter::identity();
  30. } else {
  31. return new self($from_encoding, $to_encoding);
  32. }
  33. }
  34. protected $from_encoding;
  35. protected $to_encoding;
  36. protected function __construct($from_encoding, $to_encoding)
  37. {
  38. $this->from_encoding = $from_encoding;
  39. $this->to_encoding = $to_encoding;
  40. }
  41. function from_encoding()
  42. {
  43. return $this->from_encoding;
  44. }
  45. function to_encoding()
  46. {
  47. return $this->to_encoding;
  48. }
  49. function convert($string)
  50. {
  51. $from = $this->from_encoding;
  52. $to = $this->to_encoding;
  53. if ($from == $to) {
  54. return $string;
  55. }
  56. return api_convert_encoding($string, $to, $from);
  57. }
  58. function reset()
  59. {
  60. ;
  61. }
  62. }