Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like ResourceLoaderModule often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ResourceLoaderModule, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
32 | abstract class ResourceLoaderModule implements LoggerAwareInterface { |
||
33 | # Type of resource |
||
34 | const TYPE_SCRIPTS = 'scripts'; |
||
35 | const TYPE_STYLES = 'styles'; |
||
36 | const TYPE_COMBINED = 'combined'; |
||
37 | |||
38 | # Desired load type |
||
39 | // Module only has styles (loaded via <style> or <link rel=stylesheet>) |
||
40 | const LOAD_STYLES = 'styles'; |
||
41 | // Module may have other resources (loaded via mw.loader from a script) |
||
42 | const LOAD_GENERAL = 'general'; |
||
43 | |||
44 | # sitewide core module like a skin file or jQuery component |
||
45 | const ORIGIN_CORE_SITEWIDE = 1; |
||
46 | |||
47 | # per-user module generated by the software |
||
48 | const ORIGIN_CORE_INDIVIDUAL = 2; |
||
49 | |||
50 | # sitewide module generated from user-editable files, like MediaWiki:Common.js, or |
||
51 | # modules accessible to multiple users, such as those generated by the Gadgets extension. |
||
52 | const ORIGIN_USER_SITEWIDE = 3; |
||
53 | |||
54 | # per-user module generated from user-editable files, like User:Me/vector.js |
||
55 | const ORIGIN_USER_INDIVIDUAL = 4; |
||
56 | |||
57 | # an access constant; make sure this is kept as the largest number in this group |
||
58 | const ORIGIN_ALL = 10; |
||
59 | |||
60 | # script and style modules form a hierarchy of trustworthiness, with core modules like |
||
61 | # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can |
||
62 | # limit the types of scripts and styles we allow to load on, say, sensitive special |
||
63 | # pages like Special:UserLogin and Special:Preferences |
||
64 | protected $origin = self::ORIGIN_CORE_SITEWIDE; |
||
65 | |||
66 | /* Protected Members */ |
||
67 | |||
68 | protected $name = null; |
||
69 | protected $targets = [ 'desktop' ]; |
||
70 | |||
71 | // In-object cache for file dependencies |
||
72 | protected $fileDeps = []; |
||
73 | // In-object cache for message blob (keyed by language) |
||
74 | protected $msgBlobs = []; |
||
75 | // In-object cache for version hash |
||
76 | protected $versionHash = []; |
||
77 | // In-object cache for module content |
||
78 | protected $contents = []; |
||
79 | |||
80 | /** |
||
81 | * @var Config |
||
82 | */ |
||
83 | protected $config; |
||
84 | |||
85 | /** |
||
86 | * @var array|bool |
||
87 | */ |
||
88 | protected $deprecated = false; |
||
89 | |||
90 | /** |
||
91 | * @var LoggerInterface |
||
92 | */ |
||
93 | protected $logger; |
||
94 | |||
95 | /* Methods */ |
||
96 | |||
97 | /** |
||
98 | * Get this module's name. This is set when the module is registered |
||
99 | * with ResourceLoader::register() |
||
100 | * |
||
101 | * @return string|null Name (string) or null if no name was set |
||
102 | */ |
||
103 | public function getName() { |
||
106 | |||
107 | /** |
||
108 | * Set this module's name. This is called by ResourceLoader::register() |
||
109 | * when registering the module. Other code should not call this. |
||
110 | * |
||
111 | * @param string $name Name |
||
112 | */ |
||
113 | public function setName( $name ) { |
||
116 | |||
117 | /** |
||
118 | * Get this module's origin. This is set when the module is registered |
||
119 | * with ResourceLoader::register() |
||
120 | * |
||
121 | * @return int ResourceLoaderModule class constant, the subclass default |
||
122 | * if not set manually |
||
123 | */ |
||
124 | public function getOrigin() { |
||
127 | |||
128 | /** |
||
129 | * @param ResourceLoaderContext $context |
||
130 | * @return bool |
||
131 | */ |
||
132 | public function getFlip( $context ) { |
||
137 | |||
138 | /** |
||
139 | * Get JS representing deprecation information for the current module if available |
||
140 | * |
||
141 | * @return string JavaScript code |
||
142 | */ |
||
143 | protected function getDeprecationInformation() { |
||
159 | |||
160 | /** |
||
161 | * Get all JS for this module for a given language and skin. |
||
162 | * Includes all relevant JS except loader scripts. |
||
163 | * |
||
164 | * @param ResourceLoaderContext $context |
||
165 | * @return string JavaScript code |
||
166 | */ |
||
167 | public function getScript( ResourceLoaderContext $context ) { |
||
171 | |||
172 | /** |
||
173 | * Takes named templates by the module and returns an array mapping. |
||
174 | * |
||
175 | * @return array of templates mapping template alias to content |
||
176 | */ |
||
177 | public function getTemplates() { |
||
181 | |||
182 | /** |
||
183 | * @return Config |
||
184 | * @since 1.24 |
||
185 | */ |
||
186 | View Code Duplication | public function getConfig() { |
|
194 | |||
195 | /** |
||
196 | * @param Config $config |
||
197 | * @since 1.24 |
||
198 | */ |
||
199 | public function setConfig( Config $config ) { |
||
202 | |||
203 | /** |
||
204 | * @since 1.27 |
||
205 | * @param LoggerInterface $logger |
||
206 | * @return null |
||
207 | */ |
||
208 | public function setLogger( LoggerInterface $logger ) { |
||
211 | |||
212 | /** |
||
213 | * @since 1.27 |
||
214 | * @return LoggerInterface |
||
215 | */ |
||
216 | protected function getLogger() { |
||
222 | |||
223 | /** |
||
224 | * Get the URL or URLs to load for this module's JS in debug mode. |
||
225 | * The default behavior is to return a load.php?only=scripts URL for |
||
226 | * the module, but file-based modules will want to override this to |
||
227 | * load the files directly. |
||
228 | * |
||
229 | * This function is called only when 1) we're in debug mode, 2) there |
||
230 | * is no only= parameter and 3) supportsURLLoading() returns true. |
||
231 | * #2 is important to prevent an infinite loop, therefore this function |
||
232 | * MUST return either an only= URL or a non-load.php URL. |
||
233 | * |
||
234 | * @param ResourceLoaderContext $context |
||
235 | * @return array Array of URLs |
||
236 | */ |
||
237 | View Code Duplication | public function getScriptURLsForDebug( ResourceLoaderContext $context ) { |
|
251 | |||
252 | /** |
||
253 | * Whether this module supports URL loading. If this function returns false, |
||
254 | * getScript() will be used even in cases (debug mode, no only param) where |
||
255 | * getScriptURLsForDebug() would normally be used instead. |
||
256 | * @return bool |
||
257 | */ |
||
258 | public function supportsURLLoading() { |
||
261 | |||
262 | /** |
||
263 | * Get all CSS for this module for a given skin. |
||
264 | * |
||
265 | * @param ResourceLoaderContext $context |
||
266 | * @return array List of CSS strings or array of CSS strings keyed by media type. |
||
267 | * like array( 'screen' => '.foo { width: 0 }' ); |
||
268 | * or array( 'screen' => array( '.foo { width: 0 }' ) ); |
||
269 | */ |
||
270 | public function getStyles( ResourceLoaderContext $context ) { |
||
274 | |||
275 | /** |
||
276 | * Get the URL or URLs to load for this module's CSS in debug mode. |
||
277 | * The default behavior is to return a load.php?only=styles URL for |
||
278 | * the module, but file-based modules will want to override this to |
||
279 | * load the files directly. See also getScriptURLsForDebug() |
||
280 | * |
||
281 | * @param ResourceLoaderContext $context |
||
282 | * @return array Array( mediaType => array( URL1, URL2, ... ), ... ) |
||
283 | */ |
||
284 | View Code Duplication | public function getStyleURLsForDebug( ResourceLoaderContext $context ) { |
|
298 | |||
299 | /** |
||
300 | * Get the messages needed for this module. |
||
301 | * |
||
302 | * To get a JSON blob with messages, use MessageBlobStore::get() |
||
303 | * |
||
304 | * @return array List of message keys. Keys may occur more than once |
||
305 | */ |
||
306 | public function getMessages() { |
||
310 | |||
311 | /** |
||
312 | * Get the group this module is in. |
||
313 | * |
||
314 | * @return string Group name |
||
315 | */ |
||
316 | public function getGroup() { |
||
320 | |||
321 | /** |
||
322 | * Get the origin of this module. Should only be overridden for foreign modules. |
||
323 | * |
||
324 | * @return string Origin name, 'local' for local modules |
||
325 | */ |
||
326 | public function getSource() { |
||
330 | |||
331 | /** |
||
332 | * Where on the HTML page should this module's JS be loaded? |
||
333 | * - 'top': in the "<head>" |
||
334 | * - 'bottom': at the bottom of the "<body>" |
||
335 | * |
||
336 | * @return string |
||
337 | */ |
||
338 | public function getPosition() { |
||
341 | |||
342 | /** |
||
343 | * Whether this module's JS expects to work without the client-side ResourceLoader module. |
||
344 | * Returning true from this function will prevent mw.loader.state() call from being |
||
345 | * appended to the bottom of the script. |
||
346 | * |
||
347 | * @return bool |
||
348 | */ |
||
349 | public function isRaw() { |
||
352 | |||
353 | /** |
||
354 | * Get a list of modules this module depends on. |
||
355 | * |
||
356 | * Dependency information is taken into account when loading a module |
||
357 | * on the client side. |
||
358 | * |
||
359 | * Note: It is expected that $context will be made non-optional in the near |
||
360 | * future. |
||
361 | * |
||
362 | * @param ResourceLoaderContext $context |
||
363 | * @return array List of module names as strings |
||
364 | */ |
||
365 | public function getDependencies( ResourceLoaderContext $context = null ) { |
||
369 | |||
370 | /** |
||
371 | * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile'] |
||
372 | * |
||
373 | * @return array Array of strings |
||
374 | */ |
||
375 | public function getTargets() { |
||
378 | |||
379 | /** |
||
380 | * Get the module's load type. |
||
381 | * |
||
382 | * @since 1.28 |
||
383 | * @return string ResourceLoaderModule LOAD_* constant |
||
384 | */ |
||
385 | public function getType() { |
||
388 | |||
389 | /** |
||
390 | * Get the skip function. |
||
391 | * |
||
392 | * Modules that provide fallback functionality can provide a "skip function". This |
||
393 | * function, if provided, will be passed along to the module registry on the client. |
||
394 | * When this module is loaded (either directly or as a dependency of another module), |
||
395 | * then this function is executed first. If the function returns true, the module will |
||
396 | * instantly be considered "ready" without requesting the associated module resources. |
||
397 | * |
||
398 | * The value returned here must be valid javascript for execution in a private function. |
||
399 | * It must not contain the "function () {" and "}" wrapper though. |
||
400 | * |
||
401 | * @return string|null A JavaScript function body returning a boolean value, or null |
||
402 | */ |
||
403 | public function getSkipFunction() { |
||
406 | |||
407 | /** |
||
408 | * Get the files this module depends on indirectly for a given skin. |
||
409 | * |
||
410 | * These are only image files referenced by the module's stylesheet. |
||
411 | * |
||
412 | * @param ResourceLoaderContext $context |
||
413 | * @return array List of files |
||
414 | */ |
||
415 | protected function getFileDependencies( ResourceLoaderContext $context ) { |
||
440 | |||
441 | /** |
||
442 | * Set in-object cache for file dependencies. |
||
443 | * |
||
444 | * This is used to retrieve data in batches. See ResourceLoader::preloadModuleInfo(). |
||
445 | * To save the data, use saveFileDependencies(). |
||
446 | * |
||
447 | * @param ResourceLoaderContext $context |
||
448 | * @param string[] $files Array of file names |
||
449 | */ |
||
450 | public function setFileDependencies( ResourceLoaderContext $context, $files ) { |
||
454 | |||
455 | /** |
||
456 | * Set the files this module depends on indirectly for a given skin. |
||
457 | * |
||
458 | * @since 1.27 |
||
459 | * @param ResourceLoaderContext $context |
||
460 | * @param array $localFileRefs List of files |
||
461 | */ |
||
462 | protected function saveFileDependencies( ResourceLoaderContext $context, $localFileRefs ) { |
||
497 | |||
498 | /** |
||
499 | * Make file paths relative to MediaWiki directory. |
||
500 | * |
||
501 | * This is used to make file paths safe for storing in a database without the paths |
||
502 | * becoming stale or incorrect when MediaWiki is moved or upgraded (T111481). |
||
503 | * |
||
504 | * @since 1.27 |
||
505 | * @param array $filePaths |
||
506 | * @return array |
||
507 | */ |
||
508 | public static function getRelativePaths( array $filePaths ) { |
||
514 | |||
515 | /** |
||
516 | * Expand directories relative to $IP. |
||
517 | * |
||
518 | * @since 1.27 |
||
519 | * @param array $filePaths |
||
520 | * @return array |
||
521 | */ |
||
522 | public static function expandRelativePaths( array $filePaths ) { |
||
528 | |||
529 | /** |
||
530 | * Get the hash of the message blob. |
||
531 | * |
||
532 | * @since 1.27 |
||
533 | * @param ResourceLoaderContext $context |
||
534 | * @return string|null JSON blob or null if module has no messages |
||
535 | */ |
||
536 | protected function getMessageBlob( ResourceLoaderContext $context ) { |
||
552 | |||
553 | /** |
||
554 | * Set in-object cache for message blobs. |
||
555 | * |
||
556 | * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo(). |
||
557 | * |
||
558 | * @since 1.27 |
||
559 | * @param string|null $blob JSON blob or null |
||
560 | * @param string $lang Language code |
||
561 | */ |
||
562 | public function setMessageBlob( $blob, $lang ) { |
||
565 | |||
566 | /** |
||
567 | * Get module-specific LESS variables, if any. |
||
568 | * |
||
569 | * @since 1.27 |
||
570 | * @param ResourceLoaderContext $context |
||
571 | * @return array Module-specific LESS variables. |
||
572 | */ |
||
573 | protected function getLessVars( ResourceLoaderContext $context ) { |
||
576 | |||
577 | /** |
||
578 | * Get an array of this module's resources. Ready for serving to the web. |
||
579 | * |
||
580 | * @since 1.26 |
||
581 | * @param ResourceLoaderContext $context |
||
582 | * @return array |
||
583 | */ |
||
584 | public function getModuleContent( ResourceLoaderContext $context ) { |
||
593 | |||
594 | /** |
||
595 | * Bundle all resources attached to this module into an array. |
||
596 | * |
||
597 | * @since 1.26 |
||
598 | * @param ResourceLoaderContext $context |
||
599 | * @return array |
||
600 | */ |
||
601 | final protected function buildContent( ResourceLoaderContext $context ) { |
||
696 | |||
697 | /** |
||
698 | * Get a string identifying the current version of this module in a given context. |
||
699 | * |
||
700 | * Whenever anything happens that changes the module's response (e.g. scripts, styles, and |
||
701 | * messages) this value must change. This value is used to store module responses in cache. |
||
702 | * (Both client-side and server-side.) |
||
703 | * |
||
704 | * It is not recommended to override this directly. Use getDefinitionSummary() instead. |
||
705 | * If overridden, one must call the parent getVersionHash(), append data and re-hash. |
||
706 | * |
||
707 | * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to |
||
708 | * propagate changes to the client and effectively invalidate cache. |
||
709 | * |
||
710 | * For backward-compatibility, the following optional data providers are automatically included: |
||
711 | * |
||
712 | * - getModifiedTime() |
||
713 | * - getModifiedHash() |
||
714 | * |
||
715 | * @since 1.26 |
||
716 | * @param ResourceLoaderContext $context |
||
717 | * @return string Hash (should use ResourceLoader::makeHash) |
||
718 | */ |
||
719 | public function getVersionHash( ResourceLoaderContext $context ) { |
||
763 | |||
764 | /** |
||
765 | * Whether to generate version hash based on module content. |
||
766 | * |
||
767 | * If a module requires database or file system access to build the module |
||
768 | * content, consider disabling this in favour of manually tracking relevant |
||
769 | * aspects in getDefinitionSummary(). See getVersionHash() for how this is used. |
||
770 | * |
||
771 | * @return bool |
||
772 | */ |
||
773 | public function enableModuleContentVersion() { |
||
776 | |||
777 | /** |
||
778 | * Get the definition summary for this module. |
||
779 | * |
||
780 | * This is the method subclasses are recommended to use to track values in their |
||
781 | * version hash. Call this in getVersionHash() and pass it to e.g. json_encode. |
||
782 | * |
||
783 | * Subclasses must call the parent getDefinitionSummary() and build on that. |
||
784 | * It is recommended that each subclass appends its own new array. This prevents |
||
785 | * clashes or accidental overwrites of existing keys and gives each subclass |
||
786 | * its own scope for simple array keys. |
||
787 | * |
||
788 | * @code |
||
789 | * $summary = parent::getDefinitionSummary( $context ); |
||
790 | * $summary[] = array( |
||
791 | * 'foo' => 123, |
||
792 | * 'bar' => 'quux', |
||
793 | * ); |
||
794 | * return $summary; |
||
795 | * @endcode |
||
796 | * |
||
797 | * Return an array containing values from all significant properties of this |
||
798 | * module's definition. |
||
799 | * |
||
800 | * Be careful not to normalise too much. Especially preserve the order of things |
||
801 | * that carry significance in getScript and getStyles (T39812). |
||
802 | * |
||
803 | * Avoid including things that are insiginificant (e.g. order of message keys is |
||
804 | * insignificant and should be sorted to avoid unnecessary cache invalidation). |
||
805 | * |
||
806 | * This data structure must exclusively contain arrays and scalars as values (avoid |
||
807 | * object instances) to allow simple serialisation using json_encode. |
||
808 | * |
||
809 | * If modules have a hash or timestamp from another source, that may be incuded as-is. |
||
810 | * |
||
811 | * A number of utility methods are available to help you gather data. These are not |
||
812 | * called by default and must be included by the subclass' getDefinitionSummary(). |
||
813 | * |
||
814 | * - getMessageBlob() |
||
815 | * |
||
816 | * @since 1.23 |
||
817 | * @param ResourceLoaderContext $context |
||
818 | * @return array|null |
||
819 | */ |
||
820 | public function getDefinitionSummary( ResourceLoaderContext $context ) { |
||
826 | |||
827 | /** |
||
828 | * Get this module's last modification timestamp for a given context. |
||
829 | * |
||
830 | * @deprecated since 1.26 Use getDefinitionSummary() instead |
||
831 | * @param ResourceLoaderContext $context Context object |
||
832 | * @return int|null UNIX timestamp |
||
833 | */ |
||
834 | public function getModifiedTime( ResourceLoaderContext $context ) { |
||
837 | |||
838 | /** |
||
839 | * Helper method for providing a version hash to getVersionHash(). |
||
840 | * |
||
841 | * @deprecated since 1.26 Use getDefinitionSummary() instead |
||
842 | * @param ResourceLoaderContext $context |
||
843 | * @return string|null Hash |
||
844 | */ |
||
845 | public function getModifiedHash( ResourceLoaderContext $context ) { |
||
848 | |||
849 | /** |
||
850 | * Back-compat dummy for old subclass implementations of getModifiedTime(). |
||
851 | * |
||
852 | * This method used to use ObjectCache to track when a hash was first seen. That principle |
||
853 | * stems from a time that ResourceLoader could only identify module versions by timestamp. |
||
854 | * That is no longer the case. Use getDefinitionSummary() directly. |
||
855 | * |
||
856 | * @deprecated since 1.26 Superseded by getVersionHash() |
||
857 | * @param ResourceLoaderContext $context |
||
858 | * @return int UNIX timestamp |
||
859 | */ |
||
860 | public function getHashMtime( ResourceLoaderContext $context ) { |
||
867 | |||
868 | /** |
||
869 | * Back-compat dummy for old subclass implementations of getModifiedTime(). |
||
870 | * |
||
871 | * @since 1.23 |
||
872 | * @deprecated since 1.26 Superseded by getVersionHash() |
||
873 | * @param ResourceLoaderContext $context |
||
874 | * @return int UNIX timestamp |
||
875 | */ |
||
876 | public function getDefinitionMtime( ResourceLoaderContext $context ) { |
||
883 | |||
884 | /** |
||
885 | * Check whether this module is known to be empty. If a child class |
||
886 | * has an easy and cheap way to determine that this module is |
||
887 | * definitely going to be empty, it should override this method to |
||
888 | * return true in that case. Callers may optimize the request for this |
||
889 | * module away if this function returns true. |
||
890 | * @param ResourceLoaderContext $context |
||
891 | * @return bool |
||
892 | */ |
||
893 | public function isKnownEmpty( ResourceLoaderContext $context ) { |
||
896 | |||
897 | /** @var JSParser Lazy-initialized; use self::javaScriptParser() */ |
||
898 | private static $jsParser; |
||
899 | private static $parseCacheVersion = 1; |
||
900 | |||
901 | /** |
||
902 | * Validate a given script file; if valid returns the original source. |
||
903 | * If invalid, returns replacement JS source that throws an exception. |
||
904 | * |
||
905 | * @param string $fileName |
||
906 | * @param string $contents |
||
907 | * @return string JS with the original, or a replacement error |
||
908 | */ |
||
909 | protected function validateScriptFile( $fileName, $contents ) { |
||
941 | |||
942 | /** |
||
943 | * @return JSParser |
||
944 | */ |
||
945 | protected static function javaScriptParser() { |
||
951 | |||
952 | /** |
||
953 | * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist. |
||
954 | * Defaults to 1. |
||
955 | * |
||
956 | * @param string $filePath File path |
||
957 | * @return int UNIX timestamp |
||
958 | */ |
||
959 | protected static function safeFilemtime( $filePath ) { |
||
965 | |||
966 | /** |
||
967 | * Compute a non-cryptographic string hash of a file's contents. |
||
968 | * If the file does not exist or cannot be read, returns an empty string. |
||
969 | * |
||
970 | * @since 1.26 Uses MD4 instead of SHA1. |
||
971 | * @param string $filePath File path |
||
972 | * @return string Hash |
||
973 | */ |
||
974 | protected static function safeFileHash( $filePath ) { |
||
977 | } |
||
978 |
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: