@return Workflow

@throws WorkflowNotFoundException
770854
private function createWorkflow()
    {
        $workflowId = $this->workflowContext instanceof WorkflowContextInterface ? $this->workflowContext->getWorkflowId() : $this->workflowContext;
        $workflow = $this->workflowRepository->findById($workflowId);
        if ($workflow === null) {
            throw new WorkflowNotFoundException(sprintf('The workflow "%s" is not found.', $workflowId));
        }

        return $workflow;
    }
758138
public function getWorkflow($id)
	{
		if ( ! array_key_exists($id, $this->_w) ) {

			$workflow = null;
			$def =  $this->getWorkflowDefinition($id);

			if ( $def != null ) {
				unset($def[self::KEY_NODES]);
				$def['id'] = $id;
				if ( isset($def[Workflow::PARAM_INITIAL_STATUS_ID])) {
					$ids = $this->parseStatusId($def[Workflow::PARAM_INITIAL_STATUS_ID], $id);
					$def[Workflow::PARAM_INITIAL_STATUS_ID] = implode(self::SEPARATOR_STATUS_NAME, $ids);
				} else {
					throw new WorkflowException('failed to load Workflow '.$id.' : missing initial status id');
				}
				$def['class'] = $this->getClassMapByType(self::TYPE_WORKFLOW);
				$def['source'] = $this;

				$workflow = Yii::createObject($def);
			}
			$this->_w[$id] = $workflow;
		}
		return $this->_w[$id];
	}
766822
protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!$this->workflowRegistry instanceof Registry) {
            throw new Exception('Can not execute task: No workflows were defined');
        }

        $taskId = $input->getArgument('task-id');

        $callback = function () use ($taskId) {
            $task = $this->entityManager->find(Task::class, $taskId);

            if ($task instanceof Task) {
                $task->setStatus('in-progress');
            }

            return $task;
        };

        $task = $this->entityManager->transactional($callback);

        if (!$task instanceof Task) {
            $output->writeln(sprintf('No task found for id %d', $taskId));

            return;
        }

        $this->setAnonymousToken();

        $subject = $this->subjectManager->createSubject($task->getModel());
        $subject->setUp();
        $generator = $this->generatorManager->getGenerator($task->getGenerator());
        $workflow = $this->workflowRegistry->get($subject, $task->getModel());

        $path = new Path();
        $path->add(null, null, [$workflow->getDefinition()->getInitialPlace()]);

        try {
            foreach ($generator->getAvailableTransitions($workflow, $subject, $task->getMetaData()) as $transitionName) {
                try {
                    if (!$generator->applyTransition($workflow, $subject, $transitionName)) {
                        throw new Exception(sprintf("Generator '%s' generated transition '%s' that can not be applied", $task->getGenerator(), $transitionName));
                    }
                } catch (Throwable $throwable) {
                    throw $throwable;
                } finally {
                    $data = $subject->getStoredData();
                    $places = array_keys(array_filter($workflow->getMarking($subject)->getPlaces()));
                    $path->add($transitionName, $data, $places);
                }
            }
        } catch (Throwable $throwable) {
            $message = new CreateBugMessage(
                $this->defaultBugTitle,
                Path::serialize($path),
                $path->countPlaces(),
                $throwable->getMessage(),
                $task->getId(),
                'new'
            );
            $this->messageBus->dispatch($message);
        } finally {
            $subject->tearDown();

            $this->messageBus->dispatch(new UpdateTaskStatusMessage($taskId, 'completed'));
        }
    }
914050
public function getActionByName(WorkflowDescriptor $wf, $actionName)
    {
        $actionName = (string)$actionName;

        foreach ($wf->getGlobalActions() as $actionDescriptor) {
            if ($actionName === $actionDescriptor->getName()) {
                return $actionDescriptor;
            }
        }

        foreach ($wf->getSteps() as $stepDescriptor) {
            $actions = $stepDescriptor->getActions();
            foreach ($actions as $actionDescriptor) {
                if ($actionName === $actionDescriptor->getName()) {
                    return $actionDescriptor;
                }
            }
        }

        foreach ($wf->getInitialActions() as $actionDescriptor) {
            if ($actionName === $actionDescriptor->getName()) {
                return $actionDescriptor;
            }
        }

        return null;
    }
