Skip to content
This repository was archived by the owner on Jul 8, 2018. It is now read-only.

Commit af919ed

Browse files
committed
Add WeakValueMap
1 parent 4ec5410 commit af919ed

File tree

2 files changed

+456
-0
lines changed

2 files changed

+456
-0
lines changed

src/WeakValueMap.php

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the pinepain/php-weak-lib PHP library.
5+
*
6+
* Copyright (c) 2016 Bogdan Padalko <zaq178miami@gmail.com>
7+
*
8+
* Licensed under the MIT license: http://opensource.org/licenses/MIT
9+
*
10+
* For the full copyright and license information, please view the LICENSE
11+
* file that was distributed with this source code or visit http://opensource.org/licenses/MIT
12+
*/
13+
14+
namespace Weak;
15+
16+
use RuntimeException;
17+
use SplObjectStorage;
18+
19+
class WeakValueMap extends SplObjectStorage
20+
{
21+
/** {@inheritdoc} */
22+
public function attach($object, $data = null)
23+
{
24+
$this->validateInfo($data);
25+
26+
$data = new Reference($data, function () use ($object) {
27+
$this->detach($object);
28+
});
29+
30+
parent::attach($object, $data);
31+
}
32+
33+
/** {@inheritdoc} */
34+
public function addAll($storage)
35+
{
36+
foreach ($storage as $obj) {
37+
$this->attach($obj, $storage[$obj]);
38+
}
39+
}
40+
41+
/** {@inheritdoc} */
42+
public function getInfo()
43+
{
44+
$info = parent::getInfo(); // TODO: Change the autogenerated stub
45+
46+
if ($info instanceof Reference) {
47+
$info = $info->get();
48+
}
49+
50+
return $info;
51+
}
52+
53+
/** {@inheritdoc} */
54+
public function setInfo($data)
55+
{
56+
$this->validateInfo($data);
57+
58+
$object = $this->current();
59+
60+
if (!$object) {
61+
return; // nothing to do
62+
}
63+
64+
$data = new Reference($data, function () use ($object) {
65+
$this->detach($object);
66+
});
67+
68+
parent::setInfo($data);
69+
}
70+
71+
/** {@inheritdoc} */
72+
public function offsetSet($object, $data = null)
73+
{
74+
$this->attach($object, $data);
75+
}
76+
77+
/** {@inheritdoc} */
78+
public function offsetGet($object)
79+
{
80+
$info = parent::offsetGet($object); // TODO: Change the autogenerated stub
81+
82+
if ($info instanceof Reference) {
83+
$info = $info->get();
84+
}
85+
86+
return $info;
87+
}
88+
89+
protected function validateInfo($data)
90+
{
91+
if (!is_object($data)) {
92+
throw new RuntimeException(self::class . ' expects data to be object, ' . gettype($data) . ' given');
93+
}
94+
}
95+
}

0 commit comments

Comments
 (0)