2022-08-16 14:46:06 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace Arendsen\FluxQueryBuilder\Type;
|
|
|
|
|
|
2022-08-18 17:56:02 +00:00
|
|
|
use Arendsen\FluxQueryBuilder\Settings;
|
2022-08-16 14:46:06 +00:00
|
|
|
use Arendsen\FluxQueryBuilder\Type;
|
|
|
|
|
|
|
|
|
|
class ArrayType implements TypeInterface
|
|
|
|
|
{
|
2022-08-18 17:56:02 +00:00
|
|
|
public const SETTING_IS_NESTED_ARRAY = 'isNestedArray';
|
|
|
|
|
|
2022-08-16 15:06:32 +00:00
|
|
|
/**
|
|
|
|
|
* @var array $value
|
|
|
|
|
*/
|
|
|
|
|
protected $value;
|
|
|
|
|
|
|
|
|
|
/**
|
2022-08-18 17:56:02 +00:00
|
|
|
* @var Settings|null $settings
|
2022-08-16 15:06:32 +00:00
|
|
|
*/
|
|
|
|
|
protected $settings;
|
|
|
|
|
|
2022-08-18 17:56:02 +00:00
|
|
|
public function __construct(array $value, Settings $settings = null)
|
2022-08-16 14:46:06 +00:00
|
|
|
{
|
|
|
|
|
$this->value = $value;
|
2022-08-18 17:56:02 +00:00
|
|
|
$this->settings = $settings ? $settings : Settings::set([]);
|
2022-08-16 14:46:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function __toString(): string
|
|
|
|
|
{
|
2022-08-18 17:56:02 +00:00
|
|
|
if ($this->settings->get(RecordType::SETTING_IS_RECORD)) {
|
2022-08-16 15:49:06 +00:00
|
|
|
return new RecordType($this->value);
|
2022-08-16 15:28:46 +00:00
|
|
|
}
|
|
|
|
|
|
2022-08-16 14:46:06 +00:00
|
|
|
array_walk($this->value, function (&$value, $key) {
|
2022-08-18 17:56:02 +00:00
|
|
|
if ($this->isAssociativeArray($key)) {
|
|
|
|
|
$value = $key . ': ' . new Type($value, Settings::set([
|
|
|
|
|
self::SETTING_IS_NESTED_ARRAY => is_array($value)
|
|
|
|
|
]));
|
2022-08-16 14:46:06 +00:00
|
|
|
} else {
|
2022-08-18 17:56:02 +00:00
|
|
|
$value = new Type($value, Settings::set([
|
|
|
|
|
self::SETTING_IS_NESTED_ARRAY => is_array($value)
|
|
|
|
|
]));
|
2022-08-16 14:46:06 +00:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2022-08-18 17:56:02 +00:00
|
|
|
return $this->getPrefix() . implode(', ', $this->value) . $this->getSuffix();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected function isAssociativeArray($key): bool
|
|
|
|
|
{
|
|
|
|
|
return is_string($key);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected function isNestedArray(): bool
|
|
|
|
|
{
|
|
|
|
|
return $this->settings->get(self::SETTING_IS_NESTED_ARRAY) ? true : false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected function getPrefix(): string
|
|
|
|
|
{
|
|
|
|
|
return $this->isNestedArray() ? '[' : '';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected function getSuffix(): string
|
|
|
|
|
{
|
|
|
|
|
return $this->isNestedArray() ? ']' : '';
|
2022-08-16 14:46:06 +00:00
|
|
|
}
|
|
|
|
|
}
|