<?php

namespace KupShop\ContentBundle\Util;

use Doctrine\Common\Collections\ArrayCollection;
use KupShop\ContentBundle\Entity\Block;

class BlockCollection extends ArrayCollection
{
    public $identifierToId;

    /**
     * @param $offset int Either block ID or block identification
     *
     * @return int
     */
    protected function translateOffset($offset)
    {
        if (is_numeric($offset)) {
            return $offset;
        }

        // Load identification cache
        $this->identifierToId = [];

        /** @var Block $block */
        foreach ($this as $index => $block) {
            $this->identifierToId[$block->getIdentifier()] = $index;
        }

        if (isset($this->identifierToId[$offset])) {
            return $this->identifierToId[$offset];
        }

        return '';
    }

    public function get($offset)
    {
        $offset = $this->translateOffset($offset);

        return parent::get($offset);
    }

    public function containsKey($offset)
    {
        $offset = $this->translateOffset($offset);

        return parent::containsKey($offset);
    }
}
