|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tricks\Filters; |
| 4 | + |
| 5 | +use Illuminate\Session\Store; |
| 6 | +use Illuminate\Config\Repository; |
| 7 | + |
| 8 | +class ViewThrottleFilter |
| 9 | +{ |
| 10 | + /** |
| 11 | + * Config repository instance. |
| 12 | + * |
| 13 | + * @var \Illuminate\Config\Repository |
| 14 | + */ |
| 15 | + protected $config; |
| 16 | + |
| 17 | + /** |
| 18 | + * Session store instance. |
| 19 | + * |
| 20 | + * @var \Illuminate\Session\Store |
| 21 | + */ |
| 22 | + protected $session; |
| 23 | + |
| 24 | + /** |
| 25 | + * Create a new view throttle filter instance. |
| 26 | + * |
| 27 | + * @param \Illuminate\Config\Repository $config |
| 28 | + * @param \Illuminate\Session\Store $session |
| 29 | + * @return void |
| 30 | + */ |
| 31 | + public function __construct(Repository $config, Store $session) |
| 32 | + { |
| 33 | + $this->config = $config; |
| 34 | + $this->session = $session; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Execute the route filter. |
| 39 | + * |
| 40 | + * @return void |
| 41 | + */ |
| 42 | + public function filter() |
| 43 | + { |
| 44 | + $tricks = $this->getViewedTricks(); |
| 45 | + |
| 46 | + if ($tricks !== null) { |
| 47 | + $tricks = $this->purgeExpiredTricks($tricks); |
| 48 | + |
| 49 | + $this->storeViewedTricks($tricks); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Get the recently viewed tricks from the session. |
| 55 | + * |
| 56 | + * @return array|null |
| 57 | + */ |
| 58 | + protected function getViewedTricks() |
| 59 | + { |
| 60 | + return $this->session->get('viewed_tricks', null); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * Get the view throttle time from the config. |
| 65 | + * |
| 66 | + * @return int |
| 67 | + */ |
| 68 | + protected function getThrottleTime() |
| 69 | + { |
| 70 | + return $this->config->get('config.view_throttle_time'); |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * Filter the tricks array, removing expired tricks. |
| 75 | + * |
| 76 | + * @param array $tricks |
| 77 | + * @return array |
| 78 | + */ |
| 79 | + protected function purgeExpiredTricks(array $tricks) |
| 80 | + { |
| 81 | + $time = time(); |
| 82 | + $throttleTime = $this->getThrottleTime(); |
| 83 | + |
| 84 | + return array_filter($tricks, function ($timestamp) use ($time, $throttleTime) { |
| 85 | + return ($timestamp + $throttleTime) > $time; |
| 86 | + }); |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Store the recently viewed tricks in the session. |
| 91 | + * |
| 92 | + * @param array $tricks |
| 93 | + * @return void |
| 94 | + */ |
| 95 | + protected function storeViewedTricks(array $tricks) |
| 96 | + { |
| 97 | + $this->session->put('viewed_tricks', $tricks); |
| 98 | + } |
| 99 | +} |
0 commit comments