HasProcessTrait.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * Author: 芸众商城 www.yunzshop.com
  5. * Date: 14/06/2018
  6. * Time: 11:44
  7. */
  8. namespace app\common\traits;
  9. use app\common\exceptions\AppException;
  10. use app\common\models\Flow;
  11. use app\common\models\Process;
  12. use app\frontend\modules\member\services\MemberService;
  13. use Illuminate\Database\Eloquent\Collection;
  14. use Illuminate\Database\Eloquent\Relations\HasMany;
  15. /**
  16. * Trait HasFlowTrait
  17. * @package app\common\traits
  18. * @property Collection process
  19. * @property Collection flows
  20. * @property Process flow
  21. */
  22. trait HasProcessTrait
  23. {
  24. /**
  25. * @var Process
  26. */
  27. protected $currentProcess;
  28. /**
  29. * 所有的流程类型
  30. * @return mixed
  31. */
  32. public function flows()
  33. {
  34. return $this->morphToMany(
  35. Flow::class,
  36. 'model',
  37. (new Process())->getTable(),
  38. 'model_id',
  39. 'flow_id'
  40. )->withTimestamps();
  41. }
  42. /**
  43. * @param Flow $flow
  44. * @return array
  45. */
  46. private function processAttribute(Flow $flow)
  47. {
  48. return ['uid' => \YunShop::app()->getMemberId(),
  49. 'flow_id' => $flow->id,
  50. 'model_id' => $this->id,
  51. 'model_type' => $this->getMorphClass(),
  52. 'uniacid' => \YunShop::app()->uniacid
  53. ];
  54. }
  55. /**
  56. * @param Flow $flow
  57. * @throws \Exception
  58. */
  59. public function addProcess(Flow $flow)
  60. {
  61. if ($this->currentProcess()->code == $flow->code) {
  62. throw new AppException("已存在未完成的{$this->currentProcess()->name}流程,无法继续添加");
  63. }
  64. $this->currentProcess = $this->createProcess($flow);
  65. $this->currentProcess;
  66. }
  67. /**
  68. * @param Flow $flow
  69. * @return Process
  70. * @throws \Exception
  71. */
  72. protected function createProcess(Flow $flow)
  73. {
  74. $process = new Process($this->processAttribute($flow));
  75. $process->initStatus();
  76. return $process;
  77. }
  78. /**
  79. * @return HasMany
  80. */
  81. public function process()
  82. {
  83. return $this->hasMany(Process::class, 'model_id')->where('model_type', $this->getMorphClass());
  84. }
  85. /**
  86. * 当前的流程
  87. * @return Process
  88. */
  89. public function currentProcess()
  90. {
  91. if (!isset($this->currentProcess)) {
  92. if ($this->process->isEmpty()) {
  93. return null;
  94. }
  95. $this->currentProcess = $this->process->where('state', 'processing')->first();
  96. }
  97. return $this->currentProcess;
  98. }
  99. }