julienmonnerie/kirby/src/Cms/Items.php

98 lines
1.9 KiB
PHP
Raw Normal View History

2022-06-17 17:51:59 +02:00
<?php
namespace Kirby\Cms;
use Closure;
use Exception;
/**
* A collection of items
* @since 3.5.0
*
* @package Kirby Cms
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
class Items extends Collection
{
2022-08-31 15:02:43 +02:00
public const ITEM_CLASS = '\Kirby\Cms\Item';
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* @var array
*/
protected $options;
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* @var \Kirby\Cms\ModelWithContent
*/
protected $parent;
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Constructor
*
* @param array $objects
* @param array $options
*/
public function __construct($objects = [], array $options = [])
{
$this->options = $options;
$this->parent = $options['parent'] ?? App::instance()->site();
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
parent::__construct($objects, $this->parent);
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Creates a new item collection from a
* an array of item props
*
* @param array $items
* @param array $params
* @return \Kirby\Cms\Items
*/
public static function factory(array $items = null, array $params = [])
{
$options = array_merge([
'options' => [],
'parent' => App::instance()->site(),
], $params);
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
if (empty($items) === true || is_array($items) === false) {
return new static();
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
if (is_array($options) === false) {
throw new Exception('Invalid item options');
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
// create a new collection of blocks
$collection = new static([], $options);
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
foreach ($items as $params) {
if (is_array($params) === false) {
continue;
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
$params['options'] = $options['options'];
$params['parent'] = $options['parent'];
$params['siblings'] = $collection;
$class = static::ITEM_CLASS;
$item = $class::factory($params);
$collection->append($item->id(), $item);
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
return $collection;
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Convert the items to an array
*
* @return array
*/
public function toArray(Closure $map = null): array
{
return array_values(parent::toArray($map));
}
2022-06-17 17:51:59 +02:00
}