Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Data Structures | Public Member Functions | Protected Member Functions | Protected Attributes | Static Protected Attributes
DataObject Class Reference
Inheritance diagram for DataObject:
AsyncResponse BulkSummary ItemStatus Operation OperationStatus Request Response Item Config Customer Order Backup Layer AbstractFilter Item State ListCompare Condition Option DefaultType Url Visibility Breadcrumbs Job Catalog Cart Cart Config Storage Config Template CustomerSecure AbstractIncrement DataArray AbstractForm Schema Node Event Observer Simple Lock AbstractModel Iterator View Storage Response Url QueryParamsResolver RouteParamsResolver AbstractBlock Document UiComponentFactory Save EntityCmsPage AbstractModel Indexer Multishipping State Result AbstractApi Request Request RateRequest AbstractResult Total Log Config Item AbstractAction AbstractCondition CreditmemoLoader Create Order AbstractPdf DefaultTotal Total AbstractTotal Codegenerator Item QuoteConfiguration ShipmentLoader AbstractCarrier Config Info Request ReturnShipment AbstractResult Emulation Store AbstractType AbstractComponent Item Password Swagger

Data Structures

class  CopyTest
 

Public Member Functions

 __construct (array $data=[])
 
 addData (array $arr)
 
 setData ($key, $value=null)
 
 unsetData ($key=null)
 
 getData ($key='', $index=null)
 
 getDataByPath ($path)
 
 getDataByKey ($key)
 
 setDataUsingMethod ($key, $args=[])
 
 getDataUsingMethod ($key, $args=null)
 
 hasData ($key='')
 
 toArray (array $keys=[])
 
 convertToArray (array $keys=[])
 
 toXml (array $keys=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 convertToXml (array $arrAttributes=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 toJson (array $keys=[])
 
 convertToJson (array $keys=[])
 
 toString ($format='')
 
 __call ($method, $args)
 
 isEmpty ()
 
 serialize ($keys=[], $valueSeparator='=', $fieldSeparator=' ', $quote='"')
 
 debug ($data=null, &$objects=[])
 
 offsetSet ($offset, $value)
 
 offsetExists ($offset)
 
 offsetUnset ($offset)
 
 offsetGet ($offset)
 

Protected Member Functions

 _getData ($key)
 
 _underscore ($name)
 

Protected Attributes

 $_data = []
 

Static Protected Attributes

static $_underscoreCache = []
 

Detailed Description

Universal data container with array access implementation

@api @SuppressWarnings(PHPMD.NumberOfChildren)

Since
100.0.2

Definition at line 15 of file DataObject.php.

Constructor & Destructor Documentation

◆ __construct()

__construct ( array  $data = [])

Constructor

By default is looking for first argument as array and assigns it as object attributes This behavior may change in child classes

Parameters
array$data

Definition at line 39 of file DataObject.php.

40  {
41  $this->_data = $data;
42  }

Member Function Documentation

◆ __call()

__call (   $method,
  $args 
)

Set/Get attribute wrapper

Parameters
string$method
array$args
Returns
mixed
Exceptions

Definition at line 380 of file DataObject.php.

381  {
382  switch (substr($method, 0, 3)) {
383  case 'get':
384  $key = $this->_underscore(substr($method, 3));
385  $index = isset($args[0]) ? $args[0] : null;
386  return $this->getData($key, $index);
387  case 'set':
388  $key = $this->_underscore(substr($method, 3));
389  $value = isset($args[0]) ? $args[0] : null;
390  return $this->setData($key, $value);
391  case 'uns':
392  $key = $this->_underscore(substr($method, 3));
393  return $this->unsetData($key);
394  case 'has':
395  $key = $this->_underscore(substr($method, 3));
396  return isset($this->_data[$key]);
397  }
398  throw new \Magento\Framework\Exception\LocalizedException(
399  new \Magento\Framework\Phrase('Invalid method %1::%2', [get_class($this), $method])
400  );
401  }
getData($key='', $index=null)
Definition: DataObject.php:119
$value
Definition: gender.phtml:16
$method
Definition: info.phtml:13
setData($key, $value=null)
Definition: DataObject.php:72
$index
Definition: list.phtml:44

◆ _getData()

_getData (   $key)
protected

Get value from _data array without parse key

Parameters
string$key
Returns
mixed

Definition at line 189 of file DataObject.php.

190  {
191  if (isset($this->_data[$key])) {
192  return $this->_data[$key];
193  }
194  return null;
195  }

◆ _underscore()

_underscore (   $name)
protected

Converts field names for setters and getters

$this->setMyField($value) === $this->setData('my_field', $value) Uses cache to eliminate unnecessary preg_replace

Parameters
string$name
Returns
string

Definition at line 425 of file DataObject.php.

426  {
427  if (isset(self::$_underscoreCache[$name])) {
428  return self::$_underscoreCache[$name];
429  }
430  $result = strtolower(trim(preg_replace('/([A-Z]|[0-9]+)/', "_$1", $name), '_'));
431  self::$_underscoreCache[$name] = $result;
432  return $result;
433  }
if(!isset($_GET['name'])) $name
Definition: log.php:14

◆ addData()

addData ( array  $arr)

Add data to the object.

Retains previous data in the object.

Parameters
array$arr
Returns
$this

Definition at line 52 of file DataObject.php.

53  {
54  foreach ($arr as $index => $value) {
55  $this->setData($index, $value);
56  }
57  return $this;
58  }
$value
Definition: gender.phtml:16
setData($key, $value=null)
Definition: DataObject.php:72
$index
Definition: list.phtml:44

◆ convertToArray()

convertToArray ( array  $keys = [])

The "__" style wrapper for toArray method

Parameters
array$keys
Returns
array

Definition at line 268 of file DataObject.php.

269  {
270  return $this->toArray($keys);
271  }

◆ convertToJson()

convertToJson ( array  $keys = [])

The "__" style wrapper for toJson

Parameters
array$keys
Returns
bool|string
Exceptions

Definition at line 345 of file DataObject.php.

346  {
347  return $this->toJson($keys);
348  }

◆ convertToXml()

convertToXml ( array  $arrAttributes = [],
  $rootName = 'item',
  $addOpenTag = false,
  $addCdata = true 
)

The "__" style wrapper for toXml method

Parameters
array$arrAttributesarray of keys that must be represented
string$rootNameroot node name
bool$addOpenTagflag that allow to add initial xml node
bool$addCdataflag that require wrap all values in CDATA
Returns
string

Definition at line 316 of file DataObject.php.

321  {
322  return $this->toXml($arrAttributes, $rootName, $addOpenTag, $addCdata);
323  }
toXml(array $keys=[], $rootName='item', $addOpenTag=false, $addCdata=true)
Definition: DataObject.php:282

◆ debug()

debug (   $data = null,
$objects = [] 
)

Present object data as string in debug mode

Parameters
mixed$data
array&$objects
Returns
array

Definition at line 469 of file DataObject.php.

470  {
471  if ($data === null) {
472  $hash = spl_object_hash($this);
473  if (!empty($objects[$hash])) {
474  return '*** RECURSION ***';
475  }
476  $objects[$hash] = true;
477  $data = $this->getData();
478  }
479  $debug = [];
480  foreach ($data as $key => $value) {
481  if (is_scalar($value)) {
482  $debug[$key] = $value;
483  } elseif (is_array($value)) {
484  $debug[$key] = $this->debug($value, $objects);
485  } elseif ($value instanceof \Magento\Framework\DataObject) {
486  $debug[$key . ' (' . get_class($value) . ')'] = $value->debug(null, $objects);
487  }
488  }
489  return $debug;
490  }
getData($key='', $index=null)
Definition: DataObject.php:119
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
debug($data=null, &$objects=[])
Definition: DataObject.php:469
$value
Definition: gender.phtml:16
$debug
Definition: router.php:22

◆ getData()

getData (   $key = '',
  $index = null 
)

Object data getter

If $key is not defined will return all the data as an array. Otherwise it will return value of the element specified by $key. It is possible to use keys like a/b/c for access nested array data

If $index is specified it will assume that attribute data is an array and retrieve corresponding member. If data is the string - it will be explode by new line character and converted to array.

Parameters
string$key
string | int$index
Returns
mixed

Definition at line 119 of file DataObject.php.

120  {
121  if ('' === $key) {
122  return $this->_data;
123  }
124 
125  /* process a/b/c key as ['a']['b']['c'] */
126  if (strpos($key, '/') !== false) {
127  $data = $this->getDataByPath($key);
128  } else {
129  $data = $this->_getData($key);
130  }
131 
132  if ($index !== null) {
133  if ($data === (array)$data) {
134  $data = isset($data[$index]) ? $data[$index] : null;
135  } elseif (is_string($data)) {
136  $data = explode(PHP_EOL, $data);
137  $data = isset($data[$index]) ? $data[$index] : null;
138  } elseif ($data instanceof \Magento\Framework\DataObject) {
139  $data = $data->getData($index);
140  } else {
141  $data = null;
142  }
143  }
144  return $data;
145  }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
$index
Definition: list.phtml:44

◆ getDataByKey()

getDataByKey (   $key)

Get object data by particular key

Parameters
string$key
Returns
mixed

Definition at line 178 of file DataObject.php.

179  {
180  return $this->_getData($key);
181  }

◆ getDataByPath()

getDataByPath (   $path)

Get object data by path

Method consider the path as chain of keys: a/b/c => ['a']['b']['c']

Parameters
string$path
Returns
mixed

Definition at line 155 of file DataObject.php.

156  {
157  $keys = explode('/', $path);
158 
160  foreach ($keys as $key) {
161  if ((array)$data === $data && isset($data[$key])) {
162  $data = $data[$key];
163  } elseif ($data instanceof \Magento\Framework\DataObject) {
164  $data = $data->getDataByKey($key);
165  } else {
166  return null;
167  }
168  }
169  return $data;
170  }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17

◆ getDataUsingMethod()

getDataUsingMethod (   $key,
  $args = null 
)

Get object data by key with calling getter method

Parameters
string$key
mixed$args
Returns
mixed

Definition at line 218 of file DataObject.php.

219  {
220  $method = 'get' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key)));
221  return $this->{$method}($args);
222  }
$method
Definition: info.phtml:13

