MediaWiki master
FormalityIndex.php
Go to the documentation of this file.
1<?php
8
9use Psr\Log\LoggerInterface;
11
22
26 private const FORMALITY_INDEXES_PATH = __DIR__ . '/../data/formal-indexes.json';
27
33 private static ?array $indexesCache = null;
34
44 public function __construct(
45 private readonly string $langCode,
46 private readonly LoggerInterface $logger,
47 private readonly JsonLoader $jsonLoader,
48 ) {
49 }
50
60 public function getFormalityIndex(): int {
61 self::$indexesCache ??= $this->loadIndexes();
63
64 if ( array_key_exists( $this->langCode, $indexesCache ) ) {
65 return $indexesCache[$this->langCode];
66 }
67
68 if ( str_contains( $this->langCode, '-' ) ) {
69 $parts = explode( '-', $this->langCode );
70 $suffix = array_pop( $parts );
71 if ( $suffix === 'formal' ) {
72 return 1;
73 } elseif ( $suffix === 'informal' ) {
74 return 0;
75 }
76
77 return $indexesCache[implode( '-', $parts )] ?? 0;
78 }
79
80 return 0;
81 }
82
89 private function loadIndexes(): array {
90 $rawIndexes = $this->jsonLoader->load( self::FORMALITY_INDEXES_PATH, 'formality indexes' );
91 $indexes = [];
92
93 foreach ( $rawIndexes as $key => $value ) {
94 if ( is_string( $key ) && is_int( $value ) ) {
95 $indexes[$key] = $value;
96 } else {
97 $this->logger->error(
98 'Invalid formality index entry. Expected string key and int value. ' .
99 'Got key type {keyType}, value type {valueType}.',
100 [
101 'keyType' => gettype( $key ),
102 'valueType' => gettype( $value ),
103 ]
104 );
105 }
106 }
107
108 return $indexes;
109 }
110}