LifecycleConfig.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace OSS\Model;
  3. use OSS\Core\OssException;
  4. /**
  5. * Class BucketLifecycleConfig
  6. * @package OSS\Model
  7. * @link http://help.aliyun.com/document_detail/oss/api-reference/bucket/PutBucketLifecycle.html
  8. */
  9. class LifecycleConfig implements XmlConfig
  10. {
  11. /**
  12. * 从xml数据中解析出LifecycleConfig
  13. *
  14. * @param string $strXml
  15. * @throws OssException
  16. * @return null
  17. */
  18. public function parseFromXml($strXml)
  19. {
  20. $this->rules = array();
  21. $xml = simplexml_load_string($strXml);
  22. if (!isset($xml->Rule)) return;
  23. $this->rules = array();
  24. foreach ($xml->Rule as $rule) {
  25. $id = strval($rule->ID);
  26. $prefix = strval($rule->Prefix);
  27. $status = strval($rule->Status);
  28. $actions = array();
  29. foreach ($rule as $key => $value) {
  30. if ($key === 'ID' || $key === 'Prefix' || $key === 'Status') continue;
  31. $action = $key;
  32. $timeSpec = null;
  33. $timeValue = null;
  34. foreach ($value as $timeSpecKey => $timeValueValue) {
  35. $timeSpec = $timeSpecKey;
  36. $timeValue = strval($timeValueValue);
  37. }
  38. $actions[] = new LifecycleAction($action, $timeSpec, $timeValue);
  39. }
  40. $this->rules[] = new LifecycleRule($id, $prefix, $status, $actions);
  41. }
  42. return;
  43. }
  44. /**
  45. * 生成xml字符串
  46. *
  47. * @return string
  48. */
  49. public function serializeToXml()
  50. {
  51. $xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><LifecycleConfiguration></LifecycleConfiguration>');
  52. foreach ($this->rules as $rule) {
  53. $xmlRule = $xml->addChild('Rule');
  54. $rule->appendToXml($xmlRule);
  55. }
  56. return $xml->asXML();
  57. }
  58. /**
  59. *
  60. * 添加LifecycleRule
  61. *
  62. * @param LifecycleRule $lifecycleRule
  63. * @throws OssException
  64. */
  65. public function addRule($lifecycleRule)
  66. {
  67. if (!isset($lifecycleRule)) {
  68. throw new OssException("lifecycleRule is null");
  69. }
  70. $this->rules[] = $lifecycleRule;
  71. }
  72. /**
  73. * 将配置转换成字符串,便于用户查看
  74. *
  75. * @return string
  76. */
  77. public function __toString()
  78. {
  79. return $this->serializeToXml();
  80. }
  81. /**
  82. * 得到所有的生命周期规则
  83. *
  84. * @return LifecycleRule[]
  85. */
  86. public function getRules()
  87. {
  88. return $this->rules;
  89. }
  90. /**
  91. * @var LifecycleRule[]
  92. */
  93. private $rules;
  94. }