◆ hasData()

hasData (   $key = '')

If $key is empty, checks whether there's any data in the object Otherwise checks if the specified attribute is set.

Parameters
string$key
Returns
bool

Definition at line 231 of file DataObject.php.

232  {
233  if (empty($key) || !is_string($key)) {
234  return !empty($this->_data);
235  }
236  return array_key_exists($key, $this->_data);
237  }

◆ isEmpty()

isEmpty ( )

Checks whether the object is empty

Returns
bool

Definition at line 408 of file DataObject.php.

409  {
410  if (empty($this->_data)) {
411  return true;
412  }
413  return false;
414  }

◆ offsetExists()

offsetExists (   $offset)

Implementation of \ArrayAccess::offsetExists()

Parameters
string$offset
Returns
bool http://www.php.net/manual/en/arrayaccess.offsetexists.php

Definition at line 512 of file DataObject.php.

513  {
514  return isset($this->_data[$offset]) || array_key_exists($offset, $this->_data);
515  }

◆ offsetGet()

offsetGet (   $offset)

Implementation of \ArrayAccess::offsetGet()

Parameters
string$offset
Returns
mixed http://www.php.net/manual/en/arrayaccess.offsetget.php

Definition at line 536 of file DataObject.php.

537  {
538  if (isset($this->_data[$offset])) {
539  return $this->_data[$offset];
540  }
541  return null;
542  }

