resourceloader: Throw InvalidArgumentException for invalid constructor arguments
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderImageModule.php
1 <?php
2 /**
3 * Resource loader module for generated and embedded images.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Trevor Parscal
22 */
23
24 /**
25 * Resource loader module for generated and embedded images.
26 *
27 * @since 1.25
28 */
29 class ResourceLoaderImageModule extends ResourceLoaderModule {
30
31 /**
32 * Local base path, see __construct()
33 * @var string
34 */
35 protected $localBasePath = '';
36
37 protected $origin = self::ORIGIN_CORE_SITEWIDE;
38
39 protected $images = array();
40 protected $variants = array();
41 protected $prefix = null;
42 protected $selectorWithoutVariant = '.{prefix}-{name}';
43 protected $selectorWithVariant = '.{prefix}-{name}-{variant}';
44 protected $targets = array( 'desktop', 'mobile' );
45
46 /**
47 * Constructs a new module from an options array.
48 *
49 * @param array $options List of options; if not given or empty, an empty module will be
50 * constructed
51 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
52 * to $IP
53 *
54 * Below is a description for the $options array:
55 * @par Construction options:
56 * @code
57 * array(
58 * // Base path to prepend to all local paths in $options. Defaults to $IP
59 * 'localBasePath' => [base path],
60 * // CSS class prefix to use in all style rules
61 * 'prefix' => [CSS class prefix],
62 * // Alternatively: Format of CSS selector to use in all style rules
63 * 'selector' => [CSS selector template, variables: {prefix} {name} {variant}],
64 * // Alternatively: When using variants
65 * 'selectorWithoutVariant' => [CSS selector template, variables: {prefix} {name}],
66 * 'selectorWithVariant' => [CSS selector template, variables: {prefix} {name} {variant}],
67 * // List of variants that may be used for the image files
68 * 'variants' => array(
69 * [variant name] => array(
70 * 'color' => [color string, e.g. '#ffff00'],
71 * 'global' => [boolean, if true, this variant is available
72 * for all images of this type],
73 * ),
74 * ...
75 * ),
76 * // List of image files and their options
77 * 'images' => array(
78 * [file path string],
79 * [file path string] => array(
80 * 'name' => [image name string, defaults to file name],
81 * 'variants' => [array of variant name strings, variants
82 * available for this image],
83 * ),
84 * ...
85 * ),
86 * )
87 * @endcode
88 * @throws InvalidArgumentException
89 */
90 public function __construct( $options = array(), $localBasePath = null ) {
91 $this->localBasePath = self::extractLocalBasePath( $options, $localBasePath );
92
93 // Accepted combinations:
94 // * prefix
95 // * selector
96 // * selectorWithoutVariant + selectorWithVariant
97 // * prefix + selector
98 // * prefix + selectorWithoutVariant + selectorWithVariant
99
100 $prefix = isset( $options['prefix'] ) && $options['prefix'];
101 $selector = isset( $options['selector'] ) && $options['selector'];
102 $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] ) && $options['selectorWithoutVariant'];
103 $selectorWithVariant = isset( $options['selectorWithVariant'] ) && $options['selectorWithVariant'];
104
105 if ( $selectorWithoutVariant && !$selectorWithVariant ) {
106 throw new InvalidArgumentException( "Given 'selectorWithoutVariant' but no 'selectorWithVariant'." );
107 }
108 if ( $selectorWithVariant && !$selectorWithoutVariant ) {
109 throw new InvalidArgumentException( "Given 'selectorWithVariant' but no 'selectorWithoutVariant'." );
110 }
111 if ( $selector && $selectorWithVariant ) {
112 throw new InvalidArgumentException( "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given." );
113 }
114 if ( !$prefix && !$selector && !$selectorWithVariant ) {
115 throw new InvalidArgumentException( "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given." );
116 }
117
118 foreach ( $options as $member => $option ) {
119 switch ( $member ) {
120 case 'images':
121 case 'variants':
122 if ( !is_array( $option ) ) {
123 throw new InvalidArgumentException(
124 "Invalid list error. '$option' given, array expected."
125 );
126 }
127 $this->{$member} = $option;
128 break;
129
130 case 'prefix':
131 case 'selectorWithoutVariant':
132 case 'selectorWithVariant':
133 $this->{$member} = (string)$option;
134 break;
135
136 case 'selector':
137 $this->selectorWithoutVariant = $this->selectorWithVariant = (string)$option;
138 }
139 }
140 }
141
142 /**
143 * Get CSS class prefix used by this module.
144 * @return string
145 */
146 public function getPrefix() {
147 return $this->prefix;
148 }
149
150 /**
151 * Get CSS selector templates used by this module.
152 * @return string
153 */
154 public function getSelectors() {
155 return array(
156 'selectorWithoutVariant' => $this->selectorWithoutVariant,
157 'selectorWithVariant' => $this->selectorWithVariant,
158 );
159 }
160
161 /**
162 * Get a ResourceLoaderImage object for given image.
163 * @param string $name Image name
164 * @return ResourceLoaderImage|null
165 */
166 public function getImage( $name ) {
167 $images = $this->getImages();
168 return isset( $images[$name] ) ? $images[$name] : null;
169 }
170
171 /**
172 * Get ResourceLoaderImage objects for all images.
173 * @return ResourceLoaderImage[] Array keyed by image name
174 */
175 public function getImages() {
176 if ( !isset( $this->imageObjects ) ) {
177 $this->imageObjects = array();
178
179 foreach ( $this->images as $name => $options ) {
180 $fileDescriptor = is_string( $options ) ? $options : $options['file'];
181
182 $allowedVariants = array_merge(
183 is_array( $options ) && isset( $options['variants'] ) ? $options['variants'] : array(),
184 $this->getGlobalVariants()
185 );
186 if ( isset( $this->variants ) ) {
187 $variantConfig = array_intersect_key(
188 $this->variants,
189 array_fill_keys( $allowedVariants, true )
190 );
191 } else {
192 $variantConfig = array();
193 }
194
195 $image = new ResourceLoaderImage(
196 $name,
197 $this->getName(),
198 $fileDescriptor,
199 $this->localBasePath,
200 $variantConfig
201 );
202 $this->imageObjects[ $image->getName() ] = $image;
203 }
204 }
205
206 return $this->imageObjects;
207 }
208
209 /**
210 * Get list of variants in this module that are 'global', i.e., available
211 * for every image regardless of image options.
212 * @return string[]
213 */
214 public function getGlobalVariants() {
215 if ( !isset( $this->globalVariants ) ) {
216 $this->globalVariants = array();
217
218 if ( isset( $this->variants ) ) {
219 foreach ( $this->variants as $name => $config ) {
220 if ( isset( $config['global'] ) && $config['global'] ) {
221 $this->globalVariants[] = $name;
222 }
223 }
224 }
225 }
226
227 return $this->globalVariants;
228 }
229
230 /**
231 * @param ResourceLoaderContext $context
232 * @return array
233 */
234 public function getStyles( ResourceLoaderContext $context ) {
235 // Build CSS rules
236 $rules = array();
237 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
238 $selectors = $this->getSelectors();
239
240 foreach ( $this->getImages() as $name => $image ) {
241 $declarations = $this->getCssDeclarations(
242 $image->getDataUri( $context, null, 'original' ),
243 $image->getUrl( $context, $script, null, 'rasterized' )
244 );
245 $declarations = implode( "\n\t", $declarations );
246 $selector = strtr(
247 $selectors['selectorWithoutVariant'],
248 array(
249 '{prefix}' => $this->getPrefix(),
250 '{name}' => $name,
251 '{variant}' => '',
252 )
253 );
254 $rules[] = "$selector {\n\t$declarations\n}";
255
256 // TODO: Get variant configurations from $context->getSkin()
257 foreach ( $image->getVariants() as $variant ) {
258 $declarations = $this->getCssDeclarations(
259 $image->getDataUri( $context, $variant, 'original' ),
260 $image->getUrl( $context, $script, $variant, 'rasterized' )
261 );
262 $declarations = implode( "\n\t", $declarations );
263 $selector = strtr(
264 $selectors['selectorWithVariant'],
265 array(
266 '{prefix}' => $this->getPrefix(),
267 '{name}' => $name,
268 '{variant}' => $variant,
269 )
270 );
271 $rules[] = "$selector {\n\t$declarations\n}";
272 }
273 }
274
275 $style = implode( "\n", $rules );
276 if ( $this->getFlip( $context ) ) {
277 $style = CSSJanus::transform( $style, true, false );
278 }
279 return array( 'all' => $style );
280 }
281
282 /**
283 * SVG support using a transparent gradient to guarantee cross-browser
284 * compatibility (browsers able to understand gradient syntax support also SVG).
285 * http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
286 *
287 * Keep synchronized with the .background-image-svg LESS mixin in
288 * /resources/src/mediawiki.less/mediawiki.mixins.less.
289 *
290 * @param string $primary Primary URI
291 * @param string $fallback Fallback URI
292 * @return string[] CSS declarations to use given URIs as background-image
293 */
294 protected function getCssDeclarations( $primary, $fallback ) {
295 return array(
296 "background-image: url($fallback);",
297 "background-image: -webkit-linear-gradient(transparent, transparent), url($primary);",
298 "background-image: linear-gradient(transparent, transparent), url($primary);",
299 "background-image: -o-linear-gradient(transparent, transparent), url($fallback);",
300 );
301 }
302
303 /**
304 * @return bool
305 */
306 public function supportsURLLoading() {
307 return false;
308 }
309
310 /**
311 * Extract a local base path from module definition information.
312 *
313 * @param array $options Module definition
314 * @param string $localBasePath Path to use if not provided in module definition. Defaults
315 * to $IP
316 * @return string Local base path
317 */
318 public static function extractLocalBasePath( $options, $localBasePath = null ) {
319 global $IP;
320
321 if ( $localBasePath === null ) {
322 $localBasePath = $IP;
323 }
324
325 if ( array_key_exists( 'localBasePath', $options ) ) {
326 $localBasePath = (string)$options['localBasePath'];
327 }
328
329 return $localBasePath;
330 }
331 }