Hoa central
Attribute.php
Go to the documentation of this file.
1 <?php
2 
37 namespace Hoa\Xml;
38 
47 class Attribute
48 {
54  protected $_attributes = [];
55 
56 
57 
58 
66  public function __construct($string = null)
67  {
68  if (null === $string) {
69  return;
70  }
71 
72  $out = preg_match_all(
73  '#(\w+)\s*(=\s*(?<!\\\)(?:("|\')|)(?(3)(.*?)(?<!\\\)\3|(\w+))\s*)?#',
74  trim($string),
75  $attributes,
76  PREG_SET_ORDER
77  );
78 
79  if (0 === $out) {
80  throw new Exception(
81  'The string %s does not represent attributes.',
82  0,
83  $string
84  );
85  }
86 
87  foreach ($attributes as $i => $attribute) {
88  if (!isset($attribute[2])) {
89  // Boolean: abc
90  $this->_attributes[$attribute[1]] = $attribute[1];
91  } elseif (!isset($attribute[5])) {
92  // Quote: abc="def" or abc='def'
93  $this->_attributes[$attribute[1]] = str_replace(
94  '\\' . $attribute[3],
95  $attribute[3],
96  $attribute[4]
97  );
98  } else {
99  // No-quote: abc=def
100  $this->_attributes[$attribute[1]] = $attribute[5];
101  }
102  }
103  }
104 
110  public function readAttributes()
111  {
112  return $this->_attributes;
113  }
114 
121  public function readAttribute($name)
122  {
123  if (false === $this->attributeExists($name)) {
124  return null;
125  }
126 
127  return $this->_attributes[$name];
128  }
129 
136  public function attributeExists($name)
137  {
138  return true === array_key_exists($name, $this->_attributes);
139  }
140 
146  public function readAttributesAsList()
147  {
148  $attributes = $this->_attributes;
149 
150  foreach ($attributes as $name => &$value) {
151  $value = explode(' ', $value);
152  }
153 
154  return $attributes;
155  }
156 
163  public function readAttributeAsList($name)
164  {
165  return explode(' ', $this->readAttribute($name));
166  }
167 
175  public function writeAttributes(Array $attributes)
176  {
177  foreach ($attributes as $name => $value) {
178  $this->writeAttribute($name, $value);
179  }
180 
181  return;
182  }
183 
192  public function writeAttribute($name, $value)
193  {
194  $this->_attributes[$name] = $value;
195 
196  return;
197  }
198 
205  public function removeAttribute($name)
206  {
207  unset($this->_attributes[$name]);
208 
209  return;
210  }
211 
217  public function __toString()
218  {
219  $out = null;
220 
221  foreach ($this->_attributes as $key => $value) {
222  $out .= $key . '="' . str_replace('"', '\"', $value) . '" ';
223  }
224 
225  return substr($out, 0, -1);
226  }
227 }
writeAttributes(Array $attributes)
Definition: Attribute.php:175
removeAttribute($name)
Definition: Attribute.php:205
attributeExists($name)
Definition: Attribute.php:136
__construct($string=null)
Definition: Attribute.php:66
writeAttribute($name, $value)
Definition: Attribute.php:192
readAttributeAsList($name)
Definition: Attribute.php:163
readAttribute($name)
Definition: Attribute.php:121