◆ offsetSet()

offsetSet (   $offset,
  $value 
)

Implementation of \ArrayAccess::offsetSet()

Parameters
string$offset
mixed$value
Returns
void http://www.php.net/manual/en/arrayaccess.offsetset.php

Definition at line 500 of file DataObject.php.

501  {
502  $this->_data[$offset] = $value;
503  }
$value
Definition: gender.phtml:16

◆ offsetUnset()

offsetUnset (   $offset)

Implementation of \ArrayAccess::offsetUnset()

Parameters
string$offset
Returns
void http://www.php.net/manual/en/arrayaccess.offsetunset.php

Definition at line 524 of file DataObject.php.

525  {
526  unset($this->_data[$offset]);
527  }

◆ serialize()

serialize (   $keys = [],
  $valueSeparator = '=',
  $fieldSeparator = ' ',
  $quote = '"' 
)

Convert object data into string with defined keys and values.

Example: key1="value1" key2="value2" ...

Parameters
array$keysarray of accepted keys
string$valueSeparatorseparator between key and value
string$fieldSeparatorseparator between key/value pairs
string$quotequoting sign
Returns
string

Definition at line 446 of file DataObject.php.

447  {
448  $data = [];
449  if (empty($keys)) {
450  $keys = array_keys($this->_data);
451  }
452 
453  foreach ($this->_data as $key => $value) {
454  if (in_array($key, $keys)) {
455  $data[] = $key . $valueSeparator . $quote . $value . $quote;
456  }
457  }
458  $res = implode($fieldSeparator, $data);
459  return $res;
460  }
$quote
$value
Definition: gender.phtml:16

◆ setData()

setData (   $key,
  $value = null 
)

Overwrite data in the object.

The $key parameter can be string or array. If $key is string, the attribute value will be overwritten by $value

