2022-06-17 17:51:59 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Kirby\Cms;
|
|
|
|
|
2025-04-21 18:57:21 +02:00
|
|
|
use Kirby\Content\Field;
|
|
|
|
|
2022-06-17 17:51:59 +02:00
|
|
|
/**
|
|
|
|
* The Nest class converts any array type
|
|
|
|
* into a Kirby style collection/object. This
|
|
|
|
* can be used make any type of array compatible
|
|
|
|
* with Kirby queries.
|
|
|
|
*
|
|
|
|
* REFACTOR: move this to the toolkit
|
|
|
|
*
|
|
|
|
* @package Kirby Cms
|
|
|
|
* @author Bastian Allgeier <bastian@getkirby.com>
|
|
|
|
* @link https://getkirby.com
|
|
|
|
* @copyright Bastian Allgeier
|
|
|
|
* @license https://getkirby.com/license
|
|
|
|
*/
|
|
|
|
class Nest
|
|
|
|
{
|
2022-12-19 14:56:05 +01:00
|
|
|
public static function create(
|
|
|
|
$data,
|
|
|
|
object|null $parent = null
|
|
|
|
): NestCollection|NestObject|Field {
|
2022-08-31 15:02:43 +02:00
|
|
|
if (is_scalar($data) === true) {
|
|
|
|
return new Field($parent, $data, $data);
|
|
|
|
}
|
2022-06-17 17:51:59 +02:00
|
|
|
|
2022-08-31 15:02:43 +02:00
|
|
|
$result = [];
|
2022-06-17 17:51:59 +02:00
|
|
|
|
2022-08-31 15:02:43 +02:00
|
|
|
foreach ($data as $key => $value) {
|
|
|
|
if (is_array($value) === true) {
|
|
|
|
$result[$key] = static::create($value, $parent);
|
|
|
|
} elseif (is_scalar($value) === true) {
|
|
|
|
$result[$key] = new Field($parent, $key, $value);
|
|
|
|
}
|
|
|
|
}
|
2022-06-17 17:51:59 +02:00
|
|
|
|
2022-12-19 14:56:05 +01:00
|
|
|
$key = key($data);
|
|
|
|
|
|
|
|
if ($key === null || is_int($key) === true) {
|
2022-08-31 15:02:43 +02:00
|
|
|
return new NestCollection($result);
|
|
|
|
}
|
2022-12-19 14:56:05 +01:00
|
|
|
|
|
|
|
return new NestObject($result);
|
2022-08-31 15:02:43 +02:00
|
|
|
}
|
2022-06-17 17:51:59 +02:00
|
|
|
}
|