Ei kuvausta

ProgressBar.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace MailPoet\Util;
  3. if (!defined('ABSPATH')) exit;
  4. use MailPoet\Config\Env;
  5. if (!class_exists('ProgressBar', false)) {
  6. /**
  7. * The Progress Bar class
  8. *
  9. */
  10. class ProgressBar {
  11. private $totalCount = 0;
  12. private $currentCount = 0;
  13. private $filename;
  14. public $url;
  15. /**
  16. * Initialize the class and set its properties.
  17. *
  18. */
  19. public function __construct(
  20. $progressBarId
  21. ) {
  22. $filename = $progressBarId . '-progress.json';
  23. $this->filename = Env::$tempPath . '/' . $filename;
  24. $this->url = Env::$tempUrl . '/' . $filename;
  25. $counters = $this->readProgress();
  26. if (isset($counters->total)) {
  27. $this->totalCount = $counters->total;
  28. }
  29. if (isset($counters->current)) {
  30. $this->currentCount = $counters->current;
  31. }
  32. }
  33. /**
  34. * Get the progress file URL
  35. *
  36. * @return string Progress file URL
  37. */
  38. public function getUrl() {
  39. return $this->url;
  40. }
  41. /**
  42. * Read the progress counters
  43. *
  44. * @return array|false Array of counters
  45. */
  46. private function readProgress() {
  47. if (!file_exists($this->filename)) {
  48. return false;
  49. }
  50. $jsonContent = file_get_contents($this->filename);
  51. if (is_string($jsonContent)) {
  52. return json_decode($jsonContent);
  53. }
  54. return false;
  55. }
  56. /**
  57. * Set the total count
  58. *
  59. * @param int $count Count
  60. */
  61. public function setTotalCount($count) {
  62. if (($count != $this->totalCount) || ($count == 0)) {
  63. $this->totalCount = $count;
  64. $this->currentCount = 0;
  65. $this->saveProgress();
  66. }
  67. }
  68. /**
  69. * Increment the current count
  70. *
  71. * @param int $count Count
  72. */
  73. public function incrementCurrentCount($count) {
  74. $this->currentCount += $count;
  75. $this->saveProgress();
  76. }
  77. /**
  78. * Save the progress counters
  79. *
  80. */
  81. private function saveProgress() {
  82. file_put_contents($this->filename, json_encode([
  83. 'total' => $this->totalCount,
  84. 'current' => $this->currentCount,
  85. ]));
  86. }
  87. /**
  88. * Delete the progress file
  89. *
  90. */
  91. public function deleteProgressFile() {
  92. unlink($this->filename);
  93. }
  94. }
  95. }