MediaWiki master
FormalityIndex.php
Go to the documentation of this file.
1<?php
8
9use Psr\Log\LoggerInterface;
11
22
23 private const string FORMALITY_INDEXES_PATH = __DIR__ . '/../data/formal-indexes.json';
24
28 private static ?array $indexesCache = null;
29
33 public function __construct(
34 private readonly string $langCode,
35 private readonly LoggerInterface $logger,
36 private readonly JsonLoader $jsonLoader,
37 ) {
38 }
39
49 public function getFormalityIndex(): int {
50 self::$indexesCache ??= $this->loadIndexes();
52
53 if ( array_key_exists( $this->langCode, $indexesCache ) ) {
54 return $indexesCache[$this->langCode];
55 }
56
57 if ( str_contains( $this->langCode, '-' ) ) {
58 $parts = explode( '-', $this->langCode );
59 $suffix = array_pop( $parts );
60 if ( $suffix === 'formal' ) {
61 return 1;
62 } elseif ( $suffix === 'informal' ) {
63 return 0;
64 }
65
66 return $indexesCache[implode( '-', $parts )] ?? 0;
67 }
68
69 return 0;
70 }
71
78 private function loadIndexes(): array {
79 $rawIndexes = $this->jsonLoader->load( self::FORMALITY_INDEXES_PATH, 'formality indexes' );
80 $indexes = [];
81
82 foreach ( $rawIndexes as $key => $value ) {
83 if ( is_string( $key ) && is_int( $value ) ) {
84 $indexes[$key] = $value;
85 } else {
86 $this->logger->error(
87 'Invalid formality index entry. Expected string key and int value. ' .
88 'Got key type {keyType}, value type {valueType}.',
89 [
90 'keyType' => gettype( $key ),
91 'valueType' => gettype( $value ),
92 ]
93 );
94 }
95 }
96
97 return $indexes;
98 }
99}