Debian Codegraph @

vendor/wikimedia/minify/src/IndexMap.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 an index map, as defined by the source map
28 * specification. This allows several mapped sources to be combined into a
29 * single file.
30 */
31 class IndexMap {
32 /** @var string|null */
33 private $file;
34 /** @var IndexMapOffset */
35 private $offset;
36 /** @var array */
37 private $sections;
38
39 /**
40 * Create an empty index map
41 */
42 public function __construct() {
43 $this->offset = new IndexMapOffset( 0, 0 );
44 $this->sections = [];
45 }
46
47 /**
48 * Set the name of the output file, to be given as the "file" key.
49 *
50 * @param string $file
51 * @return $this
52 */
53 public function outputFile( string $file ) {
54 $this->file = $file;
55 return $this;
56 }
57
58 /**
59 * Add a section with a source map which was encoded in the "raw" JSON format.
60 *
61 * @param string $mapJson The JSON-encoded source map.
62 * @param IndexMapOffset $generatedSize The size of the generated output
63 * corresponding to $mapJson. This is used to advance the current offset
64 * and will be used to calculate the offset of the next section, if there
65 * is one.
66 * @return $this
67 */
68 public function addEncodedMap( string $mapJson, IndexMapOffset $generatedSize ) {
69 $this->sections[] =
70 '{"offset":' .
71 json_encode( [
72 'line' => $this->offset->line,
73 'column' => $this->offset->column,
74 ] ) .
75 ',"map":' .
76 $mapJson .
77 '}';
78 $this->offset->add( $generatedSize );
79 return $this;
80 }
81
82 /**
83 * Get the index map, encoded as JSON
84 *
85 * @return string
86 */
87 public function getMap(): string {
88 $map = "{\n" .
89 "\"version\": 3,\n";
90 if ( $this->file !== null ) {
91 $map .= '"file": ' . json_encode( $this->file ) . ",\n";
92 }
93 $map .= "\"sections\": [\n";
94 if ( $this->sections ) {
95 $map .= implode( ",\n", $this->sections ) . "\n";
96 }
97 $map .= "]\n}";
98 return $map;
99 }
100 }