Files
kiri-core/kiri-engine/Core/HashMap.php
T

158 lines
3.0 KiB
PHP
Raw Normal View History

2022-01-09 03:50:38 +08:00
<?php
namespace Kiri\Core;
2023-04-15 23:32:00 +08:00
use Exception;
2022-01-09 03:50:38 +08:00
use JetBrains\PhpStorm\Pure;
2022-06-30 16:40:48 +08:00
use ReturnTypeWillChange;
2022-01-25 02:00:42 +08:00
use Traversable;
2022-01-09 03:50:38 +08:00
2022-01-25 02:00:42 +08:00
class HashMap implements \ArrayAccess, \IteratorAggregate
2022-01-09 03:50:38 +08:00
{
2023-06-27 16:29:10 +08:00
/**
* @var array
*/
private array $lists = [];
/**
* @return Traversable
*/
public function getIterator(): Traversable
{
return new \ArrayIterator($this->lists);
}
/**
* @return bool
*/
public function hasItem(): bool
{
return count($this->lists) > 0;
}
/**
* @param string $key
* @param $value
*/
2023-12-12 15:35:38 +08:00
public function put(string $key, $value): void
2023-06-27 16:29:10 +08:00
{
$this->lists[$key] = $value;
}
/**
* @param string $key
* @param $value
* @return void
* @throws Exception
*/
public function append(string $key, $value): void
{
if (!$this->has($key)) {
$this->lists[$key] = [];
} else if (!is_array($this->lists[$key])) {
throw new Exception('Source must a array.');
}
$this->lists[$key][] = $value;
}
2023-04-15 23:32:00 +08:00
2023-05-25 16:59:20 +08:00
/**
* @param string $key
* @param mixed|null $default
* @return mixed
*/
2023-06-27 16:29:10 +08:00
#[Pure] public function get(string $key, mixed $default = null): mixed
{
if (!$this->has($key)) {
return $default;
}
return $this->lists[$key];
}
/**
* @param string $key
*/
2023-12-12 15:35:38 +08:00
public function del(string $key): void
2023-06-27 16:29:10 +08:00
{
if (!$this->has($key)) {
return;
}
unset($this->lists[$key]);
}
/**
* @param string $key
* @return bool
*/
public function has(string $key): bool
{
return array_key_exists($key, $this->lists);
}
/**
* @param mixed $offset
* @return bool
*/
public function offsetExists(mixed $offset): bool
{
return isset($this->lists[$offset]);
}
/**
* @param mixed $offset
* @return mixed
*/
#[Pure] public function offsetGet(mixed $offset): mixed
{
return $this->get($offset);
}
/**
* @param mixed $offset
* @param mixed $value
*/
#[ReturnTypeWillChange]
2023-12-12 15:35:38 +08:00
public function offsetSet(mixed $offset, mixed $value): void
2023-06-27 16:29:10 +08:00
{
$this->put($offset, $value);
}
/**
* @param mixed $offset
*/
#[ReturnTypeWillChange]
2023-12-12 15:35:38 +08:00
public function offsetUnset(mixed $offset): void
2023-06-27 16:29:10 +08:00
{
unset($this->lists[$offset]);
}
2023-10-24 17:22:32 +08:00
/**
* @param HashMap $root
* @param string $leaf
* @return HashMap
*/
public static function Tree(HashMap $root, string $leaf): HashMap
2023-06-27 16:29:10 +08:00
{
if ($root->has($leaf)) {
$hashMap = $root->get($leaf);
} else {
$hashMap = new HashMap();
$root->put($leaf, $hashMap);
}
return $hashMap;
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}