SerializeXMLObject.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace MGModule\DNSManager2\mgLibs\custom\helpers;
  3. class SerializeXMLObject
  4. {
  5. protected static $instace;
  6. protected $data;
  7. private function __construct($data = null)
  8. {
  9. $this->data = $data;
  10. }
  11. private function __clone()
  12. {
  13. ;
  14. }
  15. public static function getInstance($data = null)
  16. {
  17. if (is_null(self::$instace))
  18. {
  19. $class = get_class();
  20. self::$instace = new $class($data);
  21. }
  22. return self::$instace;
  23. }
  24. public function refactor()
  25. {
  26. foreach ($this->data as $field)
  27. {
  28. $function = $this->checkTypeAndGetFunction($field);
  29. if ($function)
  30. {
  31. $this->{$function}($field);
  32. }
  33. else
  34. {
  35. return $this->data;
  36. }
  37. }
  38. return $this->data;
  39. }
  40. private function checkTypeAndGetFunction($data)
  41. {
  42. if (is_array($data))
  43. {
  44. return 'refactorArray';
  45. }
  46. if (is_object($data))
  47. {
  48. return 'refactorObject';
  49. }
  50. }
  51. protected function refactorObject(&$data)
  52. {
  53. foreach ($data as $fieldName => $fieldValue)
  54. {
  55. $function = $this->checkTypeAndGetFunction($fieldValue);
  56. if ($function)
  57. {
  58. if ($fieldValue instanceof \SimpleXMLElement)
  59. {
  60. $data->{$fieldName} = $this->readXML($fieldValue);
  61. }
  62. else
  63. {
  64. $this->{$function}($fieldValue);
  65. }
  66. }
  67. }
  68. }
  69. protected function refactorArray(&$data)
  70. {
  71. foreach ($data as $fieldName => $fieldValue)
  72. {
  73. $function = $this->checkTypeAndGetFunction($fieldValue);
  74. if ($function)
  75. {
  76. $this->{$function}($fieldValue);
  77. }
  78. }
  79. }
  80. private function readXML(\SimpleXMLElement $xml)
  81. {
  82. if ($xml->count() > 0)
  83. {
  84. return $xml->{$xml->getName()};
  85. }
  86. return "";
  87. }
  88. }