Command.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. <?php
  2. namespace easyTask;
  3. use \Closure as Closure;
  4. /**
  5. * Class Command
  6. * @package easyTask
  7. */
  8. class Command
  9. {
  10. /**
  11. * 通讯文件
  12. */
  13. private $msgFile;
  14. /**
  15. * 构造函数
  16. * @throws
  17. */
  18. public function __construct()
  19. {
  20. $this->initMsgFile();
  21. }
  22. /**
  23. * 初始化文件
  24. */
  25. private function initMsgFile()
  26. {
  27. //创建文件
  28. $path = Helper::getCsgPath();
  29. $file = $path . '%s.csg';
  30. $this->msgFile = sprintf($file, md5(__FILE__));
  31. if (!file_exists($this->msgFile))
  32. {
  33. if (!file_put_contents($this->msgFile, '[]', LOCK_EX))
  34. {
  35. Helper::showError('failed to create msgFile');
  36. }
  37. }
  38. }
  39. /**
  40. * 获取数据
  41. * @return array
  42. * @throws
  43. */
  44. public function get()
  45. {
  46. $content = @file_get_contents($this->msgFile);
  47. if (!$content)
  48. {
  49. return [];
  50. }
  51. $data = json_decode($content, true);
  52. return is_array($data) ? $data : [];
  53. }
  54. /**
  55. * 重置数据
  56. * @param array $data
  57. */
  58. public function set($data)
  59. {
  60. file_put_contents($this->msgFile, json_encode($data), LOCK_EX);
  61. }
  62. /**
  63. * 投递数据
  64. * @param array $command
  65. */
  66. public function push($command)
  67. {
  68. $data = $this->get();
  69. array_push($data, $command);
  70. $this->set($data);
  71. }
  72. /**
  73. * 发送命令
  74. * @param array $command
  75. */
  76. public function send($command)
  77. {
  78. $command['time'] = time();
  79. $this->push($command);
  80. }
  81. /**
  82. * 接收命令
  83. * @param string $msgType 消息类型
  84. * @param mixed $command 收到的命令
  85. */
  86. public function receive($msgType, &$command)
  87. {
  88. $data = $this->get();
  89. if (empty($data)) {
  90. return;
  91. }
  92. foreach ($data as $key => $item)
  93. {
  94. if ($item['msgType'] == $msgType)
  95. {
  96. $command = $item;
  97. unset($data[$key]);
  98. break;
  99. }
  100. }
  101. $this->set($data);
  102. }
  103. /**
  104. * 根据命令执行对应操作
  105. * @param int $msgType 消息类型
  106. * @param Closure $func 执行函数
  107. * @param int $time 等待方时间戳
  108. */
  109. public function waitCommandForExecute($msgType, $func, $time)
  110. {
  111. $command = '';
  112. $this->receive($msgType, $command);
  113. if (!$command || (!empty($command['time']) && $command['time'] < $time))
  114. {
  115. return;
  116. }
  117. $func($command);
  118. }
  119. }