3 * This file deals with UID generation.
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.
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.
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
22 use Wikimedia\Assert\Assert
;
23 use MediaWiki\MediaWikiServices
;
26 * Class for getting statistically unique IDs
31 /** @var UIDGenerator */
32 protected static $instance = null;
34 protected $nodeIdFile; // string; local file path
35 protected $nodeId32; // string; node ID in binary (32 bits)
36 protected $nodeId48; // string; node ID in binary (48 bits)
38 protected $lockFile88; // string; local file path
39 protected $lockFile128; // string; local file path
40 protected $lockFileUUID; // string; local file path
43 protected $fileHandles = []; // cache file handles
45 const QUICK_RAND
= 1; // get randomness from fast and insecure sources
46 const QUICK_VOLATILE
= 2; // use an APC like in-memory counter if available
48 protected function __construct() {
49 $this->nodeIdFile
= wfTempDir() . '/mw-' . __CLASS__
. '-UID-nodeid';
51 if ( is_file( $this->nodeIdFile
) ) {
52 $nodeId = file_get_contents( $this->nodeIdFile
);
54 // Try to get some ID that uniquely identifies this machine (RFC 4122)...
55 if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
56 Wikimedia\
suppressWarnings();
57 if ( wfIsWindows() ) {
58 // https://technet.microsoft.com/en-us/library/bb490913.aspx
59 $csv = trim( wfShellExec( 'getmac /NH /FO CSV' ) );
60 $line = substr( $csv, 0, strcspn( $csv, "\n" ) );
61 $info = str_getcsv( $line );
62 $nodeId = isset( $info[0] ) ?
str_replace( '-', '', $info[0] ) : '';
63 } elseif ( is_executable( '/sbin/ifconfig' ) ) { // Linux/BSD/Solaris/OS X
64 // See https://linux.die.net/man/8/ifconfig
66 preg_match( '/\s([0-9a-f]{2}(:[0-9a-f]{2}){5})\s/',
67 wfShellExec( '/sbin/ifconfig -a' ), $m );
68 $nodeId = isset( $m[1] ) ?
str_replace( ':', '', $m[1] ) : '';
70 Wikimedia\restoreWarnings
();
71 if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
72 $nodeId = MWCryptRand
::generateHex( 12, true );
73 $nodeId[1] = dechex( hexdec( $nodeId[1] ) |
0x1 ); // set multicast bit
75 file_put_contents( $this->nodeIdFile
, $nodeId ); // cache
77 $this->nodeId32
= Wikimedia\base_convert
( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
78 $this->nodeId48
= Wikimedia\base_convert
( $nodeId, 16, 2, 48 );
79 // If different processes run as different users, they may have different temp dirs.
80 // This is dealt with by initializing the clock sequence number and counters randomly.
81 $this->lockFile88
= wfTempDir() . '/mw-' . __CLASS__
. '-UID-88';
82 $this->lockFile128
= wfTempDir() . '/mw-' . __CLASS__
. '-UID-128';
83 $this->lockFileUUID
= wfTempDir() . '/mw-' . __CLASS__
. '-UUID-128';
87 * @todo move to MW-specific factory class and inject temp dir
88 * @return UIDGenerator
90 protected static function singleton() {
91 if ( self
::$instance === null ) {
92 self
::$instance = new self();
95 return self
::$instance;
99 * Get a statistically unique 88-bit unsigned integer ID string.
100 * The bits of the UID are prefixed with the time (down to the millisecond).
102 * These IDs are suitable as values for the shard key of distributed data.
103 * If a column uses these as values, it should be declared UNIQUE to handle collisions.
104 * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast.
105 * They can also be stored "DECIMAL(27) UNSIGNED" or BINARY(11) in MySQL.
107 * UID generation is serialized on each server (as the node ID is for the whole machine).
109 * @param int $base Specifies a base other than 10
110 * @return string Number
111 * @throws RuntimeException
113 public static function newTimestampedUID88( $base = 10 ) {
114 Assert
::parameterType( 'integer', $base, '$base' );
115 Assert
::parameter( $base <= 36, '$base', 'must be <= 36' );
116 Assert
::parameter( $base >= 2, '$base', 'must be >= 2' );
118 $gen = self
::singleton();
119 $info = $gen->getTimeAndDelay( 'lockFile88', 1, 1024, 1024 );
120 $info['offsetCounter'] = $info['offsetCounter'] %
1024;
121 return Wikimedia\base_convert
( $gen->getTimestampedID88( $info ), 2, $base );
125 * @param array $info result of UIDGenerator::getTimeAndDelay(), or
126 * for sub classes, a seqencial array like (time, offsetCounter).
127 * @return string 88 bits
128 * @throws RuntimeException
130 protected function getTimestampedID88( array $info ) {
131 if ( isset( $info['time'] ) ) {
132 $time = $info['time'];
133 $counter = $info['offsetCounter'];
138 // Take the 46 LSBs of "milliseconds since epoch"
139 $id_bin = $this->millisecondsSinceEpochBinary( $time );
140 // Add a 10 bit counter resulting in 56 bits total
141 $id_bin .= str_pad( decbin( $counter ), 10, '0', STR_PAD_LEFT
);
142 // Add the 32 bit node ID resulting in 88 bits total
143 $id_bin .= $this->nodeId32
;
144 // Convert to a 1-27 digit integer string
145 if ( strlen( $id_bin ) !== 88 ) {
146 throw new RuntimeException( "Detected overflow for millisecond timestamp." );
153 * Get a statistically unique 128-bit unsigned integer ID string.
154 * The bits of the UID are prefixed with the time (down to the millisecond).
156 * These IDs are suitable as globally unique IDs, without any enforced uniqueness.
157 * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast.
158 * They can also be stored as "DECIMAL(39) UNSIGNED" or BINARY(16) in MySQL.
160 * UID generation is serialized on each server (as the node ID is for the whole machine).
162 * @param int $base Specifies a base other than 10
163 * @return string Number
164 * @throws RuntimeException
166 public static function newTimestampedUID128( $base = 10 ) {
167 Assert
::parameterType( 'integer', $base, '$base' );
168 Assert
::parameter( $base <= 36, '$base', 'must be <= 36' );
169 Assert
::parameter( $base >= 2, '$base', 'must be >= 2' );
171 $gen = self
::singleton();
172 $info = $gen->getTimeAndDelay( 'lockFile128', 16384, 1048576, 1048576 );
173 $info['offsetCounter'] = $info['offsetCounter'] %
1048576;
175 return Wikimedia\base_convert
( $gen->getTimestampedID128( $info ), 2, $base );
179 * @param array $info The result of UIDGenerator::getTimeAndDelay(),
180 * for sub classes, a seqencial array like (time, offsetCounter, clkSeq).
181 * @return string 128 bits
182 * @throws RuntimeException
184 protected function getTimestampedID128( array $info ) {
185 if ( isset( $info['time'] ) ) {
186 $time = $info['time'];
187 $counter = $info['offsetCounter'];
188 $clkSeq = $info['clkSeq'];
194 // Take the 46 LSBs of "milliseconds since epoch"
195 $id_bin = $this->millisecondsSinceEpochBinary( $time );
196 // Add a 20 bit counter resulting in 66 bits total
197 $id_bin .= str_pad( decbin( $counter ), 20, '0', STR_PAD_LEFT
);
198 // Add a 14 bit clock sequence number resulting in 80 bits total
199 $id_bin .= str_pad( decbin( $clkSeq ), 14, '0', STR_PAD_LEFT
);
200 // Add the 48 bit node ID resulting in 128 bits total
201 $id_bin .= $this->nodeId48
;
202 // Convert to a 1-39 digit integer string
203 if ( strlen( $id_bin ) !== 128 ) {
204 throw new RuntimeException( "Detected overflow for millisecond timestamp." );
211 * Return an RFC4122 compliant v1 UUID
214 * @throws RuntimeException
217 public static function newUUIDv1() {
218 $gen = self
::singleton();
219 // There can be up to 10000 intervals for the same millisecond timestamp.
220 // [0,4999] counter + [0,5000] offset is in [0,9999] for the offset counter.
221 // Add this onto the timestamp to allow making up to 5000 IDs per second.
222 return $gen->getUUIDv1( $gen->getTimeAndDelay( 'lockFileUUID', 16384, 5000, 5001 ) );
226 * Return an RFC4122 compliant v1 UUID
228 * @return string 32 hex characters with no hyphens
229 * @throws RuntimeException
232 public static function newRawUUIDv1() {
233 return str_replace( '-', '', self
::newUUIDv1() );
237 * @param array $info Result of UIDGenerator::getTimeAndDelay()
238 * @return string 128 bits
240 protected function getUUIDv1( array $info ) {
241 $clkSeq_bin = Wikimedia\base_convert
( $info['clkSeq'], 10, 2, 14 );
242 $time_bin = $this->intervalsSinceGregorianBinary( $info['time'], $info['offsetCounter'] );
243 // Take the 32 bits of "time low"
244 $id_bin = substr( $time_bin, 28, 32 );
245 // Add 16 bits of "time mid" resulting in 48 bits total
246 $id_bin .= substr( $time_bin, 12, 16 );
247 // Add 4 bit version resulting in 52 bits total
249 // Add 12 bits of "time high" resulting in 64 bits total
250 $id_bin .= substr( $time_bin, 0, 12 );
251 // Add 2 bits of "variant" resulting in 66 bits total
253 // Add 6 bits of "clock seq high" resulting in 72 bits total
254 $id_bin .= substr( $clkSeq_bin, 0, 6 );
255 // Add 8 bits of "clock seq low" resulting in 80 bits total
256 $id_bin .= substr( $clkSeq_bin, 6, 8 );
257 // Add the 48 bit node ID resulting in 128 bits total
258 $id_bin .= $this->nodeId48
;
259 // Convert to a 32 char hex string with dashes
260 if ( strlen( $id_bin ) !== 128 ) {
261 throw new RuntimeException( "Detected overflow for millisecond timestamp." );
263 $hex = Wikimedia\base_convert
( $id_bin, 2, 16, 32 );
264 return sprintf( '%s-%s-%s-%s-%s',
265 // "time_low" (32 bits)
266 substr( $hex, 0, 8 ),
267 // "time_mid" (16 bits)
268 substr( $hex, 8, 4 ),
269 // "time_hi_and_version" (16 bits)
270 substr( $hex, 12, 4 ),
271 // "clk_seq_hi_res" (8 bits) and "clk_seq_low" (8 bits)
272 substr( $hex, 16, 4 ),
274 substr( $hex, 20, 12 )
279 * Return an RFC4122 compliant v4 UUID
281 * @param int $flags Bitfield (supports UIDGenerator::QUICK_RAND)
283 * @throws RuntimeException
285 public static function newUUIDv4( $flags = 0 ) {
286 $hex = ( $flags & self
::QUICK_RAND
)
287 ?
wfRandomString( 31 )
288 : MWCryptRand
::generateHex( 31 );
290 return sprintf( '%s-%s-%s-%s-%s',
291 // "time_low" (32 bits)
292 substr( $hex, 0, 8 ),
293 // "time_mid" (16 bits)
294 substr( $hex, 8, 4 ),
295 // "time_hi_and_version" (16 bits)
296 '4' . substr( $hex, 12, 3 ),
297 // "clk_seq_hi_res" (8 bits, variant is binary 10x) and "clk_seq_low" (8 bits)
298 dechex( 0x8 |
( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
300 substr( $hex, 19, 12 )
305 * Return an RFC4122 compliant v4 UUID
307 * @param int $flags Bitfield (supports UIDGenerator::QUICK_RAND)
308 * @return string 32 hex characters with no hyphens
309 * @throws RuntimeException
311 public static function newRawUUIDv4( $flags = 0 ) {
312 return str_replace( '-', '', self
::newUUIDv4( $flags ) );
316 * Return an ID that is sequential *only* for this node and bucket
318 * These IDs are suitable for per-host sequence numbers, e.g. for some packet protocols.
319 * If UIDGenerator::QUICK_VOLATILE is used the counter might reset on server restart.
321 * @param string $bucket Arbitrary bucket name (should be ASCII)
322 * @param int $bits Bit size (<=48) of resulting numbers before wrap-around
323 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
324 * @return float Integer value as float
327 public static function newSequentialPerNodeID( $bucket, $bits = 48, $flags = 0 ) {
328 return current( self
::newSequentialPerNodeIDs( $bucket, $bits, 1, $flags ) );
332 * Return IDs that are sequential *only* for this node and bucket
334 * @see UIDGenerator::newSequentialPerNodeID()
335 * @param string $bucket Arbitrary bucket name (should be ASCII)
336 * @param int $bits Bit size (16 to 48) of resulting numbers before wrap-around
337 * @param int $count Number of IDs to return
338 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
339 * @return array Ordered list of float integer values
342 public static function newSequentialPerNodeIDs( $bucket, $bits, $count, $flags = 0 ) {
343 $gen = self
::singleton();
344 return $gen->getSequentialPerNodeIDs( $bucket, $bits, $count, $flags );
348 * Return IDs that are sequential *only* for this node and bucket
350 * @see UIDGenerator::newSequentialPerNodeID()
351 * @param string $bucket Arbitrary bucket name (should be ASCII)
352 * @param int $bits Bit size (16 to 48) of resulting numbers before wrap-around
353 * @param int $count Number of IDs to return
354 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
355 * @return array Ordered list of float integer values
356 * @throws RuntimeException
358 protected function getSequentialPerNodeIDs( $bucket, $bits, $count, $flags ) {
360 return []; // nothing to do
362 if ( $bits < 16 ||
$bits > 48 ) {
363 throw new RuntimeException( "Requested bit size ($bits) is out of range." );
366 $counter = null; // post-increment persistent counter value
368 // Use APC/etc if requested, available, and not in CLI mode;
369 // Counter values would not survive across script instances in CLI mode.
371 if ( ( $flags & self
::QUICK_VOLATILE
) && !wfIsCLI() ) {
372 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
375 $counter = $cache->incrWithInit( $bucket, $cache::TTL_INDEFINITE
, $count, $count );
376 if ( $counter === false ) {
377 throw new RuntimeException( 'Unable to set value to ' . get_class( $cache ) );
381 // Note: use of fmod() avoids "division by zero" on 32 bit machines
382 if ( $counter === null ) {
383 $path = wfTempDir() . '/mw-' . __CLASS__
. '-' . rawurlencode( $bucket ) . '-48';
384 // Get the UID lock file handle
385 if ( isset( $this->fileHandles
[$path] ) ) {
386 $handle = $this->fileHandles
[$path];
388 $handle = fopen( $path, 'cb+' );
389 $this->fileHandles
[$path] = $handle ?
: null; // cache
391 // Acquire the UID lock file
392 if ( $handle === false ) {
393 throw new RuntimeException( "Could not open '{$path}'." );
395 if ( !flock( $handle, LOCK_EX
) ) {
397 throw new RuntimeException( "Could not acquire '{$path}'." );
399 // Fetch the counter value and increment it...
401 $counter = floor( trim( fgets( $handle ) ) ) +
$count; // fetch as float
402 // Write back the new counter value
403 ftruncate( $handle, 0 );
405 fwrite( $handle, fmod( $counter, 2 ** 48 ) ); // warp-around as needed
407 // Release the UID lock file
408 flock( $handle, LOCK_UN
);
412 $divisor = 2 ** $bits;
413 $currentId = floor( $counter - $count ); // pre-increment counter value
414 for ( $i = 0; $i < $count; ++
$i ) {
415 $ids[] = fmod( ++
$currentId, $divisor );
422 * Get a (time,counter,clock sequence) where (time,counter) is higher
423 * than any previous (time,counter) value for the given clock sequence.
424 * This is useful for making UIDs sequential on a per-node bases.
426 * @param string $lockFile Name of a local lock file
427 * @param int $clockSeqSize The number of possible clock sequence values
428 * @param int $counterSize The number of possible counter values
429 * @param int $offsetSize The number of possible offset values
430 * @return array Array with the following keys:
431 * - array 'time': array of seconds int and milliseconds int.
435 * - int 'offsetCounter'.
436 * @throws RuntimeException
438 protected function getTimeAndDelay( $lockFile, $clockSeqSize, $counterSize, $offsetSize ) {
439 // Get the UID lock file handle
440 if ( isset( $this->fileHandles
[$lockFile] ) ) {
441 $handle = $this->fileHandles
[$lockFile];
443 $handle = fopen( $this->$lockFile, 'cb+' );
444 $this->fileHandles
[$lockFile] = $handle ?
: null; // cache
446 // Acquire the UID lock file
447 if ( $handle === false ) {
448 throw new RuntimeException( "Could not open '{$this->$lockFile}'." );
450 if ( !flock( $handle, LOCK_EX
) ) {
452 throw new RuntimeException( "Could not acquire '{$this->$lockFile}'." );
455 // The formatters that use this method expect a timestamp with millisecond
456 // precision and a counter upto a certain size. When more IDs than the counter
457 // size are generated during the same timestamp, an exception is thrown as we
458 // cannot increment further, because the formatted ID would not have enough
459 // bits to fit the counter.
461 // To orchestrate this between independant PHP processes on the same hosts,
462 // we must have a common sense of time so that we only have to maintain
463 // a single counter in a single lock file.
466 // Format of lock file contents:
467 // "<clk seq> <sec> <msec> <counter> <rand offset>"
468 $data = explode( ' ', fgets( $handle ) );
470 // Did the clock get moved back significantly?
471 $clockChanged = false;
473 if ( count( $data ) === 5 ) {
474 // The UID lock file was already initialized
475 $clkSeq = (int)$data[0] %
$clockSeqSize;
476 $prevTime = [ (int)$data[1], (int)$data[2] ];
477 // Counter for UIDs with the same timestamp,
479 $randOffset = (int)$data[4] %
$counterSize;
481 // If the system clock moved backwards by an NTP sync,
482 // or if the last writer process had its clock drift ahead,
483 // Try to catch up if the gap is small, so that we can keep a single
484 // monotonic logic file.
485 $time = $this->timeWaitUntil( $prevTime );
486 if ( $time === false ) {
487 // Timed out. Treat it as a new clock
488 $clockChanged = true;
489 $time = $this->millitime();
490 } elseif ( $time === $prevTime ) {
491 // Sanity check, only keep remainder if a previous writer wrote
492 // something here that we don't accept.
493 $counter = (int)$data[3] %
$counterSize;
494 // Bump the counter if the time has not changed yet
495 if ( ++
$counter >= $counterSize ) {
496 // More IDs generated with the same time than counterSize can accomodate
497 flock( $handle, LOCK_UN
);
498 throw new RuntimeException( "Counter overflow for timestamp value." );
502 // Initialize UID lock file information
503 $clkSeq = mt_rand( 0, $clockSeqSize - 1 );
504 $time = $this->millitime();
506 $randOffset = mt_rand( 0, $offsetSize - 1 );
508 // microtime() and gettimeofday() can drift from time() at least on Windows.
509 // The drift is immediate for processes running while the system clock changes.
510 // time() does not have this problem. See https://bugs.php.net/bug.php?id=42659.
511 $drift = time() - $time[0];
512 if ( abs( $drift ) >= 2 ) {
513 // We don't want processes using too high or low timestamps to avoid duplicate
514 // UIDs and clock sequence number churn. This process should just be restarted.
515 flock( $handle, LOCK_UN
); // abort
516 throw new RuntimeException( "Process clock is outdated or drifted ({$drift}s)." );
518 // If microtime() is synced and a clock change was detected, then the clock went back
519 if ( $clockChanged ) {
520 // Bump the clock sequence number and also randomize the extra offset,
521 // which is useful for UIDs that do not include the clock sequence number.
522 $clkSeq = ( $clkSeq +
1 ) %
$clockSeqSize;
523 $randOffset = mt_rand( 0, $offsetSize - 1 );
524 trigger_error( "Clock was set back; sequence number incremented." );
527 // Update and release the UID lock file
528 ftruncate( $handle, 0 );
530 fwrite( $handle, "{$clkSeq} {$time[0]} {$time[1]} {$counter} {$randOffset}" );
532 flock( $handle, LOCK_UN
);
536 'counter' => $counter,
538 'offset' => $randOffset,
539 'offsetCounter' => $counter +
$randOffset,
544 * Wait till the current timestamp reaches $time and return the current
545 * timestamp. This returns false if it would have to wait more than 10ms.
547 * @param array $time Result of UIDGenerator::millitime()
548 * @return array|bool UIDGenerator::millitime() result or false
550 protected function timeWaitUntil( array $time ) {
552 $ct = $this->millitime();
553 if ( $ct >= $time ) { // https://secure.php.net/manual/en/language.operators.comparison.php
554 return $ct; // current timestamp is higher than $time
556 } while ( ( ( $time[0] - $ct[0] ) * 1000 +
( $time[1] - $ct[1] ) ) <= 10 );
562 * @param array $time Result of UIDGenerator::millitime()
563 * @return string 46 LSBs of "milliseconds since epoch" in binary (rolls over in 4201)
564 * @throws RuntimeException
566 protected function millisecondsSinceEpochBinary( array $time ) {
567 list( $sec, $msec ) = $time;
568 $ts = 1000 * $sec +
$msec;
569 if ( $ts > 2 ** 52 ) {
570 throw new RuntimeException( __METHOD__
.
571 ': sorry, this function doesn\'t work after the year 144680' );
574 return substr( Wikimedia\base_convert
( $ts, 10, 2, 46 ), -46 );
578 * @param array $time Result of UIDGenerator::millitime()
579 * @param int $delta Number of intervals to add on to the timestamp
580 * @return string 60 bits of "100ns intervals since 15 October 1582" (rolls over in 3400)
581 * @throws RuntimeException
583 protected function intervalsSinceGregorianBinary( array $time, $delta = 0 ) {
584 list( $sec, $msec ) = $time;
585 $offset = '122192928000000000';
586 if ( PHP_INT_SIZE
>= 8 ) { // 64 bit integers
587 $ts = ( 1000 * $sec +
$msec ) * 10000 +
(int)$offset +
$delta;
588 $id_bin = str_pad( decbin( $ts %
( 2 ** 60 ) ), 60, '0', STR_PAD_LEFT
);
589 } elseif ( extension_loaded( 'gmp' ) ) {
590 $ts = gmp_add( gmp_mul( (string)$sec, '1000' ), (string)$msec ); // ms
591 $ts = gmp_add( gmp_mul( $ts, '10000' ), $offset ); // 100ns intervals
592 $ts = gmp_add( $ts, (string)$delta );
593 $ts = gmp_mod( $ts, gmp_pow( '2', '60' ) ); // wrap around
594 $id_bin = str_pad( gmp_strval( $ts, 2 ), 60, '0', STR_PAD_LEFT
);
595 } elseif ( extension_loaded( 'bcmath' ) ) {
596 $ts = bcadd( bcmul( $sec, 1000 ), $msec ); // ms
597 $ts = bcadd( bcmul( $ts, 10000 ), $offset ); // 100ns intervals
598 $ts = bcadd( $ts, $delta );
599 $ts = bcmod( $ts, bcpow( 2, 60 ) ); // wrap around
600 $id_bin = Wikimedia\base_convert
( $ts, 10, 2, 60 );
602 throw new RuntimeException( 'bcmath or gmp extension required for 32 bit machines.' );
608 * @return array (current time in seconds, milliseconds since then)
610 protected function millitime() {
611 list( $msec, $sec ) = explode( ' ', microtime() );
613 return [ (int)$sec, (int)( $msec * 1000 ) ];
617 * Delete all cache files that have been created.
619 * This is a cleanup method primarily meant to be used from unit tests to
620 * avoid poluting the local filesystem. If used outside of a unit test
621 * environment it should be used with caution as it may destroy state saved
624 * @see unitTestTearDown
626 * @codeCoverageIgnore
628 private function deleteCacheFiles() {
630 foreach ( $this->fileHandles
as $path => $handle ) {
631 if ( $handle !== null ) {
634 if ( is_file( $path ) ) {
637 unset( $this->fileHandles
[$path] );
639 if ( is_file( $this->nodeIdFile
) ) {
640 unlink( $this->nodeIdFile
);
645 * Cleanup resources when tearing down after a unit test.
647 * This is a cleanup method primarily meant to be used from unit tests to
648 * avoid poluting the local filesystem. If used outside of a unit test
649 * environment it should be used with caution as it may destroy state saved
652 * @internal For use by unit tests
653 * @see deleteCacheFiles
655 * @codeCoverageIgnore
657 public static function unitTestTearDown() {
659 $gen = self
::singleton();
660 $gen->deleteCacheFiles();
663 function __destruct() {
664 array_map( 'fclose', array_filter( $this->fileHandles
) );