2020-12-11 01:25:38 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Toalett\Multiprocessing;
|
|
|
|
|
|
|
|
use Toalett\Multiprocessing\Exception\InvalidArgumentException;
|
|
|
|
|
2020-12-12 13:05:48 +01:00
|
|
|
class Concurrency
|
2020-12-11 01:25:38 +01:00
|
|
|
{
|
|
|
|
private const VALUE_UNLIMITED = -1;
|
|
|
|
private int $limit;
|
|
|
|
|
2020-12-12 02:11:05 +01:00
|
|
|
private function __construct(int $limit)
|
2020-12-11 01:25:38 +01:00
|
|
|
{
|
|
|
|
if ($limit === 0 || $limit < self::VALUE_UNLIMITED) {
|
|
|
|
throw new InvalidArgumentException('-1 or positive integer', $limit);
|
|
|
|
}
|
|
|
|
$this->limit = $limit;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function singleWorker(): self
|
|
|
|
{
|
|
|
|
return new self(1);
|
|
|
|
}
|
|
|
|
|
2020-12-12 02:11:05 +01:00
|
|
|
public static function atMost(int $limit): self
|
|
|
|
{
|
2020-12-12 13:05:48 +01:00
|
|
|
return new self($limit);
|
2020-12-12 02:11:05 +01:00
|
|
|
}
|
|
|
|
|
2020-12-11 01:25:38 +01:00
|
|
|
public static function unlimited(): self
|
|
|
|
{
|
|
|
|
return new self(self::VALUE_UNLIMITED);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function isUnlimited(): bool
|
|
|
|
{
|
|
|
|
return $this->limit === self::VALUE_UNLIMITED;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function isReachedBy(int $amount): bool
|
|
|
|
{
|
|
|
|
if ($this->isUnlimited()) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return $amount >= $this->limit;
|
|
|
|
}
|
|
|
|
}
|