Skip to content

Instantly share code, notes, and snippets.

@lav45
Last active May 5, 2017 21:45
Show Gist options
  • Save lav45/5482c413d5bd8d3551b3777385f21f2d to your computer and use it in GitHub Desktop.
Save lav45/5482c413d5bd8d3551b3777385f21f2d to your computer and use it in GitHub Desktop.
XmlResponseFormatter useObjectTags
<?php
namespace api\modules\v0;
use Yii;
class Module extends \yii\base\Module
{
public function init()
{
parent::init();
Yii::$app->response->on('beforeSend', function ($event) {
/** @var \yii\web\Response $response */
$response = $event->sender;
if ($response->data && $response->getStatusCode() == 200) {
$response->formatters['xml'] = [
'class' => 'api\components\XmlResponseFormatter',
'rootTag' => 'contacts',
'useObjectTags' => 'contact',
];
}
});
}
}
<?php
namespace api\components;
class XmlResponseFormatter extends \yii\web\XmlResponseFormatter
{
/**
* @var bool|string if object tags should be added
* @since 2.0.11
*/
public $useObjectTags = true;
/**
* @param DOMElement $element
* @param mixed $data
*/
protected function buildXml($element, $data)
{
if (is_array($data) ||
($data instanceof \Traversable && $this->useTraversableAsArray && !$data instanceof Arrayable)
) {
foreach ($data as $name => $value) {
if (is_int($name) && is_object($value)) {
$this->buildXml($element, $value);
}
$child = new DOMElement(is_int($name) ? $this->itemTag : $name);
$element->appendChild($child);
if (is_array($value) || is_object($value)) {
$this->buildXml($child, $value);
} else {
$child->appendChild(new DOMText($this->formatScalarValue($value)));
}
}
} elseif (is_object($data)) {
if ($this->useObjectTags === true) {
$child = StringHelper::basename(get_class($data));
} else {
$child = $this->useObjectTags;
}
$child = new DOMElement($child);
$element->appendChild($child);
if ($data instanceof Arrayable) {
$this->buildXml($child, $data->toArray());
} else {
$array = [];
foreach ($data as $name => $value) {
$array[$name] = $value;
}
$this->buildXml($child, $array);
}
} else {
$element->appendChild(new DOMText($this->formatScalarValue($data)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment