Brak opisu

Persistent.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace NSL\Persistent;
  3. use NSL\Persistent\Storage\Session;
  4. use NSL\Persistent\Storage\StorageAbstract;
  5. use NSL\Persistent\Storage\Transient;
  6. use WP_User;
  7. require_once dirname(__FILE__) . '/Storage/Abstract.php';
  8. require_once dirname(__FILE__) . '/Storage/Session.php';
  9. require_once dirname(__FILE__) . '/Storage/Transient.php';
  10. class Persistent {
  11. private static $instance;
  12. /** @var StorageAbstract */
  13. private $storage;
  14. public function __construct() {
  15. self::$instance = $this;
  16. add_action('init', array(
  17. $this,
  18. 'init'
  19. ), 0);
  20. add_action('wp_login', array(
  21. $this,
  22. 'transferSessionToUser'
  23. ), 10, 2);
  24. }
  25. public function init() {
  26. if ($this->storage === NULL) {
  27. if (is_user_logged_in()) {
  28. $this->storage = new Transient();
  29. } else {
  30. $this->storage = new Session();
  31. }
  32. }
  33. }
  34. public static function set($key, $value) {
  35. if (self::$instance->storage) {
  36. self::$instance->storage->set($key, $value);
  37. }
  38. }
  39. public static function get($key) {
  40. if (self::$instance->storage) {
  41. return self::$instance->storage->get($key);
  42. }
  43. return false;
  44. }
  45. public static function delete($key) {
  46. if (self::$instance->storage) {
  47. self::$instance->storage->delete($key);
  48. }
  49. }
  50. /**
  51. * @param $user_login
  52. * @param WP_User $user
  53. */
  54. public function transferSessionToUser($user_login, $user = null) {
  55. if (!$user) { // For do_action( 'wp_login' ) calls that lacked passing the 2nd arg.
  56. $user = get_user_by('login', $user_login);
  57. }
  58. $newStorage = new Transient($user->ID);
  59. /**
  60. * $this->storage might be NULL if init action not called yet
  61. */
  62. if ($this->storage !== NULL) {
  63. $newStorage->transferData($this->storage);
  64. }
  65. $this->storage = $newStorage;
  66. }
  67. public static function clear() {
  68. if (self::$instance->storage) {
  69. self::$instance->storage->clear();
  70. }
  71. }
  72. }
  73. new Persistent();