Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
50.00% covered (danger)
50.00%
4 / 8
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
GrammarTransformations
50.00% covered (danger)
50.00%
4 / 8
50.00% covered (danger)
50.00%
1 / 2
4.12
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getTransformations
42.86% covered (danger)
42.86%
3 / 7
0.00% covered (danger)
0.00%
0 / 1
2.75
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace Wikimedia\Leximorph\Provider;
8
9use Wikimedia\Leximorph\Util\JsonLoader;
10
11/**
12 * GrammarTransformations
13 *
14 * Provides functionality to load and cache grammar transformation rules from JSON files.
15 *
16 * @since     1.45
17 * @author    Doğu Abaris (abaris@null.net)
18 * @license   https://www.gnu.org/copyleft/gpl.html GPL-2.0-or-later
19 */
20class GrammarTransformations {
21
22    /**
23     * The paths to the grammar rules JSON files.
24     */
25    private const string TRANSFORMATIONS_PATH = __DIR__ . '/../data/grammarTransformations/';
26
27    /**
28     * Cached grammar transformations indexed by language code.
29     *
30     * @var array<string, array<int|string, mixed>>
31     */
32    private static array $transformationsCache = [];
33
34    /**
35     * @since 1.45
36     */
37    public function __construct(
38        private readonly string $langCode,
39        private readonly JsonLoader $jsonLoader,
40    ) {
41    }
42
43    /**
44     * Returns grammar transformation rules for the current language.
45     *
46     * @since 1.45
47     * @return array<int|string, mixed> Grammar transformation rules.
48     */
49    public function getTransformations(): array {
50        self::$transformationsCache ??= [];
51
52        if ( isset( self::$transformationsCache[$this->langCode] ) ) {
53            return self::$transformationsCache[$this->langCode];
54        }
55
56        $filePath = self::TRANSFORMATIONS_PATH . $this->langCode . '.json';
57        $transformations = $this->jsonLoader->load( $filePath, 'grammar transformations' );
58
59        self::$transformationsCache[$this->langCode] = $transformations;
60
61        return $transformations;
62    }
63}