If $key is an array, it will overwrite all the data in the object.

Parameters
string | array$key
mixed$value
Returns
$this

Definition at line 72 of file DataObject.php.

73  {
74  if ($key === (array)$key) {
75  $this->_data = $key;
76  } else {
77  $this->_data[$key] = $value;
78  }
79  return $this;
80  }
$value
Definition: gender.phtml:16

◆ setDataUsingMethod()

setDataUsingMethod (   $key,
  $args = [] 
)

Set object data with calling setter method

Parameters
string$key
mixed$args
Returns
$this

Definition at line 204 of file DataObject.php.

205  {
206  $method = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key)));
207  $this->{$method}($args);
208  return $this;
209  }
$method
Definition: info.phtml:13

◆ toArray()

toArray ( array  $keys = [])

Convert array of object data with to array with keys requested in $keys array

Parameters
array$keysarray of required keys
Returns
array

Definition at line 245 of file DataObject.php.

246  {
247  if (empty($keys)) {
248  return $this->_data;
249  }
250 
251  $result = [];
252  foreach ($keys as $key) {
253  if (isset($this->_data[$key])) {
254  $result[$key] = $this->_data[$key];
255  } else {
256  $result[$key] = null;
257  }
258  }
259  return $result;
260  }

◆ toJson()

toJson ( array  $keys = [])

Convert object data to JSON

Parameters
array$keysarray of required keys
Returns
bool|string
Exceptions

Definition at line 332 of file DataObject.php.

333  {
334  $data = $this->toArray($keys);
335  return \Magento\Framework\Serialize\JsonConverter::convert($data);
336  }

◆ toString()

toString (   $format = '')

Convert object data into string with predefined format

Will use $format as an template and substitute {{key}} for attributes

Parameters
string$format
Returns
string

Definition at line 358 of file DataObject.php.

359  {
360  if (empty($format)) {
361  $result = implode(', ', $this->getData());
362  } else {
363  preg_match_all('/\{\{([a-z0-9_]+)\}\}/is', $format, $matches);
364  foreach ($matches[1] as $var) {
365  $format = str_replace('{{' . $var . '}}', $this->getData($var), $format);
366  }
367  $result = $format;
368  }
369  return $result;
370  }
getData($key='', $index=null)
Definition: DataObject.php:119
$format
Definition: list.phtml:12

◆ toXml()

toXml ( array  $keys = [],
  $rootName = 'item',
  $addOpenTag = false,
  $addCdata = true 
)

Convert object data into XML string

Parameters
array$keysarray of keys that must be represented
string$rootNameroot node name
bool$addOpenTagflag that allow to add initial xml node
bool$addCdataflag that require wrap all values in CDATA
Returns
string

Definition at line 282 of file DataObject.php.

283  {
284  $xml = '';
285  $data = $this->toArray($keys);
286  foreach ($data as $fieldName => $fieldValue) {
287  if ($addCdata === true) {
288  $fieldValue = "<![CDATA[{$fieldValue}]]>";
289  } else {
290  $fieldValue = str_replace(
291  ['&', '"', "'", '<', '>'],
292  ['&amp;', '&quot;', '&apos;', '&lt;', '&gt;'],
293  $fieldValue
294  );
295  }
296  $xml .= "<{$fieldName}>{$fieldValue}</{$fieldName}>\n";
297  }
298  if ($rootName) {
299  $xml = "<{$rootName}>\n{$xml}</{$rootName}>\n";
300  }
301  if ($addOpenTag) {
302  $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $xml;
303  }
304  return $xml;
305  }

◆ unsetData()

unsetData (   $key = null)

Unset data from the object.

Parameters
null | string | array$key
Returns
$this

Definition at line 88 of file DataObject.php.

89  {
90  if ($key === null) {
91  $this->setData([]);
92  } elseif (is_string($key)) {
93  if (isset($this->_data[$key]) || array_key_exists($key, $this->_data)) {
94  unset($this->_data[$key]);
95  }
96  } elseif ($key === (array)$key) {
97  foreach ($key as $element) {
98  $this->unsetData($element);
99  }
100  }
101  return $this;
102  }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
setData($key, $value=null)
Definition: DataObject.php:72
$element
Definition: element.phtml:12

Field Documentation

◆ $_data

$_data = []
protected

Definition at line 22 of file DataObject.php.

◆ $_underscoreCache

$_underscoreCache = []
staticprotected

Definition at line 29 of file DataObject.php.


The documentation for this class was generated from the following file: