| 1 |
<?php |
| 2 |
namespace WPIDE\App\Services\Transient; |
| 3 |
|
| 4 |
use WPIDE\App\Services\Service; |
| 5 |
|
| 6 |
class Transient implements Service |
| 7 |
{ |
| 8 |
|
| 9 |
protected $prefix; |
| 10 |
|
| 11 |
public function init(array $config = []) |
| 12 |
{ |
| 13 |
|
| 14 |
$this->prefix = !empty($config['prefix']) ? $config['prefix'] : ''; |
| 15 |
} |
| 16 |
|
| 17 |
public function set($key, $val, $expiration = YEAR_IN_SECONDS): bool |
| 18 |
{ |
| 19 |
|
| 20 |
return set_transient( $this->prefix.$key, $val, $expiration ); |
| 21 |
} |
| 22 |
|
| 23 |
public function get($key, $default = null) { |
| 24 |
|
| 25 |
$value = get_transient( $this->prefix.$key ); |
| 26 |
|
| 27 |
if($value === false) { |
| 28 |
return $default; |
| 29 |
} |
| 30 |
|
| 31 |
return $value; |
| 32 |
} |
| 33 |
|
| 34 |
public function delete($key): bool |
| 35 |
{ |
| 36 |
|
| 37 |
return delete_transient( $this->prefix.$key ); |
| 38 |
} |
| 39 |
|
| 40 |
public function exists($key): bool |
| 41 |
{ |
| 42 |
|
| 43 |
return $this->get( $key ) !== false; |
| 44 |
} |
| 45 |
|
| 46 |
public function result($key, callable $callback, $expiration = YEAR_IN_SECONDS) { |
| 47 |
|
| 48 |
$cached = $this->get($key); |
| 49 |
|
| 50 |
if($cached === false || !empty($_GET['nocache'])) { |
| 51 |
|
| 52 |
$cached = $callback(); |
| 53 |
|
| 54 |
$this->set($key, $cached, $expiration); |
| 55 |
} |
| 56 |
|
| 57 |
return $cached; |
| 58 |
} |
| 59 |
|
| 60 |
} |