mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-08-21 23:23:51 +00:00
Bootstrap encoder for documents
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\DocGeneratorBundle\Serializer\Encoder;
|
||||
|
||||
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
|
||||
|
||||
class DocGenEncoder implements \Symfony\Component\Serializer\Encoder\EncoderInterface
|
||||
{
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function encode($data, string $format, array $context = [])
|
||||
{
|
||||
if (!$this->isAssociative($data)) {
|
||||
throw new UnexpectedValueException("Only associative arrays are allowed; lists are not allowed");
|
||||
}
|
||||
|
||||
$result = [];
|
||||
$this->recusiveEncoding($data, $result, '');
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function recusiveEncoding(array $data, array &$result, $path)
|
||||
{
|
||||
if ($this->isAssociative($data)) {
|
||||
foreach ($data as $key => $value) {
|
||||
if (\is_array($value)) {
|
||||
$this->recusiveEncoding($value, $result, $this->canonicalizeKey($path, $key));
|
||||
} else {
|
||||
$result[$this->canonicalizeKey($path, $key)] = $value;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
foreach ($data as $elem) {
|
||||
|
||||
if (!$this->isAssociative($elem)) {
|
||||
throw new UnexpectedValueException(sprintf("Embedded loops are not allowed. See data under %s path", $path));
|
||||
}
|
||||
|
||||
$sub = [];
|
||||
$this->recusiveEncoding($elem, $sub, '');
|
||||
$result[$path][] = $sub;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function canonicalizeKey(string $path, string $key): string
|
||||
{
|
||||
return $path === '' ? $key : $path.'_'.$key;
|
||||
}
|
||||
|
||||
private function isAssociative(array $data)
|
||||
{
|
||||
$keys = \array_keys($data);
|
||||
|
||||
return $keys !== \array_keys($keys);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function supportsEncoding(string $format)
|
||||
{
|
||||
return $format === 'docgen';
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user