This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/Workflow/Registry.php

93 lines
2.7 KiB
PHP
Raw Normal View History

<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Workflow;
2016-03-25 15:43:30 +00:00
use Symfony\Component\Workflow\Exception\InvalidArgumentException;
use Symfony\Component\Workflow\SupportStrategy\WorkflowSupportStrategyInterface;
2016-03-25 15:43:30 +00:00
/**
* @author Fabien Potencier <fabien@symfony.com>
2016-03-25 15:43:30 +00:00
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*/
class Registry
{
2019-01-16 18:24:45 +00:00
private $workflows = [];
public function addWorkflow(WorkflowInterface $workflow, WorkflowSupportStrategyInterface $supportStrategy)
{
2019-01-16 18:24:45 +00:00
$this->workflows[] = [$workflow, $supportStrategy];
}
public function has(object $subject, string $workflowName = null): bool
{
foreach ($this->workflows as list($workflow, $supportStrategy)) {
if ($this->supports($workflow, $supportStrategy, $subject, $workflowName)) {
return true;
}
}
return false;
}
2016-12-06 13:57:19 +00:00
/**
* @return Workflow
*/
public function get(object $subject, string $workflowName = null)
{
$matched = [];
2016-03-25 15:43:30 +00:00
foreach ($this->workflows as list($workflow, $supportStrategy)) {
if ($this->supports($workflow, $supportStrategy, $subject, $workflowName)) {
$matched[] = $workflow;
2016-03-25 15:43:30 +00:00
}
}
if (!$matched) {
2020-03-03 19:07:47 +00:00
throw new InvalidArgumentException(sprintf('Unable to find a workflow for class "%s".', get_debug_type($subject)));
2016-03-25 15:43:30 +00:00
}
if (2 <= \count($matched)) {
$names = array_map(static function (WorkflowInterface $workflow): string {
return $workflow->getName();
}, $matched);
2020-03-03 19:07:47 +00:00
throw new InvalidArgumentException(sprintf('Too many workflows (%s) match this subject (%s); set a different name on each and use the second (name) argument of this method.', implode(', ', $names), get_debug_type($subject)));
}
return $matched[0];
}
/**
* @return Workflow[]
*/
public function all(object $subject): array
{
2019-01-16 18:24:45 +00:00
$matched = [];
foreach ($this->workflows as list($workflow, $supportStrategy)) {
if ($supportStrategy->supports($workflow, $subject)) {
$matched[] = $workflow;
}
}
return $matched;
}
private function supports(WorkflowInterface $workflow, WorkflowSupportStrategyInterface $supportStrategy, object $subject, ?string $workflowName): bool
{
2017-01-18 14:08:35 +00:00
if (null !== $workflowName && $workflowName !== $workflow->getName()) {
2016-03-25 15:43:30 +00:00
return false;
}
2017-01-18 14:08:35 +00:00
return $supportStrategy->supports($workflow, $subject);
}
}