julienmonnerie/kirby/src/Cms/Item.php

119 lines
2.1 KiB
PHP
Raw Normal View History

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-08-31 15:02:43 +02:00
use Kirby\Toolkit\Str;
2022-06-17 17:51:59 +02:00
/**
* The Item class is the foundation
* for every object in context with
* other objects. I.e.
*
* - a Block in a collection of Blocks
* - a Layout in a collection of Layouts
* - a Column in a collection of Columns
* @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 Item
{
2022-08-31 15:02:43 +02:00
use HasSiblings;
2022-12-19 14:56:05 +01:00
public const ITEMS_CLASS = Items::class;
2022-08-31 15:02:43 +02:00
2023-04-14 16:34:06 +02:00
protected Field|null $field;
2025-04-21 18:57:21 +02:00
protected string $id;
protected array $params;
protected ModelWithContent $parent;
protected Items $siblings;
2022-08-31 15:02:43 +02:00
/**
* Creates a new item
*/
public function __construct(array $params = [])
{
2025-04-21 18:57:21 +02:00
$class = static::ITEMS_CLASS;
2022-08-31 15:02:43 +02:00
$this->id = $params['id'] ?? Str::uuid();
$this->params = $params;
2023-04-14 16:34:06 +02:00
$this->field = $params['field'] ?? null;
2022-08-31 15:02:43 +02:00
$this->parent = $params['parent'] ?? App::instance()->site();
2025-04-21 18:57:21 +02:00
$this->siblings = $params['siblings'] ?? new $class();
2022-08-31 15:02:43 +02:00
}
/**
* Static Item factory
*/
2025-04-21 18:57:21 +02:00
public static function factory(array $params): static
2022-08-31 15:02:43 +02:00
{
return new static($params);
}
2023-04-14 16:34:06 +02:00
/**
* Returns the parent field if known
*/
public function field(): Field|null
{
return $this->field;
}
2022-08-31 15:02:43 +02:00
/**
* Returns the unique item id (UUID v4)
*/
public function id(): string
{
return $this->id;
}
/**
* Compares the item to another one
*/
public function is(Item $item): bool
{
return $this->id() === $item->id();
}
/**
* Returns the Kirby instance
*/
2025-04-21 18:57:21 +02:00
public function kirby(): App
2022-08-31 15:02:43 +02:00
{
return $this->parent()->kirby();
}
/**
* Returns the parent model
*/
2025-04-21 18:57:21 +02:00
public function parent(): ModelWithContent
2022-08-31 15:02:43 +02:00
{
return $this->parent;
}
/**
* Returns the sibling collection
* This is required by the HasSiblings trait
*
* @psalm-return self::ITEMS_CLASS
*/
2025-04-21 18:57:21 +02:00
protected function siblingsCollection(): Items
2022-08-31 15:02:43 +02:00
{
return $this->siblings;
}
/**
* Converts the item to an array
*/
public function toArray(): array
{
return [
'id' => $this->id(),
];
}
2022-06-17 17:51:59 +02:00
}