RobinDev /
Google
| 1 | <?php |
||
| 2 | |||
| 3 | namespace rOpenDev\Google; |
||
| 4 | |||
| 5 | trait SleepTrait |
||
| 6 | { |
||
| 7 | /** @var int Time we need to wait between two request * */ |
||
| 8 | protected $sleep = 0; |
||
| 9 | |||
| 10 | /** |
||
| 11 | * Chainable `$waitBetweenRequests` setter. |
||
| 12 | * |
||
| 13 | * @return self |
||
| 14 | */ |
||
| 15 | public function setSleep($seconds) |
||
| 16 | { |
||
| 17 | $this->sleep = $seconds * 1000000; |
||
| 18 | |||
| 19 | return $this; |
||
| 20 | } |
||
| 21 | |||
| 22 | /** |
||
| 23 | * Return the time the script need to sleep. |
||
| 24 | * |
||
| 25 | * @return int Microseconds |
||
| 26 | */ |
||
| 27 | protected function getSleep() |
||
| 28 | { |
||
| 29 | $halfSleep = $this->sleep / 2; |
||
| 30 | $sleepMin = (int) floor($this->sleep - $halfSleep); |
||
| 31 | $sleepMax = (int) ceil($this->sleep + $halfSleep); |
||
| 32 | |||
| 33 | return rand($sleepMin, $sleepMax); |
||
| 34 | } |
||
| 35 | |||
| 36 | /** |
||
| 37 | * Exec sleep. |
||
| 38 | * |
||
| 39 | * @return int The time we rest |
||
| 40 | */ |
||
| 41 | public function execSleep() |
||
| 42 | { |
||
| 43 | if ($this->previousRequestUsedCache) { |
||
| 44 | return; |
||
| 45 | } |
||
| 46 | |||
| 47 | if ($this->sleep) { |
||
| 48 | $sleep = $this->getSleep(); |
||
| 49 | usleep($sleep); |
||
| 50 | |||
| 51 | return $sleep; |
||
| 52 | } |
||
| 53 | } |
||
| 54 | |||
| 55 | /** |
||
| 56 | * Exec a half sleep. |
||
| 57 | * |
||
| 58 | * @return int The time we rest |
||
| 59 | */ |
||
| 60 | public function execHalfSleep() |
||
| 61 | { |
||
| 62 | if ($this->previousRequestUsedCache) { |
||
| 63 | return; |
||
| 64 | } |
||
| 65 | |||
| 66 | if ($this->sleep) { |
||
| 67 | $sleep = round($this->getSleep() / 2); |
||
| 68 | usleep($sleep); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 69 | |||
| 70 | return $sleep; |
||
| 71 | } |
||
| 72 | } |
||
| 73 | } |
||
| 74 |