WorkflowExtension.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. new \Twig_SimpleFunction('get_class', array($this, 'getClass'))
  18. );
  19. }
  20. public function isCorrectState($object, $name = null)
  21. {
  22. try {
  23. $places = $this->workflowRegistry->get($object, $name)->getDefinition()->getPlaces();
  24. } catch (\Exception $e) {
  25. $places = array();
  26. }
  27. $state = $object->getCurrentState();
  28. if(is_null($state)) return false;
  29. if(isset($places[$state])) return true;
  30. return false;
  31. }
  32. public function canTransition($object, $transition, $name = null)
  33. {
  34. return $this->workflowRegistry->get($object, $name)->can($object, $transition);
  35. }
  36. public function getEnabledTransitions($object, $name = null)
  37. {
  38. try {
  39. $return = $this->workflowRegistry->get($object, $name)->getEnabledTransitions($object);
  40. } catch (\Exception $e) {
  41. $return = array();
  42. }
  43. return $return;
  44. }
  45. public function getName()
  46. {
  47. return 'workflow';
  48. }
  49. public function getClass($object)
  50. {
  51. return get_class($object);
  52. }
  53. }