WorkflowTypeAttributeTrait.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace Drupal\workflow;
  3. use Drupal\Core\Entity\ContentEntityBase;
  4. use Drupal\workflow\Entity\Workflow;
  5. /**
  6. * Wrapper methods for Workflow* objects
  7. *
  8. * Using this trait will add getWorkflow(), getWorkflowID() and setWorkflow()
  9. * methods to the class.
  10. *
  11. * @ingroup workflow
  12. */
  13. trait WorkflowTypeAttributeTrait {
  14. /**
  15. * The machine_name of the attached Workflow.
  16. *
  17. * @var string
  18. */
  19. protected $wid = '';
  20. /**
  21. * The attached Workflow.
  22. * It must explicitly be defined, and not be public, to avoid errors
  23. * when exporting with json_encode().
  24. *
  25. * @var \Drupal\workflow\Entity\Workflow
  26. */
  27. protected $workflow = NULL;
  28. /**
  29. * @param \Drupal\workflow\Entity\Workflow $workflow
  30. */
  31. public function setWorkflow(Workflow $workflow = NULL) {
  32. $this->wid = '';
  33. $this->workflow = NULL;
  34. if ($workflow) {
  35. $this->wid = $workflow->id();
  36. $this->workflow = $workflow;
  37. }
  38. }
  39. /**
  40. * Returns the Workflow object of this object.
  41. *
  42. * @return Workflow
  43. * Workflow object.
  44. */
  45. public function getWorkflow() {
  46. if (!empty($this->workflow)) {
  47. return $this->workflow;
  48. }
  49. /** @noinspection PhpAssignmentInConditionInspection */
  50. if ($wid = $this->getWorkflowId()) {
  51. $this->workflow = Workflow::load($wid);
  52. }
  53. return $this->workflow;
  54. }
  55. /**
  56. * Sets the Workflow ID of this object.
  57. *
  58. * @param $wid Workflow ID
  59. *
  60. * @return object
  61. */
  62. public function setWorkflowId($wid) {
  63. $this->wid = $wid;
  64. $this->workflow = NULL;
  65. return $this;
  66. }
  67. /**
  68. * Returns the Workflow ID of this object.
  69. *
  70. * @return string
  71. * Workflow Id.
  72. */
  73. public function getWorkflowId() {
  74. /** @var ContentEntityBase $this */
  75. if (!empty($this->wid)) {
  76. return $this->wid;
  77. }
  78. $value = $this->get('wid');
  79. if (is_string($value)) {
  80. $this->wid = $value;
  81. }
  82. elseif (is_object($value)) {
  83. $wid = isset($value->getValue()[0]['target_id']) ? $value->getValue()[0]['target_id'] : '';
  84. // or: $this->set('wid', $wid);
  85. $this->wid = $wid; // in WorkflowTransition.
  86. }
  87. else {
  88. workflow_debug(__FILE__, __FUNCTION__, __LINE__, '', '');
  89. }
  90. return $this->wid;
  91. }
  92. }