You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.5 KiB

  1. <?php
  2. namespace App;
  3. use Movim\Model;
  4. class Cache extends Model
  5. {
  6. protected $primaryKey = ['user_id', 'name'];
  7. public $incrementing = false;
  8. protected $fillable = ['user_id', 'name'];
  9. private static $_instance;
  10. public static function instanciate()
  11. {
  12. if (!is_object(self::$_instance)) {
  13. self::$_instance = new Cache;
  14. }
  15. return self::$_instance;
  16. }
  17. /**
  18. * Helper function to access cache.
  19. */
  20. public static function c()
  21. {
  22. $cache = self::instanciate();
  23. return call_user_func_array([$cache, 'handle'], func_get_args());
  24. }
  25. /**
  26. * Fetches or commits an object to cache with the provided key.
  27. *
  28. * Prototype: handle(string $key, ...)
  29. *
  30. * The following fetches an object from cache.
  31. * handle('key')
  32. *
  33. * This commits an object to cache.
  34. * handle('key', $object);
  35. *
  36. * Several objects can be commited to cache in this manner:
  37. * handle('key', $object1, $object2, $object3);
  38. * And retrieved as follows:
  39. * list($object1, $object2, $object3) = handle('key');
  40. */
  41. public function handle($key)
  42. {
  43. $arglist = func_get_args();
  44. $key = $arglist[0];
  45. if (func_num_args() == 1) {
  46. $content = $this->_readCache($key);
  47. if (isset($content) && $content != '') {
  48. return $content;
  49. }
  50. return null;
  51. }
  52. if (func_num_args() == 2) {
  53. return $this->_writeCache($key, $arglist[1]);
  54. }
  55. // Cutting a piece of the args.
  56. $content = array_slice($arglist, 1);
  57. return $this->_writeCache($key, $content);
  58. }
  59. /**
  60. * Serializes data in a proper fashion.
  61. */
  62. private function _writeCache($key, $object)
  63. {
  64. $data = str_replace(
  65. "'",
  66. "\\'",
  67. base64_encode(gzcompress(serialize($object)))
  68. );
  69. if (User::me()->id) {
  70. $cache = Cache::firstOrNew(['user_id' => User::me()->id, 'name' => $key]);
  71. $cache->data = $data;
  72. $cache->save();
  73. }
  74. }
  75. /**
  76. * Unserializes data.
  77. */
  78. private function _readCache($key)
  79. {
  80. $cache = $this->where('user_id', User::me()->id)
  81. ->where('name', $key)
  82. ->first();
  83. if (isset($cache)) {
  84. return unserialize(
  85. gzuncompress(base64_decode(str_replace("\\'", "'", $cache->data)))
  86. );
  87. }
  88. return false;
  89. }
  90. }