Debian Codegraph @

vendor/wikimedia/parsoid/src/Tokens/KVSourceRange.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Tokens;
5
6 use Wikimedia\Assert\Assert;
7 use Wikimedia\JsonCodec\JsonCodecable;
8 use Wikimedia\JsonCodec\JsonCodecableTrait;
9
10 /**
11 * Represents a source offset range for a key-value pair.
12 */
13 class KVSourceRange implements JsonCodecable {
14 use JsonCodecableTrait;
15
16 /**
17 * Source range for the key.
18 * @var SourceRange
19 */
20 public $key;
21
22 /**
23 * Source range for the value.
24 * @var SourceRange
25 */
26 public $value;
27
28 /**
29 * Create a new key-value source offset range.
30 * @param int $keyStart The start index of the key
31 * (unicode code points, inclusive)
32 * @param int $keyEnd The end index of the key
33 * (unicode code points, exclusive)
34 * @param int $valueStart The start index of the value
35 * (unicode code points, inclusive)
36 * @param int $valueEnd The end index of the value
37 * (unicode code points, exclusive)
38 */
39 public function __construct( int $keyStart, int $keyEnd, int $valueStart, int $valueEnd ) {
40 $this->key = new SourceRange( $keyStart, $keyEnd );
41 $this->value = new SourceRange( $valueStart, $valueEnd );
42 }
43
44 /**
45 * Return a new key-value source offset range shifted by $amount.
46 * @param int $amount The amount to shift by
47 * @return KVSourceRange
48 */
49 public function offset( int $amount ): KVSourceRange {
50 return new KVSourceRange(
51 $this->key->start + $amount,
52 $this->key->end + $amount,
53 $this->value->start + $amount,
54 $this->value->end + $amount
55 );
56 }
57
58 /**
59 * Create a new key-value source offset range from an array of
60 * integers (such as created during JSON serialization).
61 * @param int[] $so
62 * @return KVSourceRange
63 */
64 public static function newFromJsonArray( array $so ): KVSourceRange {
65 Assert::invariant(
66 count( $so ) === 4,
67 'Not enough elements in KVSourceRange array'
68 );
69 return new KVSourceRange( $so[0], $so[1], $so[2], $so[3] );
70 }
71
72 /**
73 * @inheritDoc
74 */
75 public function toJsonArray(): array {
76 return [
77 $this->key->start,
78 $this->key->end,
79 $this->value->start,
80 $this->value->end,
81 ];
82 }
83 }