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 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     * Initializes the GrammarTransformations.
36     *
37     * @param string $langCode The language code.
38     * @param JsonLoader $jsonLoader The json loader to load data
39     *
40     * @since 1.45
41     */
42    public function __construct(
43        private readonly string $langCode,
44        private readonly JsonLoader $jsonLoader,
45    ) {
46    }
47
48    /**
49     * Returns grammar transformation rules for the current language.
50     *
51     * @since 1.45
52     * @return array<int|string, mixed> Grammar transformation rules.
53     */
54    public function getTransformations(): array {
55        self::$transformationsCache ??= [];
56
57        if ( isset( self::$transformationsCache[$this->langCode] ) ) {
58            return self::$transformationsCache[$this->langCode];
59        }
60
61        $filePath = self::TRANSFORMATIONS_PATH . $this->langCode . '.json';
62        $transformations = $this->jsonLoader->load( $filePath, 'grammar transformations' );
63
64        self::$transformationsCache[$this->langCode] = $transformations;
65
66        return $transformations;
67    }
68}