Debian Codegraph @

skins/Vector/includes/FeatureManagement/FeatureManager.php

raw symbols SCIP
1 <?php
2
3 /**
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 * http://www.gnu.org/copyleft/gpl.html
18 *
19 * @file
20 * @since 1.35
21 */
22
23 namespace MediaWiki\Skins\Vector\FeatureManagement;
24
25 use MediaWiki\Context\IContextSource;
26 use MediaWiki\Skins\Vector\ConfigHelper;
27 use MediaWiki\Skins\Vector\Constants;
28 use MediaWiki\Skins\Vector\FeatureManagement\Requirements\SimpleRequirement;
29 use MediaWiki\User\Options\UserOptionsLookup;
30 use RuntimeException;
31 use Wikimedia\Assert\Assert;
32
33 /**
34 * A simple feature manager.
35 *
36 * NOTE: This API hasn't settled. It may change at any time without warning. Please don't bind to
37 * it unless you absolutely need to.
38 *
39 * @unstable
40 *
41 * @package MediaWiki\Skins\Vector\FeatureManagement
42 * @internal
43 * @final
44 */
45 class FeatureManager {
46
47 /**
48 * A map of feature name to the array of requirements (referenced by name). A feature is only
49 * considered enabled when all of its requirements are met.
50 *
51 * See FeatureManager::registerFeature for additional detail.
52 *
53 * @var Array<string,string[]>
54 */
55 private $features = [];
56
57 /**
58 * A map of requirement name to the Requirement instance that represents it.
59 *
60 * The names of requirements are assumed to be static for the lifetime of the request. Therefore
61 * we can use them to look up Requirement instances quickly.
62 *
63 * @var Array<string,Requirement>
64 */
65 private $requirements = [];
66
67 private UserOptionsLookup $userOptionsLookup;
68 private IContextSource $context;
69
70 public function __construct(
71 UserOptionsLookup $userOptionsLookup,
72 IContextSource $context
73 ) {
74 $this->userOptionsLookup = $userOptionsLookup;
75 $this->context = $context;
76 }
77
78 /**
79 * Register a feature and its requirements.
80 *
81 * Essentially, a "feature" is a friendly (hopefully) name for some component, however big or
82 * small, that has some requirements. A feature manager allows us to decouple the component's
83 * logic from its requirements, allowing them to vary independently. Moreover, the use of
84 * friendly names wherever possible allows us to define a common language with our non-technical
85 * colleagues.
86 *
87 * ```php
88 * $featureManager->registerFeature( 'featureA', 'requirementA' );
89 * ```
90 *
91 * defines the "featureA" feature, which is enabled when the "requirementA" requirement is met.
92 *
93 * ```php
94 * $featureManager->registerFeature( 'featureB', [ 'requirementA', 'requirementB' ] );
95 * ```
96 *
97 * defines the "featureB" feature, which is enabled when the "requirementA" and "requirementB"
98 * requirements are met. Note well that the feature is only enabled when _all_ requirements are
99 * met, i.e. the requirements are evaluated in order and logically `AND`ed together.
100 *
101 * @param string $feature The name of the feature
102 * @param string|array $requirements The feature's requirements. As above, you can define a
103 * feature that requires a single requirement via the shorthand
104 *
105 * ```php
106 * $featureManager->registerFeature( 'feature', 'requirementA' );
107 * // Equivalent to $featureManager->registerFeature( 'feature', [ 'requirementA' ] );
108 * ```
109 *
110 * @throws \LogicException If the feature is already registered
111 * @throws \Wikimedia\Assert\ParameterAssertionException If the feature's requirements aren't
112 * the name of a single requirement or a list of requirements
113 * @throws \InvalidArgumentException If the feature references a requirement that isn't
114 * registered
115 */
116 public function registerFeature( string $feature, $requirements ) {
117 //
118 // Validation
119 if ( array_key_exists( $feature, $this->features ) ) {
120 throw new \LogicException( sprintf(
121 'Feature "%s" is already registered.',
122 $feature
123 ) );
124 }
125
126 Assert::parameterType( 'string|array', $requirements, 'requirements' );
127
128 $requirements = (array)$requirements;
129
130 Assert::parameterElementType( 'string', $requirements, 'requirements' );
131
132 foreach ( $requirements as $name ) {
133 if ( !array_key_exists( $name, $this->requirements ) ) {
134 throw new \InvalidArgumentException( sprintf(
135 'Feature "%s" references requirement "%s", which hasn\'t been registered',
136 $feature,
137 $name
138 ) );
139 }
140 }
141
142 // Mutation
143 $this->features[$feature] = $requirements;
144 }
145
146 /**
147 * Gets user's preference value
148 *
149 * If user preference is not set or did not appear in config
150 * set it to default value we go back to defualt suffix value
151 * that will ensure that the feature will be enabled when requirements are met
152 *
153 * @param string $preferenceKey User preference key
154 * @return string
155 */
156 public function getUserPreferenceValue( $preferenceKey ) {
157 return $this->userOptionsLookup->getOption(
158 $this->context->getUser(),
159 $preferenceKey
160 // For client preferences, this should be the same as `preferenceKey`
161 // in 'resources/skins.vector.js/clientPreferences.json'
162 );
163 }
164
165 /**
166 * Return a list of classes that should be added to the body tag
167 *
168 * @return array
169 */
170 public function getFeatureBodyClass() {
171 return array_map( function ( $featureName ) {
172 // switch to lower case and switch from camel case to hyphens
173 $featureClass = ltrim( strtolower( preg_replace( '/[A-Z]([A-Z](?![a-z]))*/', '-$0', $featureName ) ), '-' );
174 $prefix = 'vector-feature-' . $featureClass . '-';
175
176 // some features (eg night mode) will require request context to determine status
177 $request = $this->context->getRequest();
178 $config = $this->context->getConfig();
179 $title = $this->context->getTitle();
180
181 // Client side preferences
182 switch ( $featureName ) {
183 // This feature has 3 possible states: 0, 1, 2 and -excluded.
184 // It persists for all users.
185 case CONSTANTS::FEATURE_FONT_SIZE:
186 if ( ConfigHelper::shouldDisable(
187 $config->get( 'VectorFontSizeConfigurableOptions' ), $request, $title
188 ) ) {
189 return $prefix . 'clientpref--excluded';
190 }
191 $suffixEnabled = 'clientpref-' . $this->getUserPreferenceValue( CONSTANTS::PREF_KEY_FONT_SIZE );
192 $suffixDisabled = 'clientpref-0';
193 break;
194 // This feature has 4 possible states: day, night, os and -excluded.
195 // It persists for all users.
196 case CONSTANTS::PREF_NIGHT_MODE:
197 // if night mode is disabled for the page, add the exclude class instead and return early
198 if ( ConfigHelper::shouldDisable( $config->get( 'VectorNightModeOptions' ), $request, $title ) ) {
199 // The additional "-" prefix, makes this an invalid client preference for anonymous users.
200 return 'skin-theme-clientpref--excluded';
201 }
202
203 $prefix = '';
204 $valueRequest = $request->getRawVal( 'vectornightmode' );
205 // If night mode query string is used, hardcode pref value to the night mode value
206 // NOTE: The query string parameter only works for logged in users.
207 // IF you have set a cookie locally this will be overriden.
208 $value = $valueRequest !== null ? self::resolveNightModeQueryValue( $valueRequest ) :
209 $this->getUserPreferenceValue( CONSTANTS::PREF_KEY_NIGHT_MODE );
210 $suffixEnabled = 'clientpref-' . $value;
211 $suffixDisabled = 'clientpref-day';
212 // Must be hardcoded to 'skin-theme-' to be consistent with Minerva
213 // So that editors can target the same class across skins
214 $prefix .= 'skin-theme-';
215 break;
216 // These features persist for all users and have two valid states: 0 and 1.
217 case CONSTANTS::FEATURE_LIMITED_WIDTH:
218 case CONSTANTS::FEATURE_TOC_PINNED:
219 case CONSTANTS::FEATURE_APPEARANCE_PINNED:
220 $suffixEnabled = 'clientpref-1';
221 $suffixDisabled = 'clientpref-0';
222 break;
223 // These features only persist for logged in users so do not contain the clientpref suffix.
224 // These features have two valid states: enabled and disabled. In future it would be nice if these
225 // were 0 and 1 so that the features.js module cannot be applied to server side only flags.
226 case CONSTANTS::FEATURE_MAIN_MENU_PINNED:
227 case CONSTANTS::FEATURE_PAGE_TOOLS_PINNED:
228 // Server side only feature flags.
229 // Note these classes are fixed and cannot be changed at runtime by JavaScript,
230 // only via modification to LocalSettings.php.
231 case Constants::FEATURE_NIGHT_MODE:
232 case Constants::FEATURE_LIMITED_WIDTH_CONTENT:
233 case Constants::FEATURE_LANGUAGE_IN_HEADER:
234 case Constants::FEATURE_LANGUAGE_IN_MAIN_PAGE_HEADER:
235 case Constants::FEATURE_STICKY_HEADER:
236 $suffixEnabled = 'enabled';
237 $suffixDisabled = 'disabled';
238 break;
239 default:
240 throw new RuntimeException( "Feature $featureName has no associated feature class." );
241 }
242 return $this->isFeatureEnabled( $featureName ) ?
243 $prefix . $suffixEnabled : $prefix . $suffixDisabled;
244 }, array_keys( $this->features ) );
245 }
246
247 /**
248 * Gets whether the feature's requirements are met.
249 *
250 * @param string $feature
251 * @return bool
252 *
253 * @throws \InvalidArgumentException If the feature isn't registered
254 */
255 public function isFeatureEnabled( string $feature ): bool {
256 if ( !array_key_exists( $feature, $this->features ) ) {
257 throw new \InvalidArgumentException( "The feature \"{$feature}\" isn't registered." );
258 }
259
260 $requirements = $this->features[$feature];
261
262 foreach ( $requirements as $name ) {
263 if ( !$this->requirements[$name]->isMet() ) {
264 return false;
265 }
266 }
267
268 return true;
269 }
270
271 /**
272 * Register a complex {@see Requirement}.
273 *
274 * A complex requirement is one that depends on object that may or may not be fully loaded
275 * while the application is booting, e.g. see `User::isSafeToLoad`.
276 *
277 * Such requirements are expected to be registered during a hook that is run early on in the
278 * application lifecycle, e.g. the `BeforePerformAction` and `APIBeforeMain` hooks.
279 *
280 * @param Requirement $requirement
281 *
282 * @throws \LogicException If the requirement has already been registered
283 */
284 public function registerRequirement( Requirement $requirement ) {
285 $name = $requirement->getName();
286
287 if ( array_key_exists( $name, $this->requirements ) ) {
288 throw new \LogicException( "The requirement \"{$name}\" is already registered." );
289 }
290
291 $this->requirements[$name] = $requirement;
292 }
293
294 /**
295 * Register a {@see SimpleRequirement}.
296 *
297 * A requirement is some condition of the application state that a feature requires to be true
298 * or false.
299 *
300 * @param string $name The name of the requirement
301 * @param bool $isMet Whether the requirement is met
302 *
303 * @throws \LogicException If the requirement has already been registered
304 */
305 public function registerSimpleRequirement( string $name, bool $isMet ) {
306 $this->registerRequirement( new SimpleRequirement( $name, $isMet ) );
307 }
308
309 /**
310 * Gets whether the requirement is met.
311 *
312 * @param string $name The name of the requirement
313 * @return bool
314 *
315 * @throws \InvalidArgumentException If the requirement isn't registered
316 */
317 public function isRequirementMet( string $name ): bool {
318 if ( !array_key_exists( $name, $this->requirements ) ) {
319 throw new \InvalidArgumentException( "Requirement \"{$name}\" isn't registered." );
320 }
321
322 return $this->requirements[$name]->isMet();
323 }
324
325 /**
326 * Converts "1", "2", and "0" to equivalent values.
327 *
328 * @return string
329 */
330 private static function resolveNightModeQueryValue( string $value ) {
331 switch ( $value ) {
332 case 'day':
333 case 'night':
334 case 'os':
335 return $value;
336 case '1':
337 return 'night';
338 case '2':
339 return 'os';
340 default:
341 return 'day';
342 }
343 }
344 }