1021632
public function run()
    {
        Model::unguard();

        Category::create([
            'parent_id'   => 0,
            'title'       => 'Blog',
            'description' => 'The main blog category',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);


        ////////////////////////////////////////////////////
        //           Lookup_workflow_status               //
        ////////////////////////////////////////////////////

        Lookup_workflow_status::create([
            'title'       => 'In Progress',
            'description' => 'Currently being edited.',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);

        Lookup_workflow_status::create([
            'title'       => 'Awaiting Approval',
            'description' => 'Waiting for approval of edits.',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);

        Lookup_workflow_status::create([
            'title'       => 'Approved',
            'description' => 'Edits are approved.',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);

        Lookup_workflow_status::create([
            'title'       => 'Published',
            'description' => 'Published.',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);

        Lookup_workflow_status::create([
            'title'       => 'Fire the Publish Event',
            'description' => 'Send to a LaSalleCRM email list, post a Tweet, etc.',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);
    }
518677
def load_or_create_workflow(self):
        
        self.workflow_spec = self.get_worfklow_spec()
        return self._load_workflow() or self.create_workflow()
316085
public function indexAction()
    {
        // To begin the step of installation, the user must click "continue".
        if (! $this->params()->fromRoute('process')) {
            return new ViewModel();
        }

        $installation = $this->getInstallation();
        $redirect     = $this->getRedirect();
        $step         = $installation->getCurrentStep();
        $member       = $step->getCurrentMember();
        $service      = $this->getService();
        $validator    = $this->getValidator();

        foreach ($member as $item) {
            if (! $validator->isValid($item)) {
                if (! $service->process($item)) {
                    return new ViewModel([
                        'errors' => $service->getMessages()
                    ]);
                }
            }
        }
        return $this->redirect()->toUrl($redirect);
    }
898789
protected function getProcessStep($stepName)
    {
        $step = $this->process->getStep($stepName);

        if (! ($step instanceof Step)) {
            throw new WorkflowException(sprintf('Can\'t find step named "%s" in process "%s".', $stepName, $this->process->getName()));
        }

        return $step;
    }
109679
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $start = microtime(true);

        $this->getContainer()->get('ez_migration_bundle.step_executed_listener.tracing')->setOutput($output);

        $workflowService = $this->getWorkflowService();

        $workflowName = $input->getOption('workflow');
        if ($workflowName != null) {
            $suspendedWorkflow = $workflowService->getWorkflow($workflowName);
            if (!$suspendedWorkflow) {
                throw new \Exception("Workflow '$workflowName' not found");
            }
            if ($suspendedWorkflow->status != Migration::STATUS_SUSPENDED) {
                throw new \Exception("Workflow '$workflowName' is not suspended, can not resume it");
            }

            $suspendedWorkflows = array($suspendedWorkflow);
        } else {
            $suspendedWorkflows = $workflowService->getWorkflowsByStatus(Migration::STATUS_SUSPENDED);
        };

        $output->writeln('<info>Found ' . count($suspendedWorkflows) . ' suspended workflows</info>');

        if (!count($suspendedWorkflows)) {
            $output->writeln('Nothing to do');
            return;
        }

        // ask user for confirmation to make changes
        if ($input->isInteractive() && !$input->getOption('no-interaction')) {
            $dialog = $this->getHelperSet()->get('dialog');
            if (!$dialog->askConfirmation(
                $output,
                '<question>Careful, the database will be modified. Do you want to continue Y/N ?</question>',
                false
            )
            ) {
                $output->writeln('<error>Workflow resuming cancelled!</error>');
                return 0;
            }
        }

        $executed = 0;
        $failed = 0;

        foreach($suspendedWorkflows as $suspendedWorkflow) {
            $output->writeln("<info>Resuming {$suspendedWorkflow->name}</info>");

            try {
                $workflowService->resumeWorkflow($suspendedWorkflow, !$input->getOption('no-transactions'));
                $executed++;
            } catch (\Exception $e) {
                $output->writeln("\n<error>Workflow failed! Reason: " . $e->getMessage() . "</error>\n");
                $failed++;
            }
        }

        $time = microtime(true) - $start;
        $output->writeln("Resumed $executed workflows, failed $failed");
        $output->writeln("Time taken: ".sprintf('%.2f', $time)." secs, memory: ".sprintf('%.2f', (memory_get_peak_usage(true) / 1000000)). ' MB');

        if ($failed) {
            return 2;
        }
    }
772229
public function createAction()
    {
        $this->initializeScaffolding();
        $this->checkRequest();

        try {
            $this->beforeCreate();
            $this->scaffolding->doCreate($this->request->getPost());
            $this->flash->success($this->successMessage);
            return $this->afterCreate();
        } catch (Exception $e) {
            $this->flash->error($e->getMessage());
            $this->afterCreateException();
        }

        return $this->dispatcher->forward(['action' => 'new']);
    }
1011873
public function getIndexMetadata()
    {
        if (null !== $this->indexMetadata) {
            return $this->indexMetadata;
        }
        $metadata = $this->getModuleOptions()->getWorkflowEntryToObjectMetadata();

        $index = [];
        foreach ($metadata as $metadataItem) {
            if (!array_key_exists(static::WORKFLOW_MANAGER_NAME, $metadataItem) && !array_key_exists(static::WORKFLOW_MANAGER_ALIAS, $metadataItem)) {
                $errMsg = sprintf(
                    'You must specify the %s or %s',
                    static::WORKFLOW_MANAGER_NAME,
                    static::WORKFLOW_MANAGER_ALIAS
                );
                throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
            }

            if (array_key_exists(static::WORKFLOW_MANAGER_NAME, $metadataItem) && array_key_exists(static::WORKFLOW_MANAGER_ALIAS, $metadataItem)) {
                $errMsg = sprintf(
                    'You can not specify both %s and %s',
                    static::WORKFLOW_MANAGER_NAME,
                    static::WORKFLOW_MANAGER_ALIAS
                );
                throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
            }

            if (!array_key_exists(static::WORKFLOW_NAME, $metadataItem)) {
                $errMsg = sprintf('there is no option %s', static::WORKFLOW_NAME);
                throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
            }
            $workflowName = $metadataItem[static::WORKFLOW_NAME];

            if (!array_key_exists(static::ROUTER_NAME, $metadataItem)) {
                $errMsg = sprintf('there is no option %s', static::ROUTER_NAME);
                throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
            }
            $routerName = $metadataItem[static::ROUTER_NAME];

            $prefix = '';
            if (array_key_exists(static::WORKFLOW_MANAGER_NAME, $metadataItem)) {
                $prefix = 'name_' . $metadataItem[static::WORKFLOW_MANAGER_NAME] . '_';
            }

            if (array_key_exists(static::WORKFLOW_MANAGER_ALIAS, $metadataItem)) {
                $prefix = 'alias_' . $metadataItem[static::WORKFLOW_MANAGER_ALIAS] . '_';
            }

            $uniqueKey = $prefix . $workflowName . '_' . $routerName;

            if (array_key_exists($uniqueKey, $index)) {
                $errMsg = sprintf('Index contains duplicate keys %s', $uniqueKey);
                throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
            }

            $index[$uniqueKey] = [];


            if (!array_key_exists(static::MAP, $metadataItem)) {
                $errMsg = sprintf('there is no option %s', static::MAP);
                throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
            }
            if (!is_array($metadataItem[static::MAP])) {
                $errMsg = sprintf('option %s is not array', static::MAP);
                throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
            }
            $map = $metadataItem[static::MAP];

            foreach ($map as $mapItem) {
                if (!array_key_exists(static::ENTITY_CLASS_NAME, $mapItem)) {
                    $errMsg = sprintf('there is no option %s', static::ENTITY_CLASS_NAME);
                    throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
                }
                $entityClassName = $mapItem[static::ENTITY_CLASS_NAME];

                if (array_key_exists($entityClassName, $index[$uniqueKey])) {
                    $errMsg = sprintf('Metadata for entities already exist %s', $mapItem[static::ENTITY_CLASS_NAME]);
                    throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
                }
                $index[$uniqueKey][$entityClassName] = [];

                if (!array_key_exists(static::IDENTIFIERS_MAP, $mapItem)) {
                    $errMsg = sprintf('there is no option %s', static::IDENTIFIERS_MAP);
                    throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
                }
                if (!is_array($mapItem[static::IDENTIFIERS_MAP])) {
                    $errMsg = sprintf('option %s is not array', static::IDENTIFIERS_MAP);
                    throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
                }

                $identifiersMap = $mapItem[static::IDENTIFIERS_MAP];

                foreach ($identifiersMap as $identifierItem) {
                    if (!array_key_exists(static::PROPERTY_NAME, $identifierItem)) {
                        $errMsg = sprintf('there is no option %s', static::PROPERTY_NAME);
                        throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
                    }
                    $propertyName = $identifierItem[static::PROPERTY_NAME];

                    if (array_key_exists($propertyName, $index[$uniqueKey][$entityClassName])) {
                        $errMsg = sprintf('Metadata for property already exist %s', $propertyName);
                        throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
                    }
                    $index[$uniqueKey][$entityClassName][$propertyName] = [];

                    $modeOriginal = array_key_exists(static::MODE, $identifierItem) ? $identifierItem[static::MODE] : static ::MODE_ROUTER_PARAM;
                    $mode = strtolower($modeOriginal);

                    if (!array_key_exists($mode, $this->accessMode)) {
                        $errMsg = sprintf('Invalid value for the "mode" %s', $mode);
                        throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
                    }
                    $index[$uniqueKey][$entityClassName][$propertyName][static::MODE] = $mode;

                    if (!array_key_exists(static::PARAM_NAME, $identifierItem)) {
                        $errMsg = sprintf('there is no option %s', static::PARAM_NAME);
                        throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
                    }
                    $paramName = $identifierItem[static::PARAM_NAME];
                    $index[$uniqueKey][$entityClassName][$propertyName][static::PARAM_NAME] = $paramName;
                }
            }
        }

        $this->indexMetadata = $index;

        return $this->indexMetadata;
    }
221997
public function execute()
    {
        $this->configure();
        $this->before();

        $name = $this->request()->attribute($this->attribute);

        if (!$this->methodExists($name))
        {
            throw new NotFound('Action \'' . $name . '\' not found!');
        }

        $data = $this->instance($name);

        $this->after($data);

        return $this->display($data);
    }
1128012
public function getFrontEndWorkflowActions()
    {
        $action    = $this->CurrentAction();
        $options   = $action->getValidTransitions();
        $actions   = new FieldList();

        $hide_disabled_actions_on_frontend = $this->config()->hide_disabled_actions_on_frontend;

        foreach ($options as $option) {
            $btn = new FormAction("transition_{$option->ID}", $option->Title);

            // add cancel class to passive actions, this prevents js validation (using jquery.validate)
            if ($option->Type == 'Passive') {
                $btn->addExtraClass('cancel');
            }

            // disable the button if canExecute() returns false
            if (!$option->canExecute($this)) {
                if ($hide_disabled_actions_on_frontend) {
                    continue;
                }

                $btn = $btn->performReadonlyTransformation();
                $btn->addExtraClass('hide');
            }

            $actions->push($btn);
        }

        $action->updateFrontEndWorkflowActions($actions);

        return $actions;
    }
340810
public function configureWorkflow($workflowName)
    {
        $this->workflowName = $workflowName;

        $this->workflow = $this->container->getParameter('free_agent_workflow.workflows.'.$this->workflowName, null);

        if (is_null($this->workflow)) {
            throw new WorkflowException('The workflow "'.$this->workflowName.'" does not exist');
        }

        $defaultStep = $this->workflow['default_step'];
        if (!array_key_exists($defaultStep, $this->workflow['steps'])) {
            throw new WorkflowException('The default step of "'.$this->workflowName.'" does not exist');
        }

        foreach ($this->workflow['steps'] as $stepName => $stepConfiguration) {
            $this->steps->offsetSet($stepName, new Step($stepName, $stepConfiguration));
        }

        $this->defaultStep = new Step($defaultStep, $this->workflow['steps'][$defaultStep]);
        $this->actions     = array_key_exists('actions', $this->workflow) ? $this->workflow['actions'] : array();
        $this->validations = array_key_exists('validations', $this->workflow) ? $this->workflow['validations'] : array();

        return $this->getSteps();
    }
922014
public function createFlow()
    {
        $model = app($this->modelName);
        $model->save();

        $step = $model->steps->firstId();

        return redirect()->route(sprintf('%s.get', $this->prefixRoute), ['flow' => $model->_id, 'step' => $step]);
    }
1156765
public function newAction(Request $request)
    {
        $workflowProfileClass = $this->container->getParameter('open_orchestra_model.document.workflow_profile.class');
        /** @var WorkflowProfileInterface $workflowProfile */
        $workflowProfile = new $workflowProfileClass();
        $this->denyAccessUnlessGranted(ContributionActionInterface::CREATE, WorkflowProfileInterface::ENTITY_TYPE);

        $form = $this->createForm('oo_workflow_profile', $workflowProfile, array(
            'action' => $this->generateUrl('open_orchestra_workflow_admin_workflow_profile_new'),
            'method' => 'POST',
            'new_button' => true
        ));
        $form->handleRequest($request);

        if ($form->isValid()) {
            $documentManager = $this->get('object_manager');
            $documentManager->persist($workflowProfile);
            $documentManager->flush();
            $message = $this->get('translator')->trans('open_orchestra_workflow_admin.form.workflow_profile.creation');
            $this->get('session')->getFlashBag()->add('success', $message);

            $this->dispatchEvent(WorkflowProfileEvents::WORKFLOW_PROFILE_CREATE, new WorkflowProfileEvent($workflowProfile));
            $response = new Response(
                '',
                Response::HTTP_CREATED,
                array('Content-type' => 'text/html; charset=utf-8', 'workflowProfileId' => $workflowProfile->getId(), 'name' => $workflowProfile->getLabel($this->get('open_orchestra_backoffice.context_backoffice_manager')->getBackOfficeLanguage()))
                );

            return $response;
        }

        return $this->renderAdminForm($form);
    }
520427
public function handleException(ServerRequestInterface $request): ResponseInterface
    {
        /** @var MiddlewareInterface $middleware */
        $middleware = $this->getExceptionHandlers()->getNextMiddleware();
        if (!$middleware) {
            throw new WorkflowException(
                'No suitable middleware was found to handle the uncaught exception.',
                null,
                $request->getAttribute('exception')
            );
        }

        $this->getServicesFactory()->injectDependencies($middleware);

        $response = $middleware->process($request, $this);

        return $response;
    }