|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Bridge\PhpUnit; |
| 13 | + |
| 14 | +/** |
| 15 | + * @author Nicolas Grekas <[email protected]> |
| 16 | + */ |
| 17 | +class ClockMock |
| 18 | +{ |
| 19 | + private static $now; |
| 20 | + |
| 21 | + public static function withClockMock($enable = null) |
| 22 | + { |
| 23 | + if (null === $enable) { |
| 24 | + return null !== self::$now; |
| 25 | + } |
| 26 | + |
| 27 | + self::$now = is_numeric($enable) ? (float) $enable : ($enable ? microtime(true) : null); |
| 28 | + } |
| 29 | + |
| 30 | + public static function time() |
| 31 | + { |
| 32 | + if (null === self::$now) { |
| 33 | + return \time(); |
| 34 | + } |
| 35 | + |
| 36 | + return (int) self::$now; |
| 37 | + } |
| 38 | + |
| 39 | + public static function sleep($s) |
| 40 | + { |
| 41 | + if (null === self::$now) { |
| 42 | + return \sleep($s); |
| 43 | + } |
| 44 | + |
| 45 | + self::$now += (int) $s; |
| 46 | + |
| 47 | + return 0; |
| 48 | + } |
| 49 | + |
| 50 | + public static function usleep($us) |
| 51 | + { |
| 52 | + if (null === self::$now) { |
| 53 | + return \usleep($us); |
| 54 | + } |
| 55 | + |
| 56 | + self::$now += $us / 1000000; |
| 57 | + } |
| 58 | + |
| 59 | + public static function microtime($asFloat = false) |
| 60 | + { |
| 61 | + if (null === self::$now) { |
| 62 | + return \microtime($asFloat); |
| 63 | + } |
| 64 | + |
| 65 | + if ($asFloat) { |
| 66 | + return self::$now; |
| 67 | + } |
| 68 | + |
| 69 | + return sprintf("%0.6f %d\n", $now - (int) $now, (int) self::$now); |
| 70 | + } |
| 71 | + |
| 72 | + public static function register($class) |
| 73 | + { |
| 74 | + $self = get_called_class(); |
| 75 | + |
| 76 | + $mockedNs = array(substr($class, 0, strrpos($class, '\\'))); |
| 77 | + if (strpos($class, '\\Tests\\')) { |
| 78 | + $ns = str_replace('\\Tests\\', '\\', $class); |
| 79 | + $mockedNs[] = substr($ns, 0, strrpos($ns, '\\')); |
| 80 | + } |
| 81 | + foreach ($mockedNs as $ns) { |
| 82 | + if (function_exists($ns.'\time')) { |
| 83 | + continue; |
| 84 | + } |
| 85 | + eval(<<<EOPHP |
| 86 | +namespace $ns; |
| 87 | +
|
| 88 | +function time() |
| 89 | +{ |
| 90 | + return \\$self::time(); |
| 91 | +} |
| 92 | +
|
| 93 | +function microtime(\$asFloat = false) |
| 94 | +{ |
| 95 | + return \\$self::microtime(\$asFloat); |
| 96 | +} |
| 97 | +
|
| 98 | +function sleep(\$s) |
| 99 | +{ |
| 100 | + return \\$self::sleep(\$s); |
| 101 | +} |
| 102 | +
|
| 103 | +function usleep(\$us) |
| 104 | +{ |
| 105 | + return \\$self::usleep(\$us); |
| 106 | +} |
| 107 | +
|
| 108 | +EOPHP |
| 109 | + ); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | +} |
0 commit comments