WorkflowExtension.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace WorkflowBundle\Twig;
  3. use Symfony\Component\Workflow\Registry;
  4. class WorkflowExtension extends \Twig_Extension
  5. {
  6. private $workflowRegistry;
  7. public function __construct(Registry $workflowRegistry)
  8. {
  9. $this->workflowRegistry = $workflowRegistry;
  10. }
  11. public function getFunctions()
  12. {
  13. return array(
  14. new \Twig_SimpleFunction('workflow_can', array($this, 'canTransition')),
  15. new \Twig_SimpleFunction('workflow_transitions', array($this, 'getEnabledTransitions')),
  16. new \Twig_SimpleFunction('workflow_correct_state', array($this, 'isCorrectState'))
  17. );
  18. }
  19. public function isCorrectState($object, $name = null)
  20. {
  21. try {
  22. $places = $this->workflowRegistry->get($object, $name)->getDefinition()->getPlaces();
  23. } catch (\Exception $e) {
  24. $places = array();
  25. }
  26. $state = $object->getCurrentState();
  27. if(is_null($state)) return false;
  28. if(isset($places[$state])) return true;
  29. return false;
  30. }
  31. public function canTransition($object, $transition, $name = null)
  32. {
  33. return $this->workflowRegistry->get($object, $name)->can($object, $transition);
  34. }
  35. public function getEnabledTransitions($object, $name = null)
  36. {
  37. try {
  38. $return = $this->workflowRegistry->get($object, $name)->getEnabledTransitions($object);
  39. } catch (\Exception $e) {
  40. $return = array();
  41. }
  42. return $return;
  43. }
  44. public function getName()
  45. {
  46. return 'workflow';
  47. }
  48. }