Skip to content

Commit

Permalink
Возможность указания контекста сериализации для моделей на этапе пост…
Browse files Browse the repository at this point in the history
…роения запроса.
  • Loading branch information
vizh committed Dec 12, 2017
1 parent 2aaeac1 commit 0e6acdd
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions framework/db/ar/CActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ abstract class CActiveRecord extends CModel
private $_pk; // old primary key value
private $_alias='t'; // the table alias being used for query

/**
* @var string[][]|null
*/
private $_ctx;

/**
* Constructor.
Expand Down Expand Up @@ -1446,6 +1450,28 @@ public function setTableAlias($alias)
$this->_alias=$alias;
}

/**
* @param string $name
*
* @return \CActiveRecord
* @since 1.1.20
*/
public function addSerializationContext(string... $names): self
{
$attributes = $this->getMetaData()->columns;

foreach ($names as $name) {
if (isset($attributes[$name]))
$this->_ctx['attributes'][] = $name;
elseif (isset($this->_related[$name]))
$this->_ctx['relations'][] = $name;
elseif (parent::__isset($name))
$this->_ctx['methods'][] = $name;
}

return $this;
}

/**
* Finds a single active record with the specified condition.
* @param mixed $condition query condition or criteria.
Expand Down Expand Up @@ -1869,6 +1895,7 @@ public function populateRecord($attributes,$callAfterFind=true)
$record->_attributes[$name]=$value;
}
$record->_pk=$record->getPrimaryKey();
$record->_ctx = $this->_ctx;
$record->attachBehaviors($record->behaviors());
if($callAfterFind)
$record->afterFind();
Expand Down Expand Up @@ -1930,6 +1957,33 @@ public function offsetExists($offset)
{
return $this->__isset($offset);
}

/**
* Specify data which should be serialized to JSON
*
* @link http://php.net/manual/en/jsonserializable.jsonserialize.php
* @return mixed data which can be serialized by <b>json_encode</b>,
* which is a value of any type other than a resource.
* @since 5.4.0
*/
public function jsonSerialize()
{
$result = [];

if (isset($this->_ctx['attributes']))
foreach ($this->_ctx['attributes'] as $name)
$result[$name] = $this->_attributes[$name];

if (isset($this->_ctx['methods']))
foreach ($this->_ctx['methods'] as $name)
$result[$name] = parent::__get($name);

if (isset($this->_ctx['relations']))
foreach ($this->_ctx['relations'] as $name)
$result[$name] = $this->_related[$name];

return $result;
}
}


Expand Down

0 comments on commit 0e6acdd

Please sign in to comment.