<?php

namespace goodboyalex\php_components_pack\traits\ObjectArray;

use ArrayIterator;

/**
 * Часть кода класса ObjectArray, отвечающая за функции из наследуемых интерфейсов и классов.
 *
 * @author Александр Бабаев
 * @package php_components_pack
 * @version 1.0
 * @since 1.0
 */
trait ObjectArrayBasicTrait
{
    /**
     * @inheritDoc
     */
    public function offsetExists (mixed $offset): bool
    {
        return isset($this->Container[$offset]);
    }

    /**
     * @inheritDoc
     */
    public function offsetGet (mixed $offset): mixed
    {
        return $this->Container[$offset] ?? null;
    }

    /**
     * @inheritDoc
     */
    public function offsetSet (mixed $offset, mixed $value): void
    {
        // Если смещение не указано
        if (is_null($offset))
            // - то добавляем объект в конец массива.
            $this->Container[] = $value;
        else
            // - иначе добавляем объект по указанному смещению.
            $this->Container[$offset] = $value;
    }

    /**
     * @inheritDoc
     */
    public function offsetUnset (mixed $offset): void
    {
        unset($this->Container[$offset]);
    }

    /**
     * @inheritDoc
     */
    public function getIterator (): ArrayIterator
    {
        return new ArrayIterator($this->Container);
    }

    /**
     * Существует ли элемент по указанному смещению.
     *
     * @param mixed $offset Смещение.
     *
     * @return bool Существует ли элемент по указанному смещению.
     */
    public function __isset (mixed $offset): bool
    {
        return isset($this->data[$offset]);
    }

    /**
     * @inheritDoc
     */
    public function Serialize (): string
    {
        return serialize($this->Container);
    }

    /**
     * @inheritDoc
     */
    public function UnSerialize (string $serialized): void
    {
        $this->Container = unserialize($serialized);
    }
}