Debian Codegraph @

vendor/wikimedia/minify/src/IndexMapOffset.php

raw
1 <?php
2 /**
3 * Copyright 2023 Wikimedia Foundation
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * @file
18 * @license Apache-2.0
19 * @license MIT
20 * @license GPL-2.0-or-later
21 * @license LGPL-2.1-or-later
22 */
23
24 namespace Wikimedia\Minify;
25
26 /**
27 * A class representing a line/column offset into a combined generated file,
28 * for index map generation.
29 *
30 * Or it can represent the past-the-end offset of a single specified file,
31 * that is, the number of lines in the file and the number of columns in
32 * the last line of the file.
33 */
34 class IndexMapOffset {
35 /** @var int */
36 public $line;
37 /** @var int */
38 public $column;
39
40 /**
41 * @param int $line The zero-based line number
42 * @param int $column The zero-based column number
43 */
44 public function __construct( int $line, int $column ) {
45 $this->line = $line;
46 $this->column = $column;
47 }
48
49 /**
50 * Count the number of lines and columns in the specified string, and
51 * create an IndexMapOffset representing the corresponding size.
52 *
53 * @param string $text
54 * @return self
55 */
56 public static function newFromText( string $text ) {
57 $lines = substr_count( $text, "\n" );
58 $lastBreakPos = strrpos( $text, "\n" );
59 if ( $lastBreakPos === false ) {
60 $columns = Utils::getJsLength( $text );
61 } else {
62 $columns = Utils::getJsLength( substr( $text, $lastBreakPos + 1 ) );
63 }
64 return new self( $lines, $columns );
65 }
66
67 /**
68 * Restore an IndexMapOffset which was serialized with toArray().
69 *
70 * @param array $data
71 * @return self
72 */
73 public static function newFromArray( array $data ) {
74 return new self( $data[0], $data[1] );
75 }
76
77 /**
78 * Convert the object to plain data.
79 *
80 * @return array
81 */
82 public function toArray(): array {
83 return [ $this->line, $this->column ];
84 }
85
86 /**
87 * Advance the offset, assuming a file of the specified size was added
88 * to the combined file.
89 *
90 * @param IndexMapOffset $nextSize
91 * @return void
92 */
93 public function add( self $nextSize ) {
94 if ( $nextSize->line > 0 ) {
95 $this->line += $nextSize->line;
96 $this->column = $nextSize->column;
97 } else {
98 $this->column += $nextSize->column;
99 }
100 }
101 }