| 1 |
<?php |
| 2 |
declare(strict_types = 1); |
| 3 |
|
| 4 |
namespace Gettext; |
| 5 |
|
| 6 |
use ArrayIterator; |
| 7 |
use Countable; |
| 8 |
use IteratorAggregate; |
| 9 |
use JsonSerializable; |
| 10 |
use ReturnTypeWillChange; |
| 11 |
|
| 12 |
/** |
| 13 |
* Class to manage the flags of a translation. |
| 14 |
*/ |
| 15 |
class Flags implements JsonSerializable, Countable, IteratorAggregate |
| 16 |
{ |
| 17 |
protected $flags = []; |
| 18 |
|
| 19 |
public static function __set_state(array $state): Flags |
| 20 |
{ |
| 21 |
return new static(...$state['flags']); |
| 22 |
} |
| 23 |
|
| 24 |
public function __construct(string ...$flags) |
| 25 |
{ |
| 26 |
if (!empty($flags)) { |
| 27 |
$this->add(...$flags); |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
public function __debugInfo() |
| 32 |
{ |
| 33 |
return $this->toArray(); |
| 34 |
} |
| 35 |
|
| 36 |
public function add(string ...$flags): self |
| 37 |
{ |
| 38 |
foreach ($flags as $flag) { |
| 39 |
if (!$this->has($flag)) { |
| 40 |
$this->flags[] = $flag; |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
sort($this->flags); |
| 45 |
|
| 46 |
return $this; |
| 47 |
} |
| 48 |
|
| 49 |
public function delete(string ...$flags): self |
| 50 |
{ |
| 51 |
foreach ($flags as $flag) { |
| 52 |
$key = array_search($flag, $this->flags); |
| 53 |
|
| 54 |
if (is_int($key)) { |
| 55 |
array_splice($this->flags, $key, 1); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
return $this; |
| 60 |
} |
| 61 |
|
| 62 |
public function has(string $flag): bool |
| 63 |
{ |
| 64 |
return in_array($flag, $this->flags, true); |
| 65 |
} |
| 66 |
|
| 67 |
#[ReturnTypeWillChange] |
| 68 |
public function jsonSerialize() |
| 69 |
{ |
| 70 |
return $this->toArray(); |
| 71 |
} |
| 72 |
|
| 73 |
#[ReturnTypeWillChange] |
| 74 |
public function getIterator() |
| 75 |
{ |
| 76 |
return new ArrayIterator($this->flags); |
| 77 |
} |
| 78 |
|
| 79 |
public function count(): int |
| 80 |
{ |
| 81 |
return count($this->flags); |
| 82 |
} |
| 83 |
|
| 84 |
public function toArray(): array |
| 85 |
{ |
| 86 |
return $this->flags; |
| 87 |
} |
| 88 |
|
| 89 |
public function mergeWith(Flags $flags): Flags |
| 90 |
{ |
| 91 |
$merged = clone $this; |
| 92 |
$merged->add(...$flags->flags); |
| 93 |
|
| 94 |
return $merged; |
| 95 |
} |
| 96 |
} |
| 97 |
|