3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Authentication\Storage
;
12 use Zend\Authentication\Storage\StorageInterface
;
13 use Zend\Stdlib\PriorityQueue
;
15 class Chain
implements StorageInterface
18 * Contains all storage that this authentication method uses. A storage
19 * placed in the priority queue with a higher priority is always used
20 * before using a storage with a lower priority.
24 protected $storageChain;
27 * Initializes the priority queue.
29 public function __construct()
31 $this->storageChain
= new PriorityQueue();
35 * @param StorageInterface $storage
36 * @param int $priority
38 public function add(StorageInterface
$storage, $priority = 1)
40 $this->storageChain
->insert($storage, $priority);
44 * Loop over the queue of storage until a storage is found that is non-empty. If such
45 * storage is not found, then this chain storage itself is empty.
47 * In case a non-empty storage is found then this chain storage is also non-empty. Report
48 * that, but also make sure that all storage with higher priorty that are empty
51 * @see StorageInterface::isEmpty()
53 public function isEmpty()
55 $storageWithHigherPriority = array();
57 // Loop invariant: $storageWithHigherPriority contains all storage with higher priorty
58 // than the current one.
59 foreach ($this->storageChain
as $storage) {
60 if ($storage->isEmpty()) {
61 $storageWithHigherPriority[] = $storage;
65 $storageValue = $storage->read();
66 foreach ($storageWithHigherPriority as $higherPriorityStorage) {
67 $higherPriorityStorage->write($storageValue);
77 * If the chain is non-empty then the storage with the top priority is guaranteed to be
78 * filled. Return its value.
80 * @see StorageInterface::read()
82 public function read()
84 return $this->storageChain
->top()->read();
88 * Write the new $contents to all storage in the chain.
90 * @see StorageInterface::write()
92 public function write($contents)
94 foreach ($this->storageChain
as $storage) {
95 $storage->write($contents);
100 * Clear all storage in the chain.
102 * @see StorageInterface::clear()
104 public function clear()
106 foreach ($this->storageChain
as $storage) {