babaev-an 97f73a73e2 20250525
Добавлен новый класс Tuple, реализующий работу кортежей почти как в C#.
2025-05-25 12:45:43 +03:00

121 lines
2.9 KiB
PHP

<?php
namespace goodboyalex\php_components_pack\classes;
use ArrayAccess;
use ArrayIterator;
use Countable;
use Exception;
use goodboyalex\php_components_pack\interfaces\ISerializable;
use IteratorAggregate;
use Traversable;
/**
* Класс, реализующий функционал кортежей от C#.
*
* @author Александр Бабаев
* @package php_components_pack
* @version 1.2
* @since 1.0.20
*/
final class Tuple implements ISerializable, ArrayAccess, IteratorAggregate, Countable
{
/**
* @var array Массив значений кортежа.
*/
private array $Values;
/**
* Конструктор кортежа.
*
* @param mixed ...$values Значения кортежа.
*/
public function __construct (...$values)
{
$this->Values = $values;
}
/**
* @inheritDoc
*/
public function Serialize (): string
{
return serialize($this->Values);
}
/**
* @inheritDoc
*/
public function UnSerialize (string $serialized): void
{
$this->Values = unserialize($serialized);
}
/**
* @inheritDoc
*/
public function offsetExists (mixed $offset): bool
{
return isset($this->Values[$offset]);
}
/**
* @inheritDoc
*/
public function offsetGet (mixed $offset): mixed
{
// Если ключ не является целым числом
if (!is_int($offset))
// - возвращаем null
return null;
// Возвращаем значение кортежа по индексу
return $this->Get($offset);
}
/**
* Возвращает значение кортежа по индексу.
*
* @param int $index Индекс значения.
*
* @return mixed Значение кортежа по индексу.
*/
public function Get (int $index): mixed
{
return $this->Values[$index] ?? null;
}
/**
* @inheritDoc
* @throws Exception Элементы кортежа не могут быть изменены после создания! / Tuple elements cannot be changed
* after creation!
*/
public function offsetSet (mixed $offset, mixed $value): void
{
throw new Exception('Элементы кортежа не могут быть изменены после создания! / Tuple elements cannot be changed after creation!');
}
/**
* @inheritDoc
*/
public function offsetUnset (mixed $offset): void
{
unset($this->Values[$offset]);
}
/**
* @inheritDoc
*/
public function getIterator (): Traversable
{
return new ArrayIterator($this->Values);
}
/**
* @inheritDoc
*/
public function count (): int
{
return count($this->Values);
}
}