QueriesPosts.php
60 lines
| 1 | <?php |
| 2 | namespace WordPressPopularPosts\Traits; |
| 3 | |
| 4 | use WordPressPopularPosts\Query; |
| 5 | |
| 6 | trait QueriesPosts |
| 7 | { |
| 8 | /** |
| 9 | * Query object. |
| 10 | * |
| 11 | * @since 6.0.0 |
| 12 | * @var \WordPressPopularPosts\Query |
| 13 | * @access private |
| 14 | */ |
| 15 | private $query; |
| 16 | |
| 17 | /** |
| 18 | * Gets Query object from cache if it exists, |
| 19 | * otherwise a new Query object will be |
| 20 | * instantiated and returned. |
| 21 | * |
| 22 | * @since 6.0.0 |
| 23 | * @param array |
| 24 | * @return Query |
| 25 | */ |
| 26 | protected function maybe_query(array $params) |
| 27 | { |
| 28 | // Return cached results |
| 29 | if ( $this->config['tools']['cache']['active'] ) { |
| 30 | $key = 'wpp_' . md5(json_encode($params)); |
| 31 | $this->query = \WordPressPopularPosts\Cache::get($key); |
| 32 | |
| 33 | if ( false === $this->query ) { |
| 34 | $this->query = new Query($params); |
| 35 | |
| 36 | $time_value = $this->config['tools']['cache']['interval']['value']; |
| 37 | $time_unit = $this->config['tools']['cache']['interval']['time']; |
| 38 | |
| 39 | // No popular posts found, check again in 1 minute |
| 40 | if ( ! $this->query->get_posts() ) { |
| 41 | $time_value = 1; |
| 42 | $time_unit = 'minute'; |
| 43 | } |
| 44 | |
| 45 | \WordPressPopularPosts\Cache::set( |
| 46 | $key, |
| 47 | $this->query, |
| 48 | $time_value, |
| 49 | $time_unit |
| 50 | ); |
| 51 | } |
| 52 | } // Get real-time popular posts |
| 53 | else { |
| 54 | $this->query = new Query($params); |
| 55 | } |
| 56 | |
| 57 | return $this->query; |
| 58 | } |
| 59 | } |
| 60 |