1<?php
2
3/*
4 * This file is part of the Assetic package, an OpenSky project.
5 *
6 * (c) 2010-2014 OpenSky Project Inc
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Assetic\Extension\Twig;
13
14use Assetic\ValueSupplierInterface;
15
16/**
17 * Container for values initialized lazily from a ValueSupplierInterface.
18 *
19 * @author Christophe Coevoet <stof@notk.org>
20 */
21class ValueContainer implements \ArrayAccess, \IteratorAggregate, \Countable
22{
23    private $values;
24    private $valueSupplier;
25
26    public function __construct(ValueSupplierInterface $valueSupplier)
27    {
28        $this->valueSupplier = $valueSupplier;
29    }
30
31    public function offsetExists($offset)
32    {
33        $this->initialize();
34
35        return array_key_exists($offset, $this->values);
36    }
37
38    public function offsetGet($offset)
39    {
40        $this->initialize();
41
42        if (!array_key_exists($offset, $this->values)) {
43            throw new \OutOfRangeException(sprintf('The variable "%s" does not exist.', $offset));
44        }
45
46        return $this->values[$offset];
47    }
48
49    public function offsetSet($offset, $value)
50    {
51        throw new \BadMethodCallException('The ValueContainer is read-only.');
52    }
53
54    public function offsetUnset($offset)
55    {
56        throw new \BadMethodCallException('The ValueContainer is read-only.');
57    }
58
59    public function getIterator()
60    {
61        $this->initialize();
62
63        return new \ArrayIterator($this->values);
64    }
65
66    public function count()
67    {
68        $this->initialize();
69
70        return count($this->values);
71    }
72
73    private function initialize()
74    {
75        if (null === $this->values) {
76            $this->values = $this->valueSupplier->getValues();
77        }
78    }
79}
80