Merge "Register a default value for the timecorrection preference"
[lhc/web/wiklou.git] / includes / libs / objectcache / BagOStuff.php
1 <?php
2 /**
3 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
4 * https://www.mediawiki.org/
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Cache
23 */
24
25 /**
26 * @defgroup Cache Cache
27 */
28
29 use Psr\Log\LoggerAwareInterface;
30 use Psr\Log\LoggerInterface;
31 use Psr\Log\NullLogger;
32
33 /**
34 * interface is intended to be more or less compatible with
35 * the PHP memcached client.
36 *
37 * backends for local hash array and SQL table included:
38 * @code
39 * $bag = new HashBagOStuff();
40 * $bag = new SqlBagOStuff(); # connect to db first
41 * @endcode
42 *
43 * @ingroup Cache
44 */
45 abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
46 /** @var array[] Lock tracking */
47 protected $locks = [];
48
49 /** @var integer ERR_* class constant */
50 protected $lastError = self::ERR_NONE;
51
52 /** @var string */
53 protected $keyspace = 'local';
54
55 /** @var LoggerInterface */
56 protected $logger;
57
58 /** @var callback|null */
59 protected $asyncHandler;
60
61 /** @var bool */
62 private $debugMode = false;
63
64 /** @var array */
65 private $duplicateKeyLookups = [];
66
67 /** @var bool */
68 private $reportDupes = false;
69
70 /** @var bool */
71 private $dupeTrackScheduled = false;
72
73 /** @var integer[] Map of (ATTR_* class constant => QOS_* class constant) */
74 protected $attrMap = [];
75
76 /** Possible values for getLastError() */
77 const ERR_NONE = 0; // no error
78 const ERR_NO_RESPONSE = 1; // no response
79 const ERR_UNREACHABLE = 2; // can't connect
80 const ERR_UNEXPECTED = 3; // response gave some error
81
82 /** Bitfield constants for get()/getMulti() */
83 const READ_LATEST = 1; // use latest data for replicated stores
84 const READ_VERIFIED = 2; // promise that caller can tell when keys are stale
85 /** Bitfield constants for set()/merge() */
86 const WRITE_SYNC = 1; // synchronously write to all locations for replicated stores
87 const WRITE_CACHE_ONLY = 2; // Only change state of the in-memory cache
88
89 /**
90 * $params include:
91 * - logger: Psr\Log\LoggerInterface instance
92 * - keyspace: Default keyspace for $this->makeKey()
93 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
94 * In CLI mode, it should run the task immediately.
95 * - reportDupes: Whether to emit warning log messages for all keys that were
96 * requested more than once (requires an asyncHandler).
97 * @param array $params
98 */
99 public function __construct( array $params = [] ) {
100 if ( isset( $params['logger'] ) ) {
101 $this->setLogger( $params['logger'] );
102 } else {
103 $this->setLogger( new NullLogger() );
104 }
105
106 if ( isset( $params['keyspace'] ) ) {
107 $this->keyspace = $params['keyspace'];
108 }
109
110 $this->asyncHandler = isset( $params['asyncHandler'] )
111 ? $params['asyncHandler']
112 : null;
113
114 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
115 $this->reportDupes = true;
116 }
117 }
118
119 /**
120 * @param LoggerInterface $logger
121 * @return null
122 */
123 public function setLogger( LoggerInterface $logger ) {
124 $this->logger = $logger;
125 }
126
127 /**
128 * @param bool $bool
129 */
130 public function setDebug( $bool ) {
131 $this->debugMode = $bool;
132 }
133
134 /**
135 * Get an item with the given key, regenerating and setting it if not found
136 *
137 * If the callback returns false, then nothing is stored.
138 *
139 * @param string $key
140 * @param int $ttl Time-to-live (seconds)
141 * @param callable $callback Callback that derives the new value
142 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
143 * @return mixed The cached value if found or the result of $callback otherwise
144 * @since 1.27
145 */
146 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
147 $value = $this->get( $key, $flags );
148
149 if ( $value === false ) {
150 if ( !is_callable( $callback ) ) {
151 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
152 }
153 $value = call_user_func( $callback );
154 if ( $value !== false ) {
155 $this->set( $key, $value, $ttl );
156 }
157 }
158
159 return $value;
160 }
161
162 /**
163 * Get an item with the given key
164 *
165 * If the key includes a determistic input hash (e.g. the key can only have
166 * the correct value) or complete staleness checks are handled by the caller
167 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
168 * This lets tiered backends know they can safely upgrade a cached value to
169 * higher tiers using standard TTLs.
170 *
171 * @param string $key
172 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
173 * @param integer $oldFlags [unused]
174 * @return mixed Returns false on failure and if the item does not exist
175 */
176 public function get( $key, $flags = 0, $oldFlags = null ) {
177 // B/C for ( $key, &$casToken = null, $flags = 0 )
178 $flags = is_int( $oldFlags ) ? $oldFlags : $flags;
179
180 $this->trackDuplicateKeys( $key );
181
182 return $this->doGet( $key, $flags );
183 }
184
185 /**
186 * Track the number of times that a given key has been used.
187 * @param string $key
188 */
189 private function trackDuplicateKeys( $key ) {
190 if ( !$this->reportDupes ) {
191 return;
192 }
193
194 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
195 // Track that we have seen this key. This N-1 counting style allows
196 // easy filtering with array_filter() later.
197 $this->duplicateKeyLookups[$key] = 0;
198 } else {
199 $this->duplicateKeyLookups[$key] += 1;
200
201 if ( $this->dupeTrackScheduled === false ) {
202 $this->dupeTrackScheduled = true;
203 // Schedule a callback that logs keys processed more than once by get().
204 call_user_func( $this->asyncHandler, function () {
205 $dups = array_filter( $this->duplicateKeyLookups );
206 foreach ( $dups as $key => $count ) {
207 $this->logger->warning(
208 'Duplicate get(): "{key}" fetched {count} times',
209 // Count is N-1 of the actual lookup count
210 [ 'key' => $key, 'count' => $count + 1, ]
211 );
212 }
213 } );
214 }
215 }
216 }
217
218 /**
219 * @param string $key
220 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
221 * @return mixed Returns false on failure and if the item does not exist
222 */
223 abstract protected function doGet( $key, $flags = 0 );
224
225 /**
226 * @note: This method is only needed if merge() uses mergeViaCas()
227 *
228 * @param string $key
229 * @param mixed $casToken
230 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
231 * @return mixed Returns false on failure and if the item does not exist
232 * @throws Exception
233 */
234 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
235 throw new Exception( __METHOD__ . ' not implemented.' );
236 }
237
238 /**
239 * Set an item
240 *
241 * @param string $key
242 * @param mixed $value
243 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
244 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
245 * @return bool Success
246 */
247 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
248
249 /**
250 * Delete an item
251 *
252 * @param string $key
253 * @return bool True if the item was deleted or not found, false on failure
254 */
255 abstract public function delete( $key );
256
257 /**
258 * Merge changes into the existing cache value (possibly creating a new one)
259 *
260 * The callback function returns the new value given the current value
261 * (which will be false if not present), and takes the arguments:
262 * (this BagOStuff, cache key, current value, TTL).
263 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
264 *
265 * @param string $key
266 * @param callable $callback Callback method to be executed
267 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
268 * @param int $attempts The amount of times to attempt a merge in case of failure
269 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
270 * @return bool Success
271 * @throws InvalidArgumentException
272 */
273 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
274 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
275 }
276
277 /**
278 * @see BagOStuff::merge()
279 *
280 * @param string $key
281 * @param callable $callback Callback method to be executed
282 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
283 * @param int $attempts The amount of times to attempt a merge in case of failure
284 * @return bool Success
285 */
286 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
287 do {
288 $this->clearLastError();
289 $reportDupes = $this->reportDupes;
290 $this->reportDupes = false;
291 $casToken = null; // passed by reference
292 $currentValue = $this->getWithToken( $key, $casToken, self::READ_LATEST );
293 $this->reportDupes = $reportDupes;
294
295 if ( $this->getLastError() ) {
296 return false; // don't spam retries (retry only on races)
297 }
298
299 // Derive the new value from the old value
300 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
301
302 $this->clearLastError();
303 if ( $value === false ) {
304 $success = true; // do nothing
305 } elseif ( $currentValue === false ) {
306 // Try to create the key, failing if it gets created in the meantime
307 $success = $this->add( $key, $value, $exptime );
308 } else {
309 // Try to update the key, failing if it gets changed in the meantime
310 $success = $this->cas( $casToken, $key, $value, $exptime );
311 }
312 if ( $this->getLastError() ) {
313 return false; // IO error; don't spam retries
314 }
315 } while ( !$success && --$attempts );
316
317 return $success;
318 }
319
320 /**
321 * Check and set an item
322 *
323 * @param mixed $casToken
324 * @param string $key
325 * @param mixed $value
326 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
327 * @return bool Success
328 * @throws Exception
329 */
330 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
331 throw new Exception( "CAS is not implemented in " . __CLASS__ );
332 }
333
334 /**
335 * @see BagOStuff::merge()
336 *
337 * @param string $key
338 * @param callable $callback Callback method to be executed
339 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
340 * @param int $attempts The amount of times to attempt a merge in case of failure
341 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
342 * @return bool Success
343 */
344 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
345 if ( !$this->lock( $key, 6 ) ) {
346 return false;
347 }
348
349 $this->clearLastError();
350 $reportDupes = $this->reportDupes;
351 $this->reportDupes = false;
352 $currentValue = $this->get( $key, self::READ_LATEST );
353 $this->reportDupes = $reportDupes;
354
355 if ( $this->getLastError() ) {
356 $success = false;
357 } else {
358 // Derive the new value from the old value
359 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
360 if ( $value === false ) {
361 $success = true; // do nothing
362 } else {
363 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
364 }
365 }
366
367 if ( !$this->unlock( $key ) ) {
368 // this should never happen
369 trigger_error( "Could not release lock for key '$key'." );
370 }
371
372 return $success;
373 }
374
375 /**
376 * Reset the TTL on a key if it exists
377 *
378 * @param string $key
379 * @param int $expiry
380 * @return bool Success Returns false if there is no key
381 * @since 1.28
382 */
383 public function changeTTL( $key, $expiry = 0 ) {
384 $value = $this->get( $key );
385
386 return ( $value === false ) ? false : $this->set( $key, $value, $expiry );
387 }
388
389 /**
390 * Acquire an advisory lock on a key string
391 *
392 * Note that if reentry is enabled, duplicate calls ignore $expiry
393 *
394 * @param string $key
395 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
396 * @param int $expiry Lock expiry [optional]; 1 day maximum
397 * @param string $rclass Allow reentry if set and the current lock used this value
398 * @return bool Success
399 */
400 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
401 // Avoid deadlocks and allow lock reentry if specified
402 if ( isset( $this->locks[$key] ) ) {
403 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
404 ++$this->locks[$key]['depth'];
405 return true;
406 } else {
407 return false;
408 }
409 }
410
411 $expiry = min( $expiry ?: INF, self::TTL_DAY );
412
413 $this->clearLastError();
414 $timestamp = microtime( true ); // starting UNIX timestamp
415 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
416 $locked = true;
417 } elseif ( $this->getLastError() || $timeout <= 0 ) {
418 $locked = false; // network partition or non-blocking
419 } else {
420 // Estimate the RTT (us); use 1ms minimum for sanity
421 $uRTT = max( 1e3, ceil( 1e6 * ( microtime( true ) - $timestamp ) ) );
422 $sleep = 2 * $uRTT; // rough time to do get()+set()
423
424 $attempts = 0; // failed attempts
425 do {
426 if ( ++$attempts >= 3 && $sleep <= 5e5 ) {
427 // Exponentially back off after failed attempts to avoid network spam.
428 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
429 $sleep *= 2;
430 }
431 usleep( $sleep ); // back off
432 $this->clearLastError();
433 $locked = $this->add( "{$key}:lock", 1, $expiry );
434 if ( $this->getLastError() ) {
435 $locked = false; // network partition
436 break;
437 }
438 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
439 }
440
441 if ( $locked ) {
442 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
443 }
444
445 return $locked;
446 }
447
448 /**
449 * Release an advisory lock on a key string
450 *
451 * @param string $key
452 * @return bool Success
453 */
454 public function unlock( $key ) {
455 if ( isset( $this->locks[$key] ) && --$this->locks[$key]['depth'] <= 0 ) {
456 unset( $this->locks[$key] );
457
458 return $this->delete( "{$key}:lock" );
459 }
460
461 return true;
462 }
463
464 /**
465 * Get a lightweight exclusive self-unlocking lock
466 *
467 * Note that the same lock cannot be acquired twice.
468 *
469 * This is useful for task de-duplication or to avoid obtrusive
470 * (though non-corrupting) DB errors like INSERT key conflicts
471 * or deadlocks when using LOCK IN SHARE MODE.
472 *
473 * @param string $key
474 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
475 * @param int $expiry Lock expiry [optional]; 1 day maximum
476 * @param string $rclass Allow reentry if set and the current lock used this value
477 * @return ScopedCallback|null Returns null on failure
478 * @since 1.26
479 */
480 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
481 $expiry = min( $expiry ?: INF, self::TTL_DAY );
482
483 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
484 return null;
485 }
486
487 $lSince = microtime( true ); // lock timestamp
488
489 return new ScopedCallback( function() use ( $key, $lSince, $expiry ) {
490 $latency = .050; // latency skew (err towards keeping lock present)
491 $age = ( microtime( true ) - $lSince + $latency );
492 if ( ( $age + $latency ) >= $expiry ) {
493 $this->logger->warning( "Lock for $key held too long ($age sec)." );
494 return; // expired; it's not "safe" to delete the key
495 }
496 $this->unlock( $key );
497 } );
498 }
499
500 /**
501 * Delete all objects expiring before a certain date.
502 * @param string $date The reference date in MW format
503 * @param callable|bool $progressCallback Optional, a function which will be called
504 * regularly during long-running operations with the percentage progress
505 * as the first parameter.
506 *
507 * @return bool Success, false if unimplemented
508 */
509 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
510 // stub
511 return false;
512 }
513
514 /**
515 * Get an associative array containing the item for each of the keys that have items.
516 * @param array $keys List of strings
517 * @param integer $flags Bitfield; supports READ_LATEST [optional]
518 * @return array
519 */
520 public function getMulti( array $keys, $flags = 0 ) {
521 $res = [];
522 foreach ( $keys as $key ) {
523 $val = $this->get( $key );
524 if ( $val !== false ) {
525 $res[$key] = $val;
526 }
527 }
528 return $res;
529 }
530
531 /**
532 * Batch insertion
533 * @param array $data $key => $value assoc array
534 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
535 * @return bool Success
536 * @since 1.24
537 */
538 public function setMulti( array $data, $exptime = 0 ) {
539 $res = true;
540 foreach ( $data as $key => $value ) {
541 if ( !$this->set( $key, $value, $exptime ) ) {
542 $res = false;
543 }
544 }
545 return $res;
546 }
547
548 /**
549 * @param string $key
550 * @param mixed $value
551 * @param int $exptime
552 * @return bool Success
553 */
554 public function add( $key, $value, $exptime = 0 ) {
555 if ( $this->get( $key ) === false ) {
556 return $this->set( $key, $value, $exptime );
557 }
558 return false; // key already set
559 }
560
561 /**
562 * Increase stored value of $key by $value while preserving its TTL
563 * @param string $key Key to increase
564 * @param int $value Value to add to $key (Default 1)
565 * @return int|bool New value or false on failure
566 */
567 public function incr( $key, $value = 1 ) {
568 if ( !$this->lock( $key ) ) {
569 return false;
570 }
571 $n = $this->get( $key );
572 if ( $this->isInteger( $n ) ) { // key exists?
573 $n += intval( $value );
574 $this->set( $key, max( 0, $n ) ); // exptime?
575 } else {
576 $n = false;
577 }
578 $this->unlock( $key );
579
580 return $n;
581 }
582
583 /**
584 * Decrease stored value of $key by $value while preserving its TTL
585 * @param string $key
586 * @param int $value
587 * @return int|bool New value or false on failure
588 */
589 public function decr( $key, $value = 1 ) {
590 return $this->incr( $key, - $value );
591 }
592
593 /**
594 * Increase stored value of $key by $value while preserving its TTL
595 *
596 * This will create the key with value $init and TTL $ttl instead if not present
597 *
598 * @param string $key
599 * @param int $ttl
600 * @param int $value
601 * @param int $init
602 * @return int|bool New value or false on failure
603 * @since 1.24
604 */
605 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
606 $newValue = $this->incr( $key, $value );
607 if ( $newValue === false ) {
608 // No key set; initialize
609 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
610 }
611 if ( $newValue === false ) {
612 // Raced out initializing; increment
613 $newValue = $this->incr( $key, $value );
614 }
615
616 return $newValue;
617 }
618
619 /**
620 * Get the "last error" registered; clearLastError() should be called manually
621 * @return int ERR_* constant for the "last error" registry
622 * @since 1.23
623 */
624 public function getLastError() {
625 return $this->lastError;
626 }
627
628 /**
629 * Clear the "last error" registry
630 * @since 1.23
631 */
632 public function clearLastError() {
633 $this->lastError = self::ERR_NONE;
634 }
635
636 /**
637 * Set the "last error" registry
638 * @param int $err ERR_* constant
639 * @since 1.23
640 */
641 protected function setLastError( $err ) {
642 $this->lastError = $err;
643 }
644
645 /**
646 * Modify a cache update operation array for EventRelayer::notify()
647 *
648 * This is used for relayed writes, e.g. for broadcasting a change
649 * to multiple data-centers. If the array contains a 'val' field
650 * then the command involves setting a key to that value. Note that
651 * for simplicity, 'val' is always a simple scalar value. This method
652 * is used to possibly serialize the value and add any cache-specific
653 * key/values needed for the relayer daemon (e.g. memcached flags).
654 *
655 * @param array $event
656 * @return array
657 * @since 1.26
658 */
659 public function modifySimpleRelayEvent( array $event ) {
660 return $event;
661 }
662
663 /**
664 * @param string $text
665 */
666 protected function debug( $text ) {
667 if ( $this->debugMode ) {
668 $this->logger->debug( "{class} debug: $text", [
669 'class' => get_class( $this ),
670 ] );
671 }
672 }
673
674 /**
675 * Convert an optionally relative time to an absolute time
676 * @param int $exptime
677 * @return int
678 */
679 protected function convertExpiry( $exptime ) {
680 if ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) ) {
681 return time() + $exptime;
682 } else {
683 return $exptime;
684 }
685 }
686
687 /**
688 * Convert an optionally absolute expiry time to a relative time. If an
689 * absolute time is specified which is in the past, use a short expiry time.
690 *
691 * @param int $exptime
692 * @return int
693 */
694 protected function convertToRelative( $exptime ) {
695 if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
696 $exptime -= time();
697 if ( $exptime <= 0 ) {
698 $exptime = 1;
699 }
700 return $exptime;
701 } else {
702 return $exptime;
703 }
704 }
705
706 /**
707 * Check if a value is an integer
708 *
709 * @param mixed $value
710 * @return bool
711 */
712 protected function isInteger( $value ) {
713 return ( is_int( $value ) || ctype_digit( $value ) );
714 }
715
716 /**
717 * Construct a cache key.
718 *
719 * @since 1.27
720 * @param string $keyspace
721 * @param array $args
722 * @return string
723 */
724 public function makeKeyInternal( $keyspace, $args ) {
725 $key = $keyspace;
726 foreach ( $args as $arg ) {
727 $arg = str_replace( ':', '%3A', $arg );
728 $key = $key . ':' . $arg;
729 }
730 return strtr( $key, ' ', '_' );
731 }
732
733 /**
734 * Make a global cache key.
735 *
736 * @since 1.27
737 * @param string ... Key component (variadic)
738 * @return string
739 */
740 public function makeGlobalKey() {
741 return $this->makeKeyInternal( 'global', func_get_args() );
742 }
743
744 /**
745 * Make a cache key, scoped to this instance's keyspace.
746 *
747 * @since 1.27
748 * @param string ... Key component (variadic)
749 * @return string
750 */
751 public function makeKey() {
752 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
753 }
754
755 /**
756 * @param integer $flag ATTR_* class constant
757 * @return integer QOS_* class constant
758 * @since 1.28
759 */
760 public function getQoS( $flag ) {
761 return isset( $this->attrMap[$flag] ) ? $this->attrMap[$flag] : self::QOS_UNKNOWN;
762 }
763
764 /**
765 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
766 *
767 * @param BagOStuff[] $bags
768 * @return integer[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
769 */
770 protected function mergeFlagMaps( array $bags ) {
771 $map = [];
772 foreach ( $bags as $bag ) {
773 foreach ( $bag->attrMap as $attr => $rank ) {
774 if ( isset( $map[$attr] ) ) {
775 $map[$attr] = min( $map[$attr], $rank );
776 } else {
777 $map[$attr] = $rank;
778 }
779 }
780 }
781
782 return $map;
783 }
784 }