Skip to content

Commit

Permalink
feat: add Pool::init & Pool::append
Browse files Browse the repository at this point in the history
  • Loading branch information
chaz6chez committed Oct 16, 2024
1 parent bdb48d6 commit bf0417b
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 6 deletions.
58 changes: 52 additions & 6 deletions src/Utils/Pool/Pool.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ class Pool
*/
protected static array $pools = [];

/**
* @var bool[]
*/
protected static array $poolIsClone = [];

/**
* 名称
*
Expand Down Expand Up @@ -64,7 +69,7 @@ class Pool
protected bool $_force;

/**
* 创建
* 初始化
*
* @param string $name 区域
* @param int $count 区域索引
Expand All @@ -74,16 +79,57 @@ class Pool
*/
public static function create(string $name, int $count, mixed $element, bool $clone = true): array
{
if (static::get($name, null)) {
throw new PoolException("Pools $name already exists. ", -1);
}
// 占位
static::init($name, $clone);
// 追加
foreach (range(1, $count) as $i) {
self::$pools[$name][$i] = new Pool($name, $i, $element, $clone);
static::append($name, $i, $element);
}

return self::$pools[$name];
}

/**
* 区域/区域对象是否存在
*
* @param string $name
* @param int|null $index
* @return bool
*/
public static function exists(string $name, ?int $index): bool
{
return $index === null ? isset(self::$pools[$name]) : isset(self::$pools[$name][$index]);
}

/**
* 初始化占位
*
* @param string $name
* @param bool $clone
* @return void
*/
public static function init(string $name, bool $clone = true): void
{
if (static::exists($name, null)) {
throw new PoolException("Pools $name already exists. ", -1);
}
self::$pools[$name] = [];
self::$poolIsClone[$name] = $clone;
}

/**
* 追加
*
* @param string $name
* @param int $index
* @param mixed $element
* @return void
*/
public static function append(string $name, int $index, mixed $element): void
{
$clone = self::$poolIsClone[$name] ?? false;
self::$pools[$name][$index] = new Pool($name, $index, $element, $clone);
}

/**
* 回收
*
Expand Down
11 changes: 11 additions & 0 deletions tests/UtilsCase/Pool/PoolTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@ protected function _arraysAreDifferent(array $array1, array $array2): bool
return false;
}

public function testPoolAppendException()
{
$element = new stdClass();
$element->property = 'value';
Pool::create($name = __METHOD__, 1, $element);
$index = 1;
$this->expectException(PoolException::class);
$this->expectExceptionMessage("Pool $name#$index already exists. ");
Pool::append(__METHOD__, $index, $element);
}

public function testCreatePoolWithStdClass()
{
$element = new stdClass();
Expand Down

0 comments on commit bf0417b

Please sign in to comment.