modalConsoleHistory.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. class modalConsoleHistory
  3. {
  4. /** @var xPDOCacheManager */
  5. public $cacheManager;
  6. /** @var array */
  7. public $items = [];
  8. /** @var string */
  9. protected $userFolder;
  10. /** @var integer */
  11. protected $limit;
  12. public function __construct($cacheManager, array $config)
  13. {
  14. $this->cacheManager = $cacheManager;
  15. $this->userFolder = $config['userFolder'];
  16. $this->limit = $config['limit'];
  17. $this->loadHistory();
  18. }
  19. public function loadHistory()
  20. {
  21. $this->items = $this->cacheManager->get('history', array(xPDO::OPT_CACHE_KEY => $this->userFolder));
  22. $this->items = is_null($this->items) ? [] : $this->items;
  23. return $this;
  24. }
  25. public function getItems()
  26. {
  27. return $this->items;
  28. }
  29. public function getItem($key, $default = '')
  30. {
  31. return isset($this->items[$key]) ? $this->items[$key] : $default;
  32. }
  33. public function addItem($key, $code)
  34. {
  35. $this->deleteItem($key);
  36. $this->items[$key] = $code;
  37. if ($this->count() > $this->limit) {
  38. $diff = $this->count() - $this->limit;
  39. $this->items = array_slice($this->items, $diff);
  40. }
  41. return $this;
  42. }
  43. public function deleteItem($key)
  44. {
  45. if ($this->hasItem($key)) {
  46. unset($this->items[$key]);
  47. }
  48. return $this;
  49. }
  50. public function hasItem($key)
  51. {
  52. return isset($this->items[$key]);
  53. }
  54. public function getLastItem($default = '')
  55. {
  56. end($this->items);
  57. return $this->getItem(key($this->items), $default);
  58. }
  59. public function getKeys()
  60. {
  61. return array_keys($this->items);
  62. }
  63. public function isEmpty()
  64. {
  65. return empty($this->items);
  66. }
  67. public function count()
  68. {
  69. return count($this->items);
  70. }
  71. public function save($force = false)
  72. {
  73. if ($this->limit > 0 || $force) {
  74. $options = array(
  75. xPDO::OPT_CACHE_KEY => $this->getUserFolder(),
  76. );
  77. $items = $this->getItems();
  78. return $this->getCacheManager()->set('history', $items, 0, $options);
  79. }
  80. return false;
  81. }
  82. public function clear()
  83. {
  84. $options = array(
  85. xPDO::OPT_CACHE_KEY => $this->getUserFolder(),
  86. );
  87. $this->items = [];
  88. return $this->getCacheManager()->set('history', $this->items, 0, $options);
  89. }
  90. public function getUserFolder()
  91. {
  92. return $this->userFolder;
  93. }
  94. public function getCacheManager()
  95. {
  96. return $this->cacheManager;
  97. }
  98. }