repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/ProcessMaker/Test/Models/TestOneClassWithEmptyConstructor.php
tests/ProcessMaker/Test/Models/TestOneClassWithEmptyConstructor.php
<?php namespace ProcessMaker\Test\Models; use ProcessMaker\Test\Contracts\TestOneInterface; /** * TestOneClassWithEmptyConstructor */ class TestOneClassWithEmptyConstructor implements TestOneInterface { public $aField; /** * Test constructor */ public function __construct() { $this->aField = 'aField'; } /** * Test function * * @return string */ public function dummyFunction() { return 'test'; } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/ProcessMaker/Bpmn/TestEngine.php
tests/ProcessMaker/Bpmn/TestEngine.php
<?php namespace ProcessMaker\Bpmn; use ProcessMaker\Nayra\Contracts\Engine\EngineInterface; use ProcessMaker\Nayra\Contracts\Engine\EventDefinitionBusInterface; use ProcessMaker\Nayra\Contracts\Engine\JobManagerInterface; use ProcessMaker\Nayra\Contracts\EventBusInterface; use ProcessMaker\Nayra\Contracts\RepositoryInterface; use ProcessMaker\Nayra\Engine\EngineTrait; /** * Test implementation for EngineInterface. */ class TestEngine implements EngineInterface { use EngineTrait; /** * @var RepositoryInterface */ private $repository; /** * @var EventBusInterface */ protected $dispatcher; /** * Test engine constructor. * * @param \ProcessMaker\Nayra\Contracts\RepositoryInterface $repository * @param \ProcessMaker\Nayra\Contracts\EventBusInterface $dispatcher * @param \ProcessMaker\Nayra\Contracts\Engine\JobManagerInterface|null $jobManager * @param \ProcessMaker\Nayra\Contracts\Engine\EventDefinitionBusInterface|null $eventDefinitionBus */ public function __construct(RepositoryInterface $repository, EventBusInterface $dispatcher, JobManagerInterface $jobManager = null, EventDefinitionBusInterface $eventDefinitionBus = null) { $this->setRepository($repository); $this->setDispatcher($dispatcher); $this->setJobManager($jobManager); $this->setDataStore($repository->createDataStore()); $eventDefinitionBus ? $this->setEventDefinitionBus($eventDefinitionBus) : null; } /** * @return EventBusInterface */ public function getDispatcher() { return $this->dispatcher; } /** * @param EventBusInterface $dispatcher * * @return $this */ public function setDispatcher(EventBusInterface $dispatcher) { $this->dispatcher = $dispatcher; return $this; } /** * @return FactoryInterface */ public function getRepository() { return $this->repository; } /** * @param RepositoryInterface $repository * * @return $this */ public function setRepository(RepositoryInterface $repository) { $this->repository = $repository; return $this; } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Patterns/PatternsTest.php
tests/Feature/Patterns/PatternsTest.php
<?php namespace Tests\Feature\Patterns; use Exception; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\CallActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ErrorInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateCatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; use Tests\Feature\Engine\EngineTestCase; /** * Tests for the ServiceTask element */ class PatternsTest extends EngineTestCase { private $basePath = __DIR__ . '/files/'; /** * List the bpmn files * * @return array */ public function caseProvider() { $data = []; foreach (glob($this->basePath . '*.bpmn') as $bpmnFile) { $data[] = [basename($bpmnFile)]; } return $data; } /** * Tests the bpmn process completing all active tasks * * @param string $bpmnFile * * @dataProvider caseProvider */ public function testProcessPatterns($bpmnFile) { $file = $this->basePath . $bpmnFile; $jsonFile = substr($file, 0, -4) . 'json'; if (file_exists($jsonFile)) { $this->runProcessWithJson($jsonFile, $file); } else { $this->runProcessWithoutJson($file); } } /** * Run a process without json data * * @param string $bpmnFile * * @return void */ private function runProcessWithoutJson($bpmnFile) { $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load($bpmnFile); $startEvents = $bpmnRepository->getElementsByTagNameNS(BpmnDocument::BPMN_MODEL, 'startEvent'); foreach ($startEvents as $startEvent) { $data = []; $result = []; $this->runProcess($bpmnFile, $data, $startEvent->getAttribute('id'), $result, [], [], [], []); } } /** * Run a process with json data * * @param string $jsonFile * @param string $bpmnFile * * @return void */ private function runProcessWithJson($jsonFile, $bpmnFile) { $tests = json_decode(file_get_contents($jsonFile), true); foreach ($tests as $json) { $events = isset($json['events']) ? $json['events'] : []; $output = isset($json['output']) ? $json['output'] : []; $errors = isset($json['errors']) ? $json['errors'] : []; $this->runProcess($bpmnFile, $json['data'], $json['startEvent'], $json['result'], $events, $output, $errors, $json); } } /** * Run a process * * @param string $filename * @param array $data * @param string $startEvent * @param array $result * @param array $events * @param mixed $output * @param array $errors * @param array $json * * @return void */ private function runProcess($filename, $data, $startEvent, $result, $events, $output, $errors, $json) { $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load($filename); $start = $bpmnRepository->getStartEvent($startEvent); $process = $start->getProcess(); $dataStore = $this->repository->createDataStore(); $dataStore->setData($data); // set global data storage $this->engine->setDataStore($dataStore); $this->engine->loadBpmnDocument($bpmnRepository); // create instance with initial data if ($start->getEventDefinitions()->count() > 0) { $start->execute($start->getEventDefinitions()->item(0)); $instance = $process->getInstances()->count() ? $process->getInstances()->item(0) : null; } else { $instance = $this->engine->createExecutionInstance($process, $dataStore); $start->start($instance); } $this->engine->runToNextState(); $tasks = []; if (!$instance) { $this->assertEquals($result, $tasks); if ($output) { $this->assertEquals($output, $dataStore->getData()); } return; } $tokens = $instance->getTokens(); $processes = $bpmnRepository->getElementsByTagNameNS(BpmnDocument::BPMN_MODEL, 'process'); $runtimeErrors = []; $this->engine->getDispatcher()->listen('ActivityException', function ($payload) use (&$runtimeErrors) { $error = $payload[1]->getProperty('error'); if ($error) { $runtimeErrors[] = [ 'element' => $payload[0]->getId(), 'error' => $error instanceof ErrorInterface ? $error->getId() : $error, ]; } }); while ($tokens->count()) { $submited = false; foreach ($processes as $process) { foreach ($process->getBpmnElementInstance()->getInstances() as $ins) { foreach ($ins->getTokens() as $token) { $element = $token->getOwnerElement(); $status = $token->getStatus(); if ( $element instanceof ActivityInterface && !($element instanceof CallActivityInterface) && $status === ActivityInterface::TOKEN_STATE_ACTIVE ) { $tasks[] = $element->getId(); if ($element instanceof ScriptTaskInterface && $element->getScriptFormat() === 'application/x-betsy') { $element->runScript($token); } else { $element->complete($token); } $this->engine->runToNextState(); $submited = true; break; } if ($element instanceof IntermediateCatchEventInterface && $status === IntermediateCatchEventInterface::TOKEN_STATE_ACTIVE) { if ($events && $element->getId() === $events[0]) { $eventDefinition = $element->getEventDefinitions()->item(0); $element->execute($eventDefinition, $token->getInstance()); $this->engine->runToNextState(); $submited = true; array_shift($events); } } } } } $tokens = $instance->getTokens(); if (!$submited && $tokens->count()) { $elements = ''; foreach ($processes as $process) { foreach ($process->getBpmnElementInstance()->getInstances() as $ins) { foreach ($ins->getTokens() as $token) { $status = $token->getStatus(); $elements .= ' ' . $token->getOwnerElement()->getId() . ':' . $status; if ($status == ActivityInterface::TOKEN_STATE_FAILING) { $error = $token->getProperty('error'); $error = $error instanceof ErrorInterface ? $error->getId() : $error; $runtimeErrors[] = [ 'element' => $token->getOwnerElement()->getId(), 'error' => $error, ]; } } } } break; //throw new Exception('The process got stuck in elements:' . $elements); } } $testName = $json['comment'] ?? ''; $this->assertEquals($result, $tasks, $testName); if ($output) { $this->assertData($output, $dataStore->getData()); } if ($errors) { $this->assertData($errors, $runtimeErrors); } // Check data from all instances $expectedDataByInstances = $json['expectedDataByInstances'] ?? false; if ($expectedDataByInstances ?? false) { $i = 0; foreach ($processes as $process) { foreach ($process->getBpmnElementInstance()->getInstances() as $ins) { if (!isset($expectedDataByInstances[$i])) { $this->fail('Data instance ' . $i . ' not found for test' . $testName); } $this->assertData($expectedDataByInstances[$i], $ins->getDataStore()->getData()); $i++; } } } } /** * Assert that $data contains the expected $subset * * @param mixed $subset * @param mixed $data * @param string $message * @param bool $skip * * @return mixed */ private function assertData($subset, $data, $message = 'data', $skip = false) { if (!is_array($subset) || !is_array($data)) { if ($skip) { return $subset == $data; } else { return $this->assertEquals($subset, $data, "{$message} does not match " . \json_encode($subset)); } } foreach ($subset as $key => $value) { if (substr($key, 0, 1) !== '*') { $this->assertData($value, $data[$key], "{$message}.{$key}"); unset($subset[$key]); unset($data[$key]); } } foreach ($subset as $key => $value) { foreach ($data as $key1 => $value1) { if ($this->assertData($value, $value1, "{$message}.{$key}", true)) { unset($subset[$key]); unset($data[$key1]); break; } } } if ($skip) { return count($subset) === 0; } else { $this->assertCount(0, $subset, "{$message} does not match"); } } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/ExclusiveGatewayTest.php
tests/Feature/Engine/ExclusiveGatewayTest.php
<?php namespace Tests\Feature\Engine; use Exception; use ProcessMaker\Nayra\Bpmn\DefaultTransition; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface; use ProcessMaker\Nayra\Contracts\Bpmn\TransitionInterface; use ProcessMaker\Nayra\Exceptions\RuntimeException; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Test transitions */ class ExclusiveGatewayTest extends EngineTestCase { /** * Creates a process where the exclusive gateway has conditioned and simple transitions * * @return \ProcessMaker\Models\Process */ private function createProcessWithExclusiveGateway() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createExclusiveGateway(); $activityA = $this->repository->createActivity(); $activityB = $this->repository->createActivity(); $activityC = $this->repository->createActivity(); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB) ->addActivity($activityC); $process ->addGateway($gatewayA); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createConditionedFlowTo($activityA, function ($data) { return $data['A'] == '1'; }, false, $this->repository) ->createConditionedFlowTo($activityB, function ($data) { return $data['B'] == '1'; }, false, $this->repository) ->createFlowTo($activityC, $this->repository); $activityA->createFlowTo($end, $this->repository); $activityB->createFlowTo($end, $this->repository); $activityC->createFlowTo($end, $this->repository); return $process; } /** * Creates a process with default transitions * * @return \ProcessMaker\Models\Process */ private function createProcessWithExclusiveGatewayAndDefaultTransition() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createExclusiveGateway(); $activityA = $this->repository->createActivity(); $activityB = $this->repository->createActivity(); $activityC = $this->repository->createActivity(); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB) ->addActivity($activityC); $process ->addGateway($gatewayA); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createConditionedFlowTo($activityA, function ($data) { return $data['A'] == '1'; }, false, $this->repository) ->createConditionedFlowTo($activityB, function ($data) { return $data['B'] == '1'; }, false, $this->repository) ->createConditionedFlowTo($activityC, function ($data) { return true; }, true, $this->repository); $activityA->createFlowTo($end, $this->repository); $activityB->createFlowTo($end, $this->repository); $activityC->createFlowTo($end, $this->repository); return $process; } /** * Parallel diverging Exclusive converging * ┌─────────┐ * ┌─→│activityA│─┐ *  ○─→╱╲─┘ └─────────┘ └─→╱╲ ┌─────────┐ * ╲╱─┐ ┌─────────┐ ┌─→╲╱─→│activityC│─→● * A └─→│activityB│─┘ B └─────────┘ * parallel └─────────┘ exclusive * * @return \ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface */ private function createParallelDivergingExclusiveConverging() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createParallelGateway(); $activityA = $this->repository->createActivity(); $activityB = $this->repository->createActivity(); $activityC = $this->repository->createActivity(); $gatewayB = $this->repository->createExclusiveGateway(); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB) ->addActivity($activityC); $process ->addGateway($gatewayA) ->addGateway($gatewayB); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createFlowTo($activityA, $this->repository) ->createFlowTo($activityB, $this->repository); $activityA->createFlowTo($gatewayB, $this->repository); $activityB->createFlowTo($gatewayB, $this->repository); $gatewayB->createFlowTo($activityC, $this->repository); $activityC->createFlowTo($end, $this->repository); return $process; } /** * Tests the basic functionality of the exclusive gateway */ public function testExclusiveGateway() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('A', '2'); $dataStore->putData('B', '1'); //Load the process $process = $this->createProcessWithExclusiveGateway(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activityB = $process->getActivities()->item(1); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); $tokenB = $activityB->getTokens($instance)->item(0); $activityB->complete($tokenB); //the run to next state should go false when the max steps is reached. $this->assertFalse($this->engine->runToNextState(1)); } /** * Tests that the correct events are triggered when the first flow has a condition evaluated to true */ public function testExclusiveGatewayFirstConditionTrue() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('A', '1'); $dataStore->putData('B', '1'); //Load the process $process = $this->createProcessWithExclusiveGatewayAndDefaultTransition(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); } /** * Tests the exclusive gateway triggering the default transition */ public function testExclusiveGatewayWithDefaultTransition() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('A', '2'); $dataStore->putData('B', '2'); //Load the process $process = $this->createProcessWithExclusiveGatewayAndDefaultTransition(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activityC = $process->getActivities()->item(2); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, DefaultTransition::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Completes the Activity C $tokenC = $activityC->getTokens($instance)->item(0); $activityC->complete($tokenC); //the run to next state should go false when the max steps is reached. $this->assertFalse($this->engine->runToNextState(1)); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed and process is ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Parallel diverging Exclusive converging * * A process with three tasks, a diverging parallelGateway and a converging exclusiveGateway. * Two of the tasks are executed in parallel and then merged by the exclusiveGateway. * As a result, the task following the exclusiveGateway should be followed twice. */ public function testParallelDivergingExclusiveConverging() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); //Load the process $process = $this->createParallelDivergingExclusiveConverging(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activityA = $process->getActivities()->item(0); $activityB = $process->getActivities()->item(1); $activityC = $process->getActivities()->item(2); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Completes the Activity A $tokenA = $activityA->getTokens($instance)->item(0); $activityA->complete($tokenA); //the run to next state should go false when the max steps is reached. $this->assertFalse($this->engine->runToNextState(1)); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Completes the Activity B $tokenB = $activityB->getTokens($instance)->item(0); $activityB->complete($tokenB); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity B is closed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Assertion: ActivityC has two tokens. $this->assertEquals(2, $activityC->getTokens($instance)->count()); //Completes the Activity C for the first token $tokenC = $activityC->getTokens($instance)->item(0); $activityC->complete($tokenC); $this->engine->runToNextState(); //Completes the Activity C for the next token $tokenC = $activityC->getTokens($instance)->item(0); $activityC->complete($tokenC); $this->engine->runToNextState(); //Assertion: ActivityC has no tokens. $this->assertEquals(0, $activityC->getTokens($instance)->count()); //Assertion: ActivityC was completed and closed per each token, then the end event was triggered twice. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test exclusive gateway with custom data */ public function testConditionalExclusiveParameters() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/ExclusiveGateway.bpmn'); //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('Age', '8'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('ExclusiveGatewayProcess'); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get start event and event definition references $start = $bpmnRepository->getStartEvent('StartEvent'); $activity1 = $bpmnRepository->getStartEvent('Exclusive1'); //Start the process $start->start($instance); $this->engine->runToNextState(); // Advance the first activity $token0 = $activity1->getTokens($instance)->item(0); $activity1->complete($token0); $this->engine->runToNextState(); //Assertion: Process started, activity completed, gateway executed, script activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); } /** * Test runtime error when evaluating an exclusive gateway */ public function testExclusiveGatewayMissingVariable() { // Create a data store with data. $dataStore = $this->repository->createDataStore(); // Load the process $process = $this->createProcessWithExclusiveGateway(); $instance = $this->engine->createExecutionInstance($process, $dataStore); // simulate a formal expression runtime error when evaluating a gateway condition $gatewayA = $process->getGateways()->item(0); $gatewayA->getConditionedTransitions()->item(0)->setCondition(function ($data) { throw new Exception('Variable A is missing'); }); // Get References $start = $process->getEvents()->item(0); // Expect a RuntimeException $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Variable A is missing'); // Run the process $start->start($instance); $this->engine->runToNextState(); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/MultiInstanceTest.php
tests/Feature/Engine/MultiInstanceTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface; use ProcessMaker\Nayra\Contracts\Engine\ExecutionInstanceInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Test a terminate event. */ class MultiInstanceTest extends EngineTestCase { /** * Test a parallel multiinstance */ public function testMultiInstanceParallelLoopCardinality() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/../Patterns/files/MultiInstance_Parallel.bpmn'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('MultiInstance_Parallel'); // Get 'start' activity of the process $activity = $bpmnRepository->getActivity('start'); // Get 'MultiInstanceTask' activity of the process $miTask = $bpmnRepository->getActivity('MultiInstanceTask'); // Start the process $instance = $process->call(); $this->engine->runToNextState(); // Assertion: A process has started. $this->assertEquals(1, $process->getInstances()->count()); // Assertion: The process has started and the first activity was activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Complete the first activity. $token = $activity->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first activity was completed then 3 script task are activated $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the first MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first MI task was completed 2 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the second MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The second MI task was completed 1 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the third MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The third MI task was completed, all MI token are closed, then continue to next task $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); } /** * Test MI script task with exception */ public function testMultiInstanceParallelLoopCardinalityScriptException() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/../Patterns/files/MultiInstance_Parallel.bpmn'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('MultiInstance_Parallel'); // Get 'start' activity of the process $activity = $bpmnRepository->getActivity('start'); // Get 'MultiInstanceTask' activity of the process $miTask = $bpmnRepository->getActivity('MultiInstanceTask'); // Start the process $instance = $process->call(); $this->engine->runToNextState(); // Assertion: A process has started. $this->assertEquals(1, $process->getInstances()->count()); // Assertion: The process has started and the first activity was activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Complete the first activity. $token = $activity->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first activity was completed then 3 script task are activated $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the first MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first MI task was completed 2 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the second MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The second MI task was completed 1 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the third MI activity. $token = $miTask->getTokens($instance)->item(0); $token->setStatus(ScriptTaskInterface::TOKEN_STATE_FAILING); $this->engine->runToNextState(); // Assertion: Fail third MI task $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_EXCEPTION, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Close failing task instance. $token->setStatus(ScriptTaskInterface::TOKEN_STATE_CLOSED); $this->engine->runToNextState(); // Assertion: The third MI task was cancelled, the MI Activity hangs because it could not close all the parallel instances $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_CANCELLED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); } /** * Test MI task cancel instance */ public function testMultiInstanceParallelLoopCardinalityCancellInstance() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/../Patterns/files/MultiInstance_Parallel.bpmn'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('MultiInstance_Parallel'); // Get 'start' activity of the process $activity = $bpmnRepository->getActivity('start'); // Get 'multiInstanceTask' activity of the process $miTask = $bpmnRepository->getActivity('MultiInstanceTask'); // Start the process $instance = $process->call(); $this->engine->runToNextState(); // Assertion: A process has started. $this->assertEquals(1, $process->getInstances()->count()); // Assertion: The process has started and the first activity was activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Complete the first activity. $token = $activity->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first activity was completed then 3 script task are activated $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the first MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first MI task was completed 2 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the second MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The second MI task was completed 1 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Cancel the third MI activity. $token = $miTask->getTokens($instance)->item(0); $token->setStatus(ScriptTaskInterface::TOKEN_STATE_CLOSED); $this->engine->runToNextState(); // Assertion: The third MI task was cancelled, the MI Activity hangs because it could not close all the parallel instances $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_CANCELLED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); } /** * Test a sequential multiinstance */ public function testMultiInstanceSequentialLoopCardinality() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/../Patterns/files/MultiInstance_AllBehavior.bpmn'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('MultiInstance_AllBehavior'); // Get 'start' activity of the process $activity = $bpmnRepository->getActivity('start'); // Get 'MultiInstanceTask' activity of the process $miTask = $bpmnRepository->getActivity('multiInstanceTask'); // Start the process $instance = $process->call(); $this->engine->runToNextState(); // Assertion: A process has started. $this->assertEquals(1, $process->getInstances()->count()); // Assertion: The process has started and the first activity was activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Complete the first activity. $token = $activity->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first activity was completed then 3 script task are activated $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the first MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first MI task was completed 2 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the second MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The second MI task was completed 1 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the third MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The third MI task was completed, closed, then continue to next task $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); } /** * Test MI script task with exception */ public function testMultiInstanceSequentialLoopCardinalityScriptException() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/../Patterns/files/MultiInstance_AllBehavior.bpmn'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('MultiInstance_AllBehavior'); // Get 'start' activity of the process $activity = $bpmnRepository->getActivity('start'); // Get 'multiInstanceTask' activity of the process $miTask = $bpmnRepository->getActivity('multiInstanceTask'); // Start the process $instance = $process->call(); $this->engine->runToNextState(); // Assertion: A process has started. $this->assertEquals(1, $process->getInstances()->count()); // Assertion: The process has started and the first activity was actioned $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Complete the first activity. $token = $activity->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first activity was completed then 3 script task are activated $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the first MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first MI task was completed 2 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the second MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The second MI task was completed 1 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the third MI activity. $token = $miTask->getTokens($instance)->item(0); $token->setStatus(ScriptTaskInterface::TOKEN_STATE_FAILING); $this->engine->runToNextState(); // Assertion: Fail third MI task, the MI Activity hangs until the failing instance is closed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_EXCEPTION, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Close failing task instance. $token->setStatus(ScriptTaskInterface::TOKEN_STATE_CLOSED); $this->engine->runToNextState(); // Assertion: The third and last MI Activity is cancelled, then the process is closed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_CANCELLED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test MI task cancel instance */ public function testMultiInstanceSequentialLoopCardinalityCancelInstance() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/../Patterns/files/MultiInstance_AllBehavior.bpmn'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('MultiInstance_AllBehavior'); // Get 'start' activity of the process $activity = $bpmnRepository->getActivity('start'); // Get 'multiInstanceTask' activity of the process $miTask = $bpmnRepository->getActivity('multiInstanceTask'); // Start the process $instance = $process->call(); $this->engine->runToNextState(); // Assertion: A process has started. $this->assertEquals(1, $process->getInstances()->count()); // Assertion: The process has started and the first activity was activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Complete the first activity. $token = $activity->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first activity was completed then 3 script task are activated $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the first MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first MI task was completed 2 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the second MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The second MI task was completed 1 pending $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Cancel the third MI activity. $token = $miTask->getTokens($instance)->item(0); $token->setStatus(ScriptTaskInterface::TOKEN_STATE_CLOSED); $this->engine->runToNextState(); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Assertion: The third and last MI task was cancelled, then the process is completed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_CANCELLED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Tests a process with MI as marker but not executable * * @return void */ public function testUnspecifiedLoop() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/MultiInstance_DocumentOnly.bpmn'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('MultiInstance_DocumentOnly'); // Get 'start' activity of the process $activity = $bpmnRepository->getActivity('start'); // Get 'MultiInstanceTask' activity of the process $miTask = $bpmnRepository->getActivity('MultiInstanceTask'); // Get 'last task' activity $lastTask = $bpmnRepository->getActivity('node_8'); // Start the process $instance = $process->call(); $this->engine->runToNextState(); // Assertion: A process has started. $this->assertEquals(1, $process->getInstances()->count()); // Assertion: The process has started and the first activity was activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Complete the first activity. $token = $activity->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first activity was completed then only 1 task are activated (as a normal task) $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the MI activity. $token = $miTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The MI task was completed and next task is activated $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the last task $token = $lastTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The last task was completed and process is completed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Tests a multi-instance with input-output data * * @return void */ public function testMultiInstanceInputOutput() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/MultiInstance_InputOutput.bpmn'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('MultiInstance_Process'); // Get 'start' activity of the process $activity = $bpmnRepository->getActivity('start'); // Get 'MultiInstanceTask' activity of the process $miTask = $bpmnRepository->getScriptTask('MultiInstanceTask'); // Get 'last task' activity $lastTask = $bpmnRepository->getActivity('end'); // Start the process $instance = $process->call(); $instance->getDataStore()->putData('users', [ ['name' => 'Marco', 'age' => 20], ['name' => 'Jonas', 'age' => 23], ]); $this->engine->runToNextState(); // Assertion: A process has started. $this->assertEquals(1, $process->getInstances()->count()); // Assertion: The process has started and the first activity was activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Complete the first activity. $token = $activity->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The first activity was completed then 2 script task are started $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the MI activity. $token1 = $miTask->getTokens($instance)->item(0); $token2 = $miTask->getTokens($instance)->item(1); $miTask->runScript($token1); $miTask->runScript($token2); $this->engine->runToNextState(); // Assertion: The MI task was completed and next task is activated $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Complete the last task $token = $lastTask->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); // Assertion: The last task was completed and process is completed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); // Assertion: The internal data of the LoopCharacteristics are stored in the instance data. $this->verifyStoredInstanceData($instance); // Assertion: Output data 'result' should contain the expected result $data = $instance->getDataStore()->getData(); $this->assertArrayHasKey('result', $data); $this->assertEquals([ [ 'name' => 'Marco', 'age' => 21, ], [ 'name' => 'Jonas', 'age' => 24, ],
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
true
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/ActivityTest.php
tests/Feature/Engine/ActivityTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Bpmn\Models\Activity; use ProcessMaker\Nayra\Contracts\Bpmn\BoundaryEventInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; use Tests\Feature\Engine\EngineTestCase; /** * Tests the activity collection */ class ActivityTest extends EngineTestCase { /** * Test get boundary events from standalone activity */ public function testGetEmptyBoundaryEvents() { $element = new Activity(); $this->assertCount(0, $element->getBoundaryEvents()); } /** * Test get boundary events from call activity with boundary events */ public function testGetBoundaryEvents() { $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Error_BoundaryEvent_CallActivity.bpmn'); // Get boundary events of call activity _7 $element = $bpmnRepository->getCallActivity('_7'); $boundaryEvents = $element->getBoundaryEvents(); // Assertion: There is one boundary event with id=_12 $this->assertCount(1, $boundaryEvents); $boundaryEvent = $boundaryEvents->item(0); $this->assertInstanceOf(BoundaryEventInterface::class, $boundaryEvent); $this->assertEquals('_12', $boundaryEvent->getId()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/LoadFromBPMNFileTest.php
tests/Feature/Engine/LoadFromBPMNFileTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\CallableElementInterface; use ProcessMaker\Nayra\Contracts\Bpmn\CatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ConditionalEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DataInputInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DataOutputInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ErrorInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ExclusiveGatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\FlowElementInterface; use ProcessMaker\Nayra\Contracts\Bpmn\FlowInterface; use ProcessMaker\Nayra\Contracts\Bpmn\FlowNodeInterface; use ProcessMaker\Nayra\Contracts\Bpmn\FormalExpressionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\InclusiveGatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\InputSetInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateCatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ItemDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\LaneInterface; use ProcessMaker\Nayra\Contracts\Bpmn\LaneSetInterface; use ProcessMaker\Nayra\Contracts\Bpmn\MessageEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\MessageFlowInterface; use ProcessMaker\Nayra\Contracts\Bpmn\MessageInterface; use ProcessMaker\Nayra\Contracts\Bpmn\OperationInterface; use ProcessMaker\Nayra\Contracts\Bpmn\OutputSetInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ParallelGatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface; use ProcessMaker\Nayra\Contracts\Bpmn\SignalEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\TerminateEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ThrowEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\TimerEventDefinitionInterface; use ProcessMaker\Nayra\Exceptions\ElementNotFoundException; use ProcessMaker\Nayra\Exceptions\ElementNotImplementedException; use ProcessMaker\Nayra\Exceptions\NamespaceNotImplementedException; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Test load of process from BPMN files. */ class LoadFromBPMNFileTest extends EngineTestCase { /** * Test parallel gateway loaded from BPMN file. */ public function testParallelGateway() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/ParallelGateway.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('ParallelGateway'); //Create a data store with data. $dataStore = $this->repository->createDataStore(); //Create a process instance $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References by id $start = $process->getEvents()->item(0); $startActivity = $bpmnRepository->getScriptTask('start'); $activityA = $bpmnRepository->getScriptTask('ScriptTask_1'); $activityB = $bpmnRepository->getScriptTask('ScriptTask_2'); $endActivity = $bpmnRepository->getScriptTask('end'); //Assertion: Check reference to BpmnDocument $this->assertEquals($bpmnRepository, $start->getOwnerDocument()); $this->assertEquals($bpmnRepository, $startActivity->getOwnerDocument()); $this->assertEquals($bpmnRepository, $activityA->getOwnerDocument()); $this->assertEquals($bpmnRepository, $activityB->getOwnerDocument()); $this->assertEquals($bpmnRepository, $endActivity->getOwnerDocument()); //Assertion: Check reference to BPMN element $this->assertEquals($bpmnRepository->findElementById('StartEvent'), $start->getBpmnElement()); $this->assertEquals($bpmnRepository->findElementById('start'), $startActivity->getBpmnElement()); //Start the process $start->start($instance); $this->engine->runToNextState(); //Completes the Activity 0 $token0 = $startActivity->getTokens($instance)->item(0); $startActivity->complete($token0); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); //Completes the Activity A $tokenA = $activityA->getTokens($instance)->item(0); $activityA->complete($tokenA); //the run to next state should go false when the max steps is reached. $this->assertFalse($this->engine->runToNextState(1)); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); //Completes the Activity B $tokenB = $activityB->getTokens($instance)->item(0); $activityB->complete($tokenB); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity B is closed and process is ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); //Assertion: ActivityC has one token. $this->assertEquals(1, $endActivity->getTokens($instance)->count()); //Completes the Activity C $tokenC = $endActivity->getTokens($instance)->item(0); $endActivity->complete($tokenC); $this->engine->runToNextState(); //Assertion: ActivityC has no tokens. $this->assertEquals(0, $endActivity->getTokens($instance)->count()); //Assertion: ActivityC was completed and closed, then the process has ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test inclusive gateway loaded from BPMN file. */ public function testInclusiveGatewayWithDefault() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/InclusiveGateway_Default.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('InclusiveGateway_Default'); //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('a', 1); $dataStore->putData('b', 1); //Get References by id $start = $bpmnRepository->getStartEvent('StartEvent'); $startActivity = $bpmnRepository->getScriptTask('start'); $activityA = $bpmnRepository->getScriptTask('ScriptTask_1'); $activityB = $bpmnRepository->getScriptTask('ScriptTask_2'); $default = $bpmnRepository->getScriptTask('ScriptTask_3'); $endActivity = $bpmnRepository->getEndEvent('end'); //Load the process $instance = $this->engine->createExecutionInstance($process, $dataStore); //Start the process $start->start($instance); $this->engine->runToNextState(); //Completes the Activity 0 $token0 = $startActivity->getTokens($instance)->item(0); $startActivity->complete($token0); $this->engine->runToNextState(); $this->assertEquals(0, $startActivity->getTokens($instance)->count()); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); //Completes the Activity A $tokenA = $activityA->getTokens($instance)->item(0); $activityA->complete($tokenA); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); //Completes the Activity B $tokenB = $activityB->getTokens($instance)->item(0); $activityB->complete($tokenB); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed and process is ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); //Completes the End Activity $endToken = $endActivity->getTokens($instance)->item(0); $endActivity->complete($endToken); $this->engine->runToNextState(); //Assertion: Verify the activity is closed and end event is triggered. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test to load a collaboration. */ public function testLoadCollaborationWithMultipleProcesses() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadBPMNElements.bpmn'); //Get a Collaboration $collaboration = $bpmnRepository->getCollaboration('COLLABORATION_1'); //Assertion: Verify the number of message flows in the Collaboration $this->assertEquals(1, $collaboration->getMessageFlows()->count()); //Assertion: Verify the number of participants in the Collaboration $this->assertEquals(3, $collaboration->getParticipants()->count()); //Get the first process $processOne = $bpmnRepository->getProcess('PROCESS_1'); //Assertion: Verify the number of activities in the process one $this->assertEquals(7, $processOne->getActivities()->count()); //Assertion: Verify the number of gateways in the process one $this->assertEquals(2, $processOne->getGateways()->count()); //Assertion: Verify the number of gateways in the process one $this->assertEquals(5, $processOne->getEvents()->count()); //Get the intermediate throw event $throwEvent = $bpmnRepository->getIntermediateThrowEvent('_20'); //Assertion: Verify the number of event definitions $this->assertEquals(1, $throwEvent->getEventDefinitions()->count()); //Assertion: Verify it is an MessageEventDefinitionInterface $eventDefinition = $throwEvent->getEventDefinitions()->item(0); $this->assertInstanceOf(MessageEventDefinitionInterface::class, $eventDefinition); //Assertion: Verify the payload is a Message $this->assertInstanceOf(MessageInterface::class, $eventDefinition->getPayload()); //Assertion: Verify the operation $operation = $eventDefinition->getOperation(); $this->assertInstanceOf(OperationInterface::class, $operation); //Assertion: Verify the operation implementation $this->assertEquals('foo.service.url', $operation->getImplementation()); //Assertion: Verify the input message of the operation. $this->assertInstanceOf(MessageInterface::class, $operation->getInMessage()->item(0)); //Assertion: Verify the output message of the operation. $this->assertInstanceOf(MessageInterface::class, $operation->getOutMessage()->item(0)); //Assertion: Verify the output message of the operation. $error = $operation->getErrors()->item(0); $this->assertInstanceOf(ErrorInterface::class, $error); //Assertion: Verify error name. $this->assertEquals('BusinessError', $error->getName()); //Assertion: Verify error code. $this->assertEquals('4040', $error->getErrorCode()); //Get the third process as callable element $processThree = $bpmnRepository->getCallableElement('PROCESS_3'); //Assertion: Verify it is a callable element. $this->assertInstanceOf(CallableElementInterface::class, $processThree); //Get a catch event element $element = $bpmnRepository->getCatchEvent('_50'); //Assertion: Verify it is a catch event. $this->assertInstanceOf(CatchEventInterface::class, $element); //Get a data input element $element = $bpmnRepository->getDataInput('Din_20_1'); //Assertion: Verify it is a data input. $this->assertInstanceOf(DataInputInterface::class, $element); $this->assertInstanceOf(ItemDefinitionInterface::class, $element->getItemSubject()); //Get a data input collection element $element = $bpmnRepository->getDataInput('Din_20_2'); //Assertion: Verify it is a data input. $this->assertInstanceOf(DataInputInterface::class, $element); $this->assertEquals(true, $element->isCollection()); //Get a data output element $element = $bpmnRepository->getDataOutput('Dout_22_1'); //Assertion: Verify it is a data output. $this->assertInstanceOf(DataOutputInterface::class, $element); $this->assertInstanceOf(ItemDefinitionInterface::class, $element->getItemSubject()); //Get a data output collection element $element = $bpmnRepository->getDataOutput('Dout_22_2'); //Assertion: Verify it is a data output. $this->assertInstanceOf(DataOutputInterface::class, $element); $this->assertEquals(true, $element->isCollection()); //Get a data store element $element = $bpmnRepository->getDataStore('DS_1'); //Assertion: Verify it is a data store. $this->assertInstanceOf(DataStoreInterface::class, $element); //Get a event definition element $element = $bpmnRepository->getEventDefinition('_4_ED_1'); //Assertion: Verify it is a event definition. $this->assertInstanceOf(EventDefinitionInterface::class, $element); //Get a event element $element = $bpmnRepository->getEvent('_50'); //Assertion: Verify it is a event. $this->assertInstanceOf(EventInterface::class, $element); //Get a exclusive gateway element $element = $bpmnRepository->getExclusiveGateway('_15'); //Assertion: Verify it is a exclusive gateway. $this->assertInstanceOf(ExclusiveGatewayInterface::class, $element); //Get a flow element element $element = $bpmnRepository->getFlowElement('_50'); //Assertion: Verify it is a flow element. $this->assertInstanceOf(FlowElementInterface::class, $element); //Get a flow element $element = $bpmnRepository->getFlow('_10'); //Assertion: Verify it is a flow. $this->assertInstanceOf(FlowInterface::class, $element); //Get a flow node element $element = $bpmnRepository->getFlowNode('_50'); //Assertion: Verify it is a flow node. $this->assertInstanceOf(FlowNodeInterface::class, $element); //Get a formal expression element $element = $bpmnRepository->getFormalExpression('TD_EX_1'); //Assertion: Verify it is a formal expression. $this->assertInstanceOf(FormalExpressionInterface::class, $element); //Get a gateway element $element = $bpmnRepository->getGateway('_30'); //Assertion: Verify it is a gateway. $this->assertInstanceOf(GatewayInterface::class, $element); //Get a inclusive gateway element $element = $bpmnRepository->getInclusiveGateway('_30'); //Assertion: Verify it is a inclusive gateway. $this->assertInstanceOf(InclusiveGatewayInterface::class, $element); //Get a input set element $element = $bpmnRepository->getInputSet('IS_1'); //Assertion: Verify it is a input set. $this->assertInstanceOf(InputSetInterface::class, $element); //Assertion: Verify the input set content. $this->assertEquals(2, $element->getDataInputs()->count()); //Get a intermediate catch event element $element = $bpmnRepository->getIntermediateCatchEvent('_50'); //Assertion: Verify it is a intermediate catch event. $this->assertInstanceOf(IntermediateCatchEventInterface::class, $element); //Get a lane element $element = $bpmnRepository->getLane('_59'); //Assertion: Verify it is a lane. $this->assertInstanceOf(LaneInterface::class, $element); //Get a lane set element $element = $bpmnRepository->getLaneSet('LS_59'); //Assertion: Verify it is a lane set. $this->assertInstanceOf(LaneSetInterface::class, $element); //Get a message event definition element $element = $bpmnRepository->getMessageEventDefinition('_22_ED_1'); //Assertion: Verify it is a message event definition. $this->assertInstanceOf(MessageEventDefinitionInterface::class, $element); //Get a message flow element $element = $bpmnRepository->getMessageFlow('_71'); //Assertion: Verify it is a message flow. $this->assertInstanceOf(MessageFlowInterface::class, $element); //Get a operation element $element = $bpmnRepository->getOperation('IF_1_O_1'); //Assertion: Verify it is a operation. $this->assertInstanceOf(OperationInterface::class, $element); //Get a output set element $element = $bpmnRepository->getOutputSet('OS_1'); //Assertion: Verify it is a output set. $this->assertInstanceOf(OutputSetInterface::class, $element); //Assertion: Verify the output set content. $this->assertEquals(2, $element->getDataOutputs()->count()); //Get a parallel gateway element $element = $bpmnRepository->getParallelGateway('_38'); //Assertion: Verify it is a parallel gateway. $this->assertInstanceOf(ParallelGatewayInterface::class, $element); //Get a signal event definition element $element = $bpmnRepository->getSignalEventDefinition('_50_ED_1'); //Assertion: Verify it is a signal event definition. $this->assertInstanceOf(SignalEventDefinitionInterface::class, $element); //Get a terminate event definition element $element = $bpmnRepository->getTerminateEventDefinition('_53_ED_1'); //Assertion: Verify it is a terminate event definition. $this->assertInstanceOf(TerminateEventDefinitionInterface::class, $element); //Get a throw event element $element = $bpmnRepository->getThrowEvent('_20'); //Assertion: Verify it is a throw event. $this->assertInstanceOf(ThrowEventInterface::class, $element); //Get a timer event definition element $element = $bpmnRepository->getTimerEventDefinition('_72_ED_1'); //Assertion: Verify it is a timer event definition. $this->assertInstanceOf(TimerEventDefinitionInterface::class, $element); //Get a conditional event definition element $element = $bpmnRepository->getConditionalEventDefinition('_23_ED_1'); //Assertion: Verify it is a timer event definition. $this->assertInstanceOf(ConditionalEventDefinitionInterface::class, $element); } /** * Test to set a custom element mapping. */ public function testUseACustomElementMapping() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->setBpmnElementMapping('http://www.processmaker.org/spec/PM/20100607/MODEL', 'webEntry', [ StartEventInterface::class, [ FlowNodeInterface::BPMN_PROPERTY_INCOMING => ['n', [BpmnDocument::BPMN_MODEL, FlowNodeInterface::BPMN_PROPERTY_INCOMING]], FlowNodeInterface::BPMN_PROPERTY_OUTGOING => ['n', [BpmnDocument::BPMN_MODEL, FlowNodeInterface::BPMN_PROPERTY_OUTGOING]], StartEventInterface::BPMN_PROPERTY_EVENT_DEFINITIONS => ['n', EventDefinitionInterface::class], ], ]); $bpmnRepository->load(__DIR__ . '/files/CustomElements.bpmn'); $task = $bpmnRepository->getActivity('_2'); $this->assertEquals('Web Entry', $task->getName()); } /** * Test to load custom elements. */ public function testCustomNameSpaceNotImplemented() { $this->expectException(NamespaceNotImplementedException::class); //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/CustomElements.bpmn'); $bpmnRepository->getActivity('_2'); } /** * Test to load custom elements. */ public function testCustomElementNotImplemented() { //Assertion: An ElementNotImplementedException expected $this->expectException(ElementNotImplementedException::class); //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->setBpmnElementMapping('http://www.processmaker.org/spec/PM/20100607/MODEL', 'task', [ ActivityInterface::class, [ FlowNodeInterface::BPMN_PROPERTY_INCOMING => ['n', [BpmnDocument::BPMN_MODEL, FlowNodeInterface::BPMN_PROPERTY_INCOMING]], FlowNodeInterface::BPMN_PROPERTY_OUTGOING => ['n', [BpmnDocument::BPMN_MODEL, FlowNodeInterface::BPMN_PROPERTY_OUTGOING]], ], ]); $bpmnRepository->load(__DIR__ . '/files/CustomElements.bpmn'); //Try to get custom element $bpmnRepository->getActivity('_2'); } /** * Test skip loading of non implemented elements. */ public function testSkipCustomElementNotImplemented() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setSkipElementsNotImplemented(true); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->setBpmnElementMapping('http://www.processmaker.org/spec/PM/20100607/MODEL', 'task', [ ActivityInterface::class, [ FlowNodeInterface::BPMN_PROPERTY_INCOMING => ['n', [BpmnDocument::BPMN_MODEL, FlowNodeInterface::BPMN_PROPERTY_INCOMING]], FlowNodeInterface::BPMN_PROPERTY_OUTGOING => ['n', [BpmnDocument::BPMN_MODEL, FlowNodeInterface::BPMN_PROPERTY_OUTGOING]], ], ]); $bpmnRepository->load(__DIR__ . '/files/CustomElements.bpmn'); //Try to get custom element $process = $bpmnRepository->getActivity('PROCESS_1'); // Assertion: Process instance is loaded $this->assertNotEmpty($process); $this->assertInstanceOf(ProcessInterface::class, $process); } /** * Test to get a missing BPMN element. */ public function testGetMissingElement() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadBPMNElements.bpmn'); //Try to get an non existing element //Assertion: An ElementNotImplementedException expected $this->expectException(ElementNotFoundException::class); $bpmnRepository->getCollaboration('NON_EXIXTING_ELEMENT'); } /** * Test if an BPMN element exists. */ public function testBPMNElementExists() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadBPMNElements.bpmn'); //Test an existing element $exists = $bpmnRepository->hasElementInstance('PROCESS_1'); //Assertion: hasElementInstance('PROCESS_1') must return true $this->assertTrue($exists); //Test an existing element $doesNotExists = $bpmnRepository->hasElementInstance('DOES_NOT_EXISTS'); //Assertion: hasElementInstance('DOES_NOT_EXISTS') must return false $this->assertFalse($doesNotExists); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/IntermediateTimerEventTest.php
tests/Feature/Engine/IntermediateTimerEventTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateCatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\TimerEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Engine\JobManagerInterface; use ProcessMaker\Test\Models\FormalExpression; /** * Test intermediate timer events */ class IntermediateTimerEventTest extends EngineTestCase { /** * Creates a process with an intermediate timer event * * @return \ProcessMaker\Models\Process */ public function createStartTimerEventProcess() { $process = $this->repository->createProcess(); $process->setEngine($this->engine); //elements $start = $this->repository->createStartEvent(); $timerEvent = $this->repository->createIntermediateCatchEvent(); $activityA = $this->repository->createActivity(); $activityB = $this->repository->createActivity(); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB); $process ->addEvent($start) ->addEvent($timerEvent) ->addEvent($end); //flows $start->createFlowTo($activityA, $this->repository); $activityA->createFlowTo($timerEvent, $this->repository); $timerEvent->createFlowTo($activityB, $this->repository); $activityB->createFlowTo($end, $this->repository); return $process; } /** * Tests that a intermediate timer event that uses duration, sends the events to schedules the job */ public function testIntermediateTimerEventWithDuration() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); //Load the process $process = $this->createStartTimerEventProcess(); //Get references to the process elements $start = $process->getEvents()->item(0); $activityA = $process->getActivities()->item(0); $activityB = $process->getActivities()->item(1); $timerEvent = $process->getEvents()->item(1); $this->addTimerEventDefinition($timerEvent, 'duration'); //create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); //run the process $start->start($instance); $this->engine->runToNextState(); //Complete the first task $token = $activityA->getTokens($instance)->item(0); $activityA->complete($token); $this->engine->runToNextState(); //Assertion: one token should arrive to the intermediate timer event $this->assertTrue($timerEvent->getTokens($instance)->count() === 1); //Assertion: verify that the event schedule duration is sent to the job manager $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, JobManagerInterface::EVENT_SCHEDULE_DURATION, ]); //force the dispatch of the required job simulation and execute call $timerEvent->execute($timerEvent->getEventDefinitions()->item(0), $instance); $this->engine->runToNextState(); //Assertion: the process should continue to the next task $this->assertEvents([ IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CATCH, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_PASSED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); } /** * Tests that a intermediate timer event that uses cycles, sends the events to schedules the job */ public function testIntermediateTimerEventWithCycle() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); //Load the process $process = $this->createStartTimerEventProcess(); //Get references to the process elements $start = $process->getEvents()->item(0); $activityA = $process->getActivities()->item(0); $activityB = $process->getActivities()->item(1); $timerEvent = $process->getEvents()->item(1); $this->addTimerEventDefinition($timerEvent, 'cycle'); //create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); //run the process $start->start($instance); $this->engine->runToNextState(); //Complete the first task $token = $activityA->getTokens($instance)->item(0); $activityA->complete($token); $this->engine->runToNextState(); //Assertion: one token should arrive to the intermediate timer event $this->assertTrue($timerEvent->getTokens($instance)->count() === 1); //Assertion: verify that the event schedule duration is sent to the job manager $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, JobManagerInterface::EVENT_SCHEDULE_CYCLE, ]); //force the dispatch of the required job simulation and execute call $timerEvent->execute($timerEvent->getEventDefinitions()->item(0), $instance); $this->engine->runToNextState(); //Assertion: the process should continue to the next task $this->assertEvents([ IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CATCH, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_PASSED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); } /** * Tests that a intermediate timer event that uses dates, sends the events to schedules the job */ public function testIntermediateTimerEventWithDate() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); //Load the process $process = $this->createStartTimerEventProcess(); //Get references to the process elements $start = $process->getEvents()->item(0); $activityA = $process->getActivities()->item(0); $activityB = $process->getActivities()->item(1); $timerEvent = $process->getEvents()->item(1); $this->addTimerEventDefinition($timerEvent, 'date'); //create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); //run the process $start->start($instance); $this->engine->runToNextState(); //Complete the first task $token = $activityA->getTokens($instance)->item(0); $activityA->complete($token); $this->engine->runToNextState(); //Assertion: one token should arrive to the intermediate timer event $this->assertTrue($timerEvent->getTokens($instance)->count() === 1); //Assertion: verify that the event schedule duration is sent to the job manager $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, JobManagerInterface::EVENT_SCHEDULE_DATE, ]); //force the dispatch of the required job simulation and execute call $timerEvent->execute($timerEvent->getEventDefinitions()->item(0), $instance); $this->engine->runToNextState(); //Assertion: the process should continue to the next task $this->assertEvents([ IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CATCH, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_PASSED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); } /** * Adds a test timer event definition for the timer event passed * * @param EventInterface $timerEvent * @param string $type * * @return \ProcessMaker\Nayra\Bpmn\Models\TimerEventDefinition */ private function addTimerEventDefinition(EventInterface $timerEvent, $type) { $formalExpression = new FormalExpression(); $formalExpression->setId('formalExpression'); $timerEventDefinition = $this->repository->createTimerEventDefinition(); $timerEventDefinition->setRepository($this->repository); $timerEventDefinition->setId('TimerEventDefinition'); switch ($type) { case 'duration': $timerEventDefinition->setTimeDuration(function ($data) { return 'PT1H'; }); break; case 'cycle': $timerEventDefinition->setTimeCycle(function ($data) { return 'R4/2018-05-01T00:00:00Z/PT1M'; }); break; default: $timerEventDefinition->setTimeDate(function ($data) { return '2018-05-01T14:30:00'; }); } $timerEvent->getEventDefinitions()->push($timerEventDefinition); return $timerEventDefinition; } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/MessageEndEventTest.php
tests/Feature/Engine/MessageEndEventTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Bpmn\Models\Collaboration; use ProcessMaker\Nayra\Bpmn\Models\DataStoreCollection; use ProcessMaker\Nayra\Bpmn\Models\Participant; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateCatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateThrowEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ItemDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\MessageEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; /** * Test message end events */ class MessageEndEventTest extends EngineTestCase { /** * Creates a process with a throwing message and other with an end message event * * @return array */ public function createMessageStartEventProcesses() { $item = $this->repository->createItemDefinition([ 'id' => 'item', 'isCollection' => true, 'itemKind' => ItemDefinitionInterface::ITEM_KIND_INFORMATION, 'structure' => 'String', ]); $message = $this->repository->createMessage(); $message->setId('MessageA'); $message->setItem($item); $processA = $this->repository->createProcess(); $processA->setEngine($this->engine); $processA->setRepository($this->repository); $startA = $this->repository->createStartEvent(); $activityA1 = $this->repository->createActivity(); $eventA = $this->repository->createIntermediateCatchEvent(); $messageEventDefA = $this->repository->createMessageEventDefinition(); $messageEventDefA->setId('MessageEvent1'); $messageEventDefA->setPayload($message); $eventA->getEventDefinitions()->push($messageEventDefA); $activityA2 = $this->repository->createActivity(); $endA = $this->repository->createEndEvent(); $startA->createFlowTo($activityA1, $this->repository); $activityA1->createFlowTo($eventA, $this->repository); $eventA->createFlowTo($activityA2, $this->repository); $activityA2->createFlowTo($endA, $this->repository); $processA->addActivity($activityA1) ->addActivity($activityA2) ->addEvent($startA) ->addEvent($eventA) ->addEvent($endA); //Process B $processB = $this->repository->createProcess(); $processB->setEngine($this->engine); $startB = $this->repository->createStartEvent(); $activityB1 = $this->repository->createActivity(); $messageEventDefB = $this->repository->createMessageEventDefinition(); $messageEventDefB->setPayload($message); $messageEndEventB = $this->repository->createEndEvent(); $messageEndEventB->getEventDefinitions()->push($messageEventDefB); $startB->createFlowTo($activityB1, $this->repository); $activityB1->createFlowTo($messageEndEventB, $this->repository); $processB->addActivity($activityB1) ->addEvent($startB) ->addEvent($messageEndEventB); return [$processA, $processB]; } /** * Tests the message end event of a process */ public function testMessageEndEvent() { //Create two processes list($processA, $processB) = $this->createMessageStartEventProcesses(); //Create a collaboration $collaboration = new Collaboration; //Add process A as participant of the collaboration $participant = new Participant(); $participant->setProcess($processA); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); //Add process B as participant of the collaboration $participant = new Participant(); $participant->setProcess($processB); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); //Create message flow from intermediate events A to B $eventA = $processA->getEvents()->item(1); $messageEndEventB = $processB->getEvents()->item(1); $messageFlow = $this->repository->createMessageFlow(); $messageFlow->setCollaboration($collaboration); $messageFlow->setSource($messageEndEventB); $messageFlow->setTarget($eventA); $collaboration->addMessageFlow($messageFlow); $eventA = $processA->getEvents()->item(1); $eventB = $processB->getEvents()->item(1); $dataStoreA = $this->repository->createDataStore(); $dataStoreA->putData('A', '1'); $dataStoreB = $this->repository->createDataStore(); $dataStoreB->putData('B', '1'); $dataStoreCollectionA = new DataStoreCollection(); $dataStoreCollectionA->add($dataStoreA); $dataStoreCollectionB = new DataStoreCollection(); $dataStoreCollectionB->add($dataStoreB); $processA->setDataStores($dataStoreCollectionA); $processB->setDataStores($dataStoreCollectionB); $this->engine->loadCollaboration($collaboration); $instanceA = $this->engine->createExecutionInstance($processA, $dataStoreA); $instanceB = $this->engine->createExecutionInstance($processB, $dataStoreB); // we start the second process and run it up to the end $startB = $processB->getEvents()->item(0); $activityB1 = $processB->getActivities()->item(0); // we start the process A $startA = $processA->getEvents()->item(0); $activityA1 = $processA->getActivities()->item(0); $startA->start($instanceA); $this->engine->runToNextState(); //Assertion: The activity must be activated $this->assertEvents([ //Instance for process A ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, //Instance for process B ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // we finish the first activity so that the catch message is activated $tokenA = $activityA1->getTokens($instanceA)->item(0); $activityA1->complete($tokenA); $this->engine->runToNextState(); $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, ]); $startB->start($instanceB); $this->engine->runToNextState(); //Assertion: Process B - The activity must be activated $this->assertEvents([ EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); $tokenB = $activityB1->getTokens($instanceB)->item(0); $activityB1->complete($tokenB); $this->engine->runToNextState(); //Assertion: Process B - The activity is completed and the end event must be activated $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, // the throw token of the end is sent IntermediateThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, MessageEventDefinitionInterface::EVENT_THROW_EVENT_DEFINITION, // the Process A catching message is activated IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CATCH, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_PASSED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, // the Process B end throw event must consume its tokens IntermediateThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/EngineTestCase.php
tests/Feature/Engine/EngineTestCase.php
<?php namespace Tests\Feature\Engine; use DateInterval; use DateTime; use PHPUnit\Framework\TestCase; use ProcessMaker\Bpmn\TestEngine; use ProcessMaker\Nayra\Bpmn\Models\DatePeriod; use ProcessMaker\Nayra\Bpmn\Models\EventDefinitionBus; use ProcessMaker\Nayra\Contracts\Bpmn\BoundaryEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\FlowElementInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateCatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateThrowEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ThrowEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\TimerEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\TokenInterface; use ProcessMaker\Nayra\Contracts\Engine\EngineInterface; use ProcessMaker\Nayra\Contracts\Engine\JobManagerInterface; use ProcessMaker\Nayra\Contracts\EventBusInterface; use ProcessMaker\Test\Models\Repository; /** * Test transitions */ class EngineTestCase extends TestCase { /** * @var EngineInterface */ protected $engine; /** * Fired events during the test. * * @var array */ protected $firedEvents = []; /** * Event listeners * * @var array */ protected $listeners = []; /** * Scheduled jobs. * * @var array */ protected $jobs = []; /** * Repository. * * @var \ProcessMaker\Nayra\Contracts\RepositoryInterface */ protected $repository; /** * List of of events that should be persisted by the engine * * @var array */ protected $eventsToPersist = [ BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, //IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, //IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_PASSED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CATCH, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_PASSED, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_PASSED, ThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, ThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, ThrowEventInterface::EVENT_THROW_TOKEN_PASSED, ]; /** * Initialize the engine and the factories. */ protected function setUp(): void { parent::setUp(); $this->repository = $this->createRepository(); //Initialize a dispatcher $fakeDispatcher = $this->getMockBuilder(EventBusInterface::class) ->getMock(); $fakeDispatcher->expects($this->any()) ->method('dispatch') ->will($this->returnCallback(function ($event, ...$payload) { $this->firedEvents[] = $event; if (empty($this->listeners[$event])) { return; } foreach ($this->listeners[$event] as $listener) { call_user_func_array($listener, $payload); } })); $fakeDispatcher->expects($this->any()) ->method('listen') ->will($this->returnCallback(function ($event, $listener) { $this->listeners[$event][] = $listener; })); //Initialize the engine $this->engine = new TestEngine($this->repository, $fakeDispatcher); //Mock a job manager $this->jobManager = $this->getMockBuilder(JobManagerInterface::class) ->getMock(); $this->jobManager->expects($this->any()) ->method('scheduleDate') ->will($this->returnCallback(function (DateTime $date, TimerEventDefinitionInterface $timerDefinition, FlowElementInterface $element, TokenInterface $token = null) { $this->jobs[] = [ 'repeat' => false, 'timer' => $date, 'eventDefinition' => $timerDefinition, 'element' => $element, 'token' => $token, ]; })); $this->jobManager->expects($this->any()) ->method('scheduleCycle') ->will($this->returnCallback(function (DatePeriod $cycle, TimerEventDefinitionInterface $timerDefinition, FlowElementInterface $element, TokenInterface $token = null) { $this->jobs[] = [ 'repeat' => true, 'timer' => $cycle, 'eventDefinition' => $timerDefinition, 'element' => $element, 'token' => $token, ]; })); $this->jobManager->expects($this->any()) ->method('scheduleDuration') ->will($this->returnCallback(function (DateInterval $duration, TimerEventDefinitionInterface $timerDefinition, FlowElementInterface $element, TokenInterface $token = null) { $this->jobs[] = [ 'repeat' => false, 'timer' => $duration, 'eventDefinition' => $timerDefinition, 'element' => $element, 'token' => $token, ]; })); $this->eventDefinitionBus = new EventDefinitionBus; //Initialize the engine $this->engine = new TestEngine($this->repository, $fakeDispatcher, $this->jobManager, $this->eventDefinitionBus); } /** * Tear down the test case. */ protected function tearDown(): void { $this->engine->closeExecutionInstances(); parent::tearDown(); } /** * Assert that events were fired. * * @param array $events */ protected function assertEvents(array $events) { $tokenRepository = $this->engine->getRepository()->getTokenRepository(); $this->assertRepositoryCalls($tokenRepository->getPersistCalls()); $tokenRepository->resetPersistCalls(); $this->assertEquals( $events, $this->firedEvents, 'Expected event was not fired' ); $this->firedEvents = []; } /** * Asserts that for every persisted call a repository persist method was called * * @param int $expectedCalls */ protected function assertRepositoryCalls($expectedCalls) { $count = 0; foreach ($this->firedEvents as $event) { $count += (in_array($event, $this->eventsToPersist)) ? 1 : 0; } $this->assertEquals($expectedCalls, $count); } /** * Assert that a date timer was scheduled. * * @param string $date * @param FlowElementInterface $element * @param TokenInterface|null $token */ protected function assertScheduledDateTimer($date, FlowElementInterface $element, TokenInterface $token = null) { $found = false; $scheduled = []; $logScheduled = ''; foreach ($this->jobs as $job) { $logScheduled .= "\n" . $this->representJob($job['timer'], $job['element'], $job['token']); $scheduled[] = $job['timer']; if (isset($job['timer']) && $job['timer'] == $date && $job['element'] === $element && $job['token'] === $token) { $found = true; } } $this->assertTrue($found, "Failed asserting that a date timer:\n" . $this->representJob($date, $element, $token) . "\n\nWas scheduled: " . $logScheduled); } /** * Assert that a cyclic timer was scheduled. * * @param DatePeriod $cycle * @param FlowElementInterface $element * @param TokenInterface|null $token */ protected function assertScheduledCyclicTimer(DatePeriod $cycle, FlowElementInterface $element, TokenInterface $token = null) { $found = false; $scheduled = []; $logScheduled = ''; foreach ($this->jobs as $job) { $logScheduled .= "\n" . $this->representJob($job['timer'], $job['element'], $job['token']); $scheduled[] = $job['timer']; if (isset($job['timer']) && json_encode($job['timer']) == json_encode($cycle) && $job['element'] === $element && $job['token'] === $token) { $found = true; } } $this->assertTrue($found, "Failed asserting that a cycle timer:\n" . $this->representJob($cycle, $element, $token) . "\n\nWas scheduled: " . $logScheduled); } /** * Assert that a duration timer was scheduled. * * @param string $duration * @param FlowElementInterface $element * @param TokenInterface|null $token */ protected function assertScheduledDurationTimer($duration, FlowElementInterface $element, TokenInterface $token = null) { $found = false; $logScheduled = ''; foreach ($this->jobs as $job) { $logScheduled .= "\n" . $this->representJob($job['timer'], $job['element'], $job['token']); if (isset($job['timer']) && $job['timer'] === $duration && $job['element'] === $element && $job['token'] === $token) { $found = true; } } $this->assertTrue($found, "Failed asserting that a duration timer was scheduled:\n" . $this->representJob($duration, $element, $token) . "\n\nWas scheduled: " . $logScheduled); } /** * String representation of a job * * @param mixed $timer * @param FlowElementInterface $element * @param TokenInterface|null $token * @return void */ private function representJob($timer, FlowElementInterface $element, TokenInterface $token = null) { return sprintf( '(%s) at "%s" token "%s"', (is_object($timer) ? get_class($timer) : gettype($timer)), $element->getId(), $token ? $token->getId() : 'null' ); } /** * Helper to dispatch a job from the JobManager mock */ protected function dispatchJob() { $job = array_shift($this->jobs); if ($job && $job['repeat']) { $this->jobs[] = $job; } $instance = $job['token'] ? $job['token']->getInstance() : null; return $job ? $job['element']->execute($job['eventDefinition'], $instance) : null; } /** * Get repository instance * * @return \ProcessMaker\Nayra\Contracts\RepositoryInterface */ private function createRepository() { return new Repository(); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/ServiceTaskTest.php
tests/Feature/Engine/ServiceTaskTest.php
<?php namespace Tests\Feature\Engine; use Exception; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ServiceTaskInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Tests for the ServiceTask element */ class ServiceTaskTest extends EngineTestCase { // Property that is increased when the service task is executed. private static $serviceCalls = 0; /** * Tests the a process with the sequence start->serviceTask->End executes correctly */ public function testProcessWithServiceTask() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/ServiceTaskProcess.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('ServiceTaskProcess'); $dataStore = $this->repository->createDataStore(); //create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $serviceTask = $bpmnRepository->getServiceTask('_2'); static::$serviceCalls = 0; $serviceCalls = static::$serviceCalls; //start the process an instance of the process $start->start($instance); $this->engine->runToNextState(); //Assert: that the process is stared and the service task is activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ServiceTaskInterface::EVENT_SERVICE_TASK_ACTIVATED, ]); //Execute the service task $token = $serviceTask->getTokens($instance)->item(0); $serviceTask->run($token); $this->engine->runToNextState(); //Assertion: The service task must be completed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); //Assertion: Verify the method convertToDoc was called $this->assertEquals($serviceCalls + 1, static::$serviceCalls); } /** * Tests a process with the sequence start->serviceTask->End when fails * the task goes to a failure state. */ public function testProcessWithServiceTaskFailure() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/ServiceTaskProcess.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('ServiceTaskProcess'); $dataStore = $this->repository->createDataStore(); //create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $serviceTask = $bpmnRepository->getServiceTask('_2'); //Set to the limit of the service calls static::$serviceCalls = 10; $serviceCalls = static::$serviceCalls; //start the process an instance of the process $start->start($instance); $this->engine->runToNextState(); //Assert: that the process is stared and the service task is activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ServiceTaskInterface::EVENT_SERVICE_TASK_ACTIVATED, ]); //Execute the service task $token = $serviceTask->getTokens($instance)->item(0); $serviceTask->run($token); $this->engine->runToNextState(); //Assertion: The service task must go to exception state $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_EXCEPTION, ]); } /** * A public function that is called by the Service Task. */ public static function convertToDoc() { if (static::$serviceCalls === 10) { throw new Exception('Limit of executions reached.'); } static::$serviceCalls++; } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/LoadExecutionInstancesTest.php
tests/Feature/Engine/LoadExecutionInstancesTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Repositories\StorageInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Test to load execution instances */ class LoadExecutionInstancesTest extends EngineTestCase { /** * Set data for a sequential process * * @param StorageInterface $repository */ private function prepareSequentialProcess(StorageInterface $repository) { $executionInstanceRepository = $this->engine->getRepository()->createExecutionInstanceRepository($repository); $executionInstanceRepository->setRawData([ 'executionInstanceId' => [ 'processId' => 'SequentialTask', 'data' => [], 'tokens' => [ [ 'elementId' => 'second', 'status' => ActivityInterface::TOKEN_STATE_ACTIVE, ], ], ], ]); } /** * Set data for a parallel process * * @param StorageInterface $repository */ private function prepareParallelProcess(StorageInterface $repository) { $executionInstanceRepository = $this->engine->getRepository()->createExecutionInstanceRepository($repository); $executionInstanceRepository->setRawData([ 'otherExecutionInstanceId' => [ 'processId' => 'ParallelProcess', 'data' => [], 'tokens' => [ [ 'elementId' => 'task2', 'status' => ActivityInterface::TOKEN_STATE_ACTIVE, ], [ 'elementId' => 'task3', 'status' => ActivityInterface::TOKEN_STATE_ACTIVE, ], ], ], ]); } /** * Set data for a parallel process with an activity just completed * * @param StorageInterface $repository */ private function prepareParallelProcessWithActivityCompleted(StorageInterface $repository) { $executionInstanceRepository = $this->engine->getRepository()->createExecutionInstanceRepository($repository); $executionInstanceRepository->setRawData([ 'otherExecutionInstanceId' => [ 'processId' => 'ParallelProcess', 'data' => [], 'tokens' => [ [ 'elementId' => 'task2', 'status' => ActivityInterface::TOKEN_STATE_COMPLETED, ], [ 'elementId' => 'task3', 'status' => ActivityInterface::TOKEN_STATE_ACTIVE, ], ], ], ]); } /** * Set data for a parallel process with an activity in exception state * * @param StorageInterface $repository */ private function prepareParallelProcessWithException(StorageInterface $repository) { $executionInstanceRepository = $this->engine->getRepository()->createExecutionInstanceRepository($repository); $executionInstanceRepository->setRawData([ 'otherExecutionInstanceId' => [ 'processId' => 'ParallelProcess', 'data' => [], 'tokens' => [ [ 'elementId' => 'task2', 'status' => ActivityInterface::TOKEN_STATE_ACTIVE, ], [ 'elementId' => 'task3', 'status' => ActivityInterface::TOKEN_STATE_FAILING, ], ], ], ]); } /** * Test load an execution instance from repository with one token */ public function testLoadExecutionInstanceWithOneToken() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $this->engine->setRepository($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadTokens.bpmn'); //Set test data to load the sequential process $this->prepareSequentialProcess($bpmnRepository); //Load the execution instance $instance = $this->engine->loadExecutionInstance('executionInstanceId', $bpmnRepository); //Get References by id $secondActivity = $bpmnRepository->getScriptTask('second'); //Completes the second activity $token = $secondActivity->getTokens($instance)->item(0); $secondActivity->complete($token); $this->engine->runToNextState(); //Assertion: Second activity was completed and closed, then the process has ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test load an execution instance from repository with multiple tokens */ public function testLoadExecutionInstanceWithMultipleTokens() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $this->engine->setRepository($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadTokens.bpmn'); //Set test data to load the sequential process $this->prepareParallelProcess($bpmnRepository); //Load the execution instance $instance = $this->engine->loadExecutionInstance('otherExecutionInstanceId', $bpmnRepository); //Get References by id $secondActivity = $bpmnRepository->getScriptTask('task2'); $thirdActivity = $bpmnRepository->getScriptTask('task3'); //Completes the second activity $token = $secondActivity->getTokens($instance)->item(0); $secondActivity->complete($token); $this->engine->runToNextState(); //Completes the third activity $token = $thirdActivity->getTokens($instance)->item(0); $thirdActivity->complete($token); $this->engine->runToNextState(); //Assertion: Second and third activity are completed and closed, the gateway is activate, and the process ends. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test load an execution instance from repository with multiple tokens * in different states */ public function testLoadExecutionInstanceWithMultipleTokensStates() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $this->engine->setRepository($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadTokens.bpmn'); //Set test data to load the sequential process $this->prepareParallelProcessWithActivityCompleted($bpmnRepository); //Load the execution instance $instance = $this->engine->loadExecutionInstance('otherExecutionInstanceId', $bpmnRepository); //Get References by id $secondActivity = $bpmnRepository->getScriptTask('task2'); $thirdActivity = $bpmnRepository->getScriptTask('task3'); //Completes the third activity $token = $thirdActivity->getTokens($instance)->item(0); $thirdActivity->complete($token); $this->engine->runToNextState(); //Assertion: Second activity is closed and the third activity are completed, then closed, the join gateway is activiate, and finally the process is completed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test load an execution instance from repository with multiple tokens * and one token in falling state */ public function testLoadExecutionInstanceWithMultipleTokensFallingState() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadTokens.bpmn'); //Set test data to load the sequential process $this->prepareParallelProcessWithException($bpmnRepository); //Load the execution instance $instance = $this->engine->loadExecutionInstance('otherExecutionInstanceId', $bpmnRepository); //Get References by id $thirdActivity = $bpmnRepository->getActivity('task3'); //Assertion: The third activity is in falling state $token = $thirdActivity->getTokens($instance)->item(0); $this->assertEquals(ActivityInterface::TOKEN_STATE_FAILING, $token->getStatus()); } /** * Test load a non existing execution instance from repository */ public function testLoadNonExistingInstance() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadTokens.bpmn'); //Load the execution instance $instance = $this->engine->loadExecutionInstance('nonExistingInstance', $bpmnRepository); //Assertion: The returned value must be null $this->assertNull($instance); } /** * Test load the same execution instance twice */ public function testLoadTheSameExistingInstanceTwice() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $this->engine->setRepository($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadTokens.bpmn'); //Set test data to load the sequential process $this->prepareSequentialProcess($bpmnRepository); //Load the execution instance twice $instance1 = $this->engine->loadExecutionInstance('executionInstanceId', $bpmnRepository); $instance2 = $this->engine->loadExecutionInstance('executionInstanceId', $bpmnRepository); //Assertion: Both variables point to the same instance $this->assertEquals($instance1, $instance2); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/ActivityExceptionTest.php
tests/Feature/Engine/ActivityExceptionTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Bpmn\ActivityTrait; use ProcessMaker\Nayra\Bpmn\Events\ActivityActivatedEvent; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\TokenInterface; /** * Test an activity with exception. */ class ActivityExceptionTest extends EngineTestCase { /** * Create a simple process * * ┌────────┐ *  ○─→│activity│─→● * └────────┘ * * * @return \ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface */ private function createSimpleProcessInstance() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $activity = new ActivityWithException(); $end = $this->repository->createEndEvent(); $process->addActivity($activity); $process->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($activity, $this->repository); $activity->createFlowTo($end, $this->repository); return $process; } /** * Test activity exception. */ public function testSimpleTransitions() { //Create a data store to test the process. $dataStore = $this->repository->createDataStore(); //Load a simple process with activity exception. $process = $this->createSimpleProcessInstance(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get references to the start event and activity. $start = $process->getEvents()->item(0); $activity = $process->getActivities()->item(0); //Assertion: Initially the activity does not have tokens. $this->assertEquals(0, $activity->getTokens($instance)->count()); //Trigger start event $start->start($instance); $this->engine->runToNextState(); $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_EXCEPTION, ]); //Assertion: The activity has one token. $this->assertEquals(1, $activity->getTokens($instance)->count()); //Assertion: The activity is in FAILING status. $token = $activity->getTokens($instance)->item(0); $this->assertEquals(ActivityInterface::TOKEN_STATE_FAILING, $token->getOwnerStatus()); //Complete the activity $token = $activity->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); //Assertion: Finally the activity does not have tokens. $this->assertEquals(0, $activity->getTokens($instance)->count()); } } class ActivityWithException implements ActivityInterface { use ActivityTrait; /** * Configure the activity to go to a FAILING status when activated. */ protected function initActivity() { $this->attachEvent(ActivityInterface::EVENT_ACTIVITY_ACTIVATED, function ($self, TokenInterface $token) { $token->setStatus(ActivityInterface::TOKEN_STATE_FAILING); }); } /** * Array map of custom event classes for the bpmn element. * * @return array */ protected function getBpmnEventClasses() { return [ ActivityInterface::EVENT_ACTIVITY_ACTIVATED => ActivityActivatedEvent::class, ]; } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/EventBasedGatewayTest.php
tests/Feature/Engine/EventBasedGatewayTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\CatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventBasedGatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateCatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ThrowEventInterface; use ProcessMaker\Nayra\Contracts\Engine\ExecutionInstanceInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Test the event based gateway element. */ class EventBasedGatewayTest extends EngineTestCase { /** * Current instance * * @var ExecutionInstanceInterface */ private $instance; /** * Test the WCP16 Deferred Choice pattern */ public function testDeferredChoiceChoiceOne() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/WCP16_DeferredChoiceEBG.bpmn'); $this->engine->loadBpmnDocument($bpmnRepository); // Load the collaboration $bpmnRepository->getProcess('COLLABORATION_1'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $managerProcess = $bpmnRepository->getProcess('PROCESS_2'); //Get start event and event definition references $startTask = $bpmnRepository->getScriptTask('_5'); $approve = $bpmnRepository->getScriptTask('_17'); $catch1 = $bpmnRepository->getIntermediateCatchEvent('_25'); $catch2 = $bpmnRepository->getIntermediateCatchEvent('_27'); $task2 = $bpmnRepository->getScriptTask('_29'); // Get the event based gateway reference $eventGateway = $bpmnRepository->getEventBasedGateway('_9'); // Assertion: $eventGateway is an instance of EventBasedGateway $this->assertInstanceOf(EventBasedGatewayInterface::class, $eventGateway); // Start the process $this->instance = $process->call(); $this->engine->runToNextState(); // Complete the 'start' activity $this->completeTask($startTask); // Assertion: Verify that Error End Event was triggered and the process is completed $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, ThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, ThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, ThrowEventInterface::EVENT_THROW_TOKEN_PASSED, CatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, CatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: We have two tokens in the main process (in the intermediate catch events) $this->assertEquals(2, $this->instance->getTokens()->count()); $this->assertEquals(1, $catch1->getTokens($this->instance)->count()); $this->assertEquals(1, $catch2->getTokens($this->instance)->count()); // Complete the 'Approve' task $manager = $managerProcess->getInstances()->item(0); $this->completeTask($approve, $manager); $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CATCH, ThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_PASSED, EventInterface::EVENT_EVENT_TRIGGERED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, ThrowEventInterface::EVENT_THROW_TOKEN_PASSED, ThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, ThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ]); // Assertion: We have one token in the main process (and it is in the task 2) $this->assertEquals(1, $this->instance->getTokens()->count()); $this->assertEquals(1, $task2->getTokens($this->instance)->count()); } /** * Test the WCP16 Deferred Choice pattern */ public function testDeferredChoiceChoiceTwo() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/WCP16_DeferredChoiceEBG.bpmn'); $this->engine->loadBpmnDocument($bpmnRepository); // Load the collaboration $bpmnRepository->getProcess('COLLABORATION_1'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $managerProcess = $bpmnRepository->getProcess('PROCESS_2'); //Get start event and event definition references $startTask = $bpmnRepository->getScriptTask('_5'); $reject = $bpmnRepository->getScriptTask('_19'); $catch1 = $bpmnRepository->getIntermediateCatchEvent('_25'); $catch2 = $bpmnRepository->getIntermediateCatchEvent('_27'); $task2 = $bpmnRepository->getScriptTask('_29'); $task3 = $bpmnRepository->getScriptTask('_31'); //$timer = $bpmnRepository->getIntermediateCatchEvent('IntermediateCatchEvent_Timer'); // Start the process $this->instance = $process->call(); $this->engine->runToNextState(); // Complete the 'start' activity $this->completeTask($startTask); // Assertion: Verify that Error End Event was triggered and the process is completed $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, ThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, ThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, ThrowEventInterface::EVENT_THROW_TOKEN_PASSED, CatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, CatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: We have two tokens in the main process (in the intermediate catch events) $this->assertEquals(2, $this->instance->getTokens()->count()); $this->assertEquals(1, $catch1->getTokens($this->instance)->count()); $this->assertEquals(1, $catch2->getTokens($this->instance)->count()); // Complete the 'Approve' task $manager = $managerProcess->getInstances()->item(0); $this->completeTask($reject, $manager); $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CATCH, ThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_PASSED, EventInterface::EVENT_EVENT_TRIGGERED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, ThrowEventInterface::EVENT_THROW_TOKEN_PASSED, ThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, ThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ]); // Assertion: We have one token in the main process (and it is in the task 3) $this->assertEquals(1, $this->instance->getTokens()->count()); $this->assertEquals(1, $task3->getTokens($this->instance)->count()); } /** * Test parallel gateway can not have conditioned outgoing flows. */ public function testEventBasedGatewayCanNotHaveConditionedOutgoingFlow() { //Create a parallel gateway and an activity. $gatewayA = $this->repository->createEventBasedGateway(); $eventA = $this->repository->createIntermediateCatchEvent(); //Assertion: Throw exception when creating a conditioned flow from parallel. $this->expectException('ProcessMaker\Nayra\Exceptions\InvalidSequenceFlowException'); $gatewayA->createConditionedFlowTo($eventA, function () { }, false, $this->repository); $process = $this->repository->createProcess(); $process ->addEvent($eventA) ->addGateway($gatewayA); } /** * Complete an active task * * @param \ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface $task * @param \ProcessMaker\Nayra\Contracts\Engine\ExecutionInstanceInterface|null $instance * * @return void */ private function completeTask(ActivityInterface $task, ExecutionInstanceInterface $instance = null) { $token = $task->getTokens($instance ? $instance : $this->instance)->item(0); $task->complete($token); $this->engine->runToNextState(); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/JobManagerTest.php
tests/Feature/Engine/JobManagerTest.php
<?php namespace Tests\Feature\Engine; use DateInterval; use DateTime; use ProcessMaker\Nayra\Engine\JobManagerTrait; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Start Timer Event tests */ class JobManagerTest extends EngineTestCase { use JobManagerTrait; /** * Test the job manager date time cycle calculation. */ public function testGetNextDateTimeCycle() { /* @var $startDate \DateTime */ /* @var $interval \DateInterval */ //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Timer_StartEvent_TimeCycle.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('Process'); $this->engine->loadProcess($process); //Get scheduled job information $job = $this->jobs[0]; $startDate = $job['timer']->getStartDate(); $interval = $job['timer']->getDateInterval(); //Get the next DateTime cycle after the start date of the timer. $nextDate = $this->getNextDateTimeCycle($job['timer'], $startDate); //Assertion: The next DateTime must be the start date plus one interval. $expected = clone $startDate; $expected->add($interval); $this->assertEquals($expected, $nextDate); //Get the next DateTime cycle $nextDateTwo = $this->getNextDateTimeCycle($job['timer'], $expected); //Assertion: The next DateTime must be the start date plus two intervals. $expectedNext = clone $startDate; $expectedNext->add($interval); $expectedNext->add($interval); $this->assertEquals($expectedNext, $nextDateTwo); } /** * Test the job manager date time cycle between two dates. */ public function testCycleBetweenDatesExpression() { /* @var $startDate \DateTime */ /* @var $interval \DateInterval */ //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Timer_StartEvent_TimeCycle.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('Process'); $timerEventDefinition = $bpmnRepository->getTimerEventDefinition('_9_ED_1'); //Set a time cycle between two dates $expression = $this->repository->createFormalExpression(); $expression->setRepository($this->repository); $expression->setProperty('body', 'R/2018-05-01T00:00:00Z/PT1M/2018-06-01T00:00:00Z'); $timerEventDefinition->setTimeCycle($expression); $this->engine->loadProcess($process); //Get scheduled job information $job = $this->jobs[0]; $startDate = $job['timer']->getStartDate(); $interval = $job['timer']->getDateInterval(); //Get the next DateTime cycle after the start date of the timer. $nextDate = $this->getNextDateTimeCycle($job['timer'], $startDate); //Assertion: The next DateTime must be the start date plus one interval. $expected = clone $startDate; $expected->add($interval); $this->assertEquals($expected, $nextDate); //Get the next DateTime cycle $nextDateTwo = $this->getNextDateTimeCycle($job['timer'], $expected); //Assertion: The next DateTime must be the start date plus two intervals. $expectedNext = clone $startDate; $expectedNext->add($interval); $expectedNext->add($interval); $this->assertEquals($expectedNext, $nextDateTwo); } /** * Test the job manager with timer event with an specify date. */ public function testSpecificDate() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Timer_StartEvent_TimeDate.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('Process'); $timerEventDefinition = $bpmnRepository->getTimerEventDefinition('_9_ED_1'); //Set an specific date time $date = '2018-10-02T21:30:00Z'; $expression = $this->repository->createFormalExpression(); $expression->setRepository($this->repository); $expression->setProperty('body', $date); $timerEventDefinition->setTimeDate($expression); $this->engine->loadProcess($process); //Get scheduled job information $job = $this->jobs[0]; $startDate = $job['timer']; //Assertion: The start DateTime must be the one specified. $expected = new DateTime($date); $this->assertEquals($expected, $startDate); } /** * Test the job manager with timer event with an date time interval. */ public function testDateTimeInterval() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Timer_StartEvent_TimeDateInterval.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('Process'); $timerEventDefinition = $bpmnRepository->getTimerEventDefinition('_9_ED_1'); //Set an date time interval $interval = 'PT1H'; $expression = $this->repository->createFormalExpression(); $expression->setRepository($this->repository); $expression->setProperty('body', $interval); $timerEventDefinition->setTimeDuration($expression); $this->engine->loadProcess($process); //Get scheduled job information $job = $this->jobs[0]; $duration = $job['timer']; //Assertion: The duration must be the specified date time interval. $expected = new DateInterval($interval); $this->assertEquals($expected, $duration); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/StartTimerEventTest.php
tests/Feature/Engine/StartTimerEventTest.php
<?php namespace Tests\Feature\Engine; use DateInterval; use DateTime; use ProcessMaker\Nayra\Bpmn\Models\DatePeriod; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Start Timer Event tests */ class StartTimerEventTest extends EngineTestCase { /** * Test the start timer event with a date time specified in ISO8601 format. */ public function testStartTimerEventWithTimeDate() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Timer_StartEvent_TimeDate.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('Process'); $startEvent = $bpmnRepository->getStartEvent('_9'); $this->engine->loadProcess($process); //Assertion: The jobs manager receive a scheduling request to trigger the start event time cycle specified in the process $this->assertScheduledDateTimer(new DateTime('2018-05-01T14:30:00'), $startEvent); //Force to dispatch the requersted job $this->dispatchJob(); $this->assertEquals(1, $process->getInstances()->count()); } /** * Test the start timer event with a time cycle specified in ISO8601 format. */ public function testStartTimerEventWithTimeCycle() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Timer_StartEvent_TimeCycle.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('Process'); $startEvent = $bpmnRepository->getStartEvent('_9'); $this->engine->loadProcess($process); //Assertion: The jobs manager receive a scheduling request to trigger the start event time cycle specified in the process $this->assertScheduledCyclicTimer(new DatePeriod('R4/2018-05-01T00:00:00Z/PT1M'), $startEvent); //Force to dispatch the requersted job $this->dispatchJob(); $this->assertEquals(1, $process->getInstances()->count()); //Force to dispatch the requersted job $this->dispatchJob(); $this->assertEquals(2, $process->getInstances()->count()); } /** * Test the start timer event with a date time specified by an expression. */ public function testStartTimerEventWithTimeDateExpression() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); //Create a default environment data $environmentData = $this->repository->createDataStore(); $this->engine->setDataStore($environmentData); $date = new DateTime; $date->setTime(23, 59, 59); $calculatedDate = $date->format(DateTime::ISO8601); $environmentData->putData('calculatedDate', $calculatedDate); //Load a process from a bpmn repository by Id $bpmnRepository->load(__DIR__ . '/files/Timer_StartEvent_TimeDateExpression.bpmn'); $process = $bpmnRepository->getProcess('Process'); $startEvent = $bpmnRepository->getStartEvent('_9'); $this->engine->loadProcess($process); //Assertion: The jobs manager receive a scheduling request to trigger the start event at the date time calculated by the expression $this->assertScheduledDateTimer(new DateTime($calculatedDate), $startEvent); //Assertion: The calculated value should conform to the ISO-8601 format for date and time representations. $value = $this->jobs[0]['timer']; $this->assertValidDate($value); //Force to dispatch the requersted job $this->dispatchJob(); $this->assertEquals(1, $process->getInstances()->count()); } /** * Test the start timer event with a time cycle specified by an expression. */ public function testStartTimerEventWithTimeCycleExpression() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); //Create a default environment data $environmentData = $this->repository->createDataStore(); $this->engine->setDataStore($environmentData); //Calculate a iso8601 string for a cyclic timer of 1 minute from 2018-05-01 at 00:00 UTC $everyMinute = '1M'; $fromDate = '2018-05-01T00:00:00Z'; $calculatedCycle = 'R4/' . $fromDate . '/PT' . $everyMinute; $environmentData->putData('calculatedCycle', $calculatedCycle); //Load a process from a bpmn repository by Id $bpmnRepository->load(__DIR__ . '/files/Timer_StartEvent_TimeCycleExpression.bpmn'); $process = $bpmnRepository->getProcess('Process'); $startEvent = $bpmnRepository->getStartEvent('_9'); $this->engine->loadProcess($process); //Assertion: The jobs manager receive a scheduling request to trigger the start event time cycle specified in the process $this->assertScheduledCyclicTimer(new DatePeriod($calculatedCycle), $startEvent); //Assertion: The calculated value should conform to the ISO-8601 format for date and time representations. $value = $this->jobs[0]['timer']; $this->assertValidCycle($value); //Force to dispatch the requersted job $this->dispatchJob(); $this->assertEquals(1, $process->getInstances()->count()); //Force to dispatch the requersted job $this->dispatchJob(); $this->assertEquals(2, $process->getInstances()->count()); } /** * Validate if the string has a valid ISO8601 date time representation * * @param mixed $date */ private function assertValidDate($date) { $this->assertTrue($date instanceof DateTime, 'Failed asserting that ' . json_encode($date) . ' is a valid date timer'); } /** * Validate if the string has a valid ISO8601 cycle representation * * @param mixed $cycle */ private function assertValidCycle($cycle) { $this->assertTrue($cycle instanceof DatePeriod, 'Failed asserting that ' . json_encode($cycle) . ' is a valid cyclic timer'); } /** * Validate if the string has a valid ISO8601 duration representation * * @param mixed $duration */ private function assertValidDuration($duration) { $this->assertTrue($duration instanceof DateInterval, 'Failed asserting that ' . json_encode($duration) . ' is a valid duration timer'); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/SaveExecutionInstancesTest.php
tests/Feature/Engine/SaveExecutionInstancesTest.php
<?php namespace Tests\Feature\Engine; use Exception; use ProcessMaker\Nayra\Bpmn\Events\ActivityActivatedEvent; use ProcessMaker\Nayra\Bpmn\Events\ActivityClosedEvent; use ProcessMaker\Nayra\Bpmn\Events\ActivityCompletedEvent; use ProcessMaker\Nayra\Bpmn\Events\ProcessInstanceCompletedEvent; use ProcessMaker\Nayra\Bpmn\Events\ProcessInstanceCreatedEvent; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; use ProcessMaker\Test\Models\TokenRepository; /** * Test to save execution instances */ class SaveExecutionInstancesTest extends EngineTestCase { /** * Array where to save the tokens of the execution instance tested. * * @var array */ private $storage = []; /** * Configure the Listener to save the tokens and instances. */ protected function setUp(): void { parent::setUp(); //Prepare the listener to save tokens $dispatcher = $this->engine->getDispatcher(); $dispatcher->listen(ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, function (ProcessInstanceCreatedEvent $payload) { $this->storage[$payload->instance->getId()] = [ 'processId' => $payload->process->getId(), 'data' => [], 'tokens' => [], 'status' => 'ACTIVE', ]; }); $dispatcher->listen(ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, function (ProcessInstanceCompletedEvent $payload) { $this->storage[$payload->instance->getId()]['status'] = 'COMPLETED'; }); $dispatcher->listen(ActivityInterface::EVENT_ACTIVITY_ACTIVATED, function (ActivityActivatedEvent $event) { $id = $event->token->getInstance()->getId(); $this->storage[$id]['tokens'][$event->token->getId()] = [ 'elementId' => $event->activity->getId(), 'status' => $event->token->getStatus(), ]; }); $dispatcher->listen(ActivityInterface::EVENT_ACTIVITY_COMPLETED, function (ActivityCompletedEvent $event) { $id = $event->token->getInstance()->getId(); $this->storage[$id]['tokens'][$event->token->getId()] = [ 'elementId' => $event->activity->getId(), 'status' => $event->token->getStatus(), ]; }); $dispatcher->listen(ActivityInterface::EVENT_ACTIVITY_CLOSED, function (ActivityClosedEvent $event) { $id = $event->token->getInstance()->getId(); $this->storage[$id]['tokens'][$event->token->getId()] = [ 'elementId' => $event->activity->getId(), 'status' => $event->token->getStatus(), ]; }); //Prepare a clean storage. $this->storage = []; } /** * Test to save a sequential process with one active token. */ public function testSaveExecutionInstanceWithOneToken() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadTokens.bpmn'); //Call the process $process = $bpmnRepository->getProcess('SequentialTask'); $instance = $process->call(); $this->engine->runToNextState(); //Completes the first activity $firstActivity = $bpmnRepository->getActivity('first'); $token = $firstActivity->getTokens($instance)->item(0); $firstActivity->complete($token); $this->engine->runToNextState(); //Assertion: Verify that first activity was activated, completed and closed, then the second is activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, StartEventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); //Assertion: Saved data show the first activity was closed, the second is active $this->assertSavedTokens($instance->getId(), [ ['elementId' => 'first', 'status' => ActivityInterface::TOKEN_STATE_CLOSED], ['elementId' => 'second', 'status' => ActivityInterface::TOKEN_STATE_ACTIVE], ]); } /** * Test save execution instance with multiple tokens */ public function testSaveExecutionInstanceWithMultipleTokens() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadTokens.bpmn'); //Call the process $process = $bpmnRepository->getProcess('ParallelProcess'); $instance = $process->call(); $this->engine->runToNextState(); //Completes the first task $firstTask = $bpmnRepository->getActivity('task1'); $token = $firstTask->getTokens($instance)->item(0); $firstTask->complete($token); $this->engine->runToNextState(); //Assertion: Verify that gateway was activated, the two tasks activate, one completed and another activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, StartEventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Assertion: Saved data show the first activity was closed, the second is active, and the third is active $this->assertSavedTokens($instance->getId(), [ ['elementId' => 'task1', 'status' => ActivityInterface::TOKEN_STATE_CLOSED], ['elementId' => 'task2', 'status' => ActivityInterface::TOKEN_STATE_ACTIVE], ['elementId' => 'task3', 'status' => ActivityInterface::TOKEN_STATE_ACTIVE], ]); //Completes the second task $secondtTask = $bpmnRepository->getActivity('task2'); $token = $secondtTask->getTokens($instance)->item(0); $secondtTask->complete($token); $this->engine->runToNextState(); //Assertion: Saved data show the first activity was closed, the second is completed, and the third is active $this->assertSavedTokens($instance->getId(), [ ['elementId' => 'task1', 'status' => ActivityInterface::TOKEN_STATE_CLOSED], ['elementId' => 'task2', 'status' => ActivityInterface::TOKEN_STATE_CLOSED], ['elementId' => 'task3', 'status' => ActivityInterface::TOKEN_STATE_ACTIVE], ]); //Completes the third task $thirdTask = $bpmnRepository->getActivity('task3'); $token = $thirdTask->getTokens($instance)->item(0); $thirdTask->complete($token); $this->engine->runToNextState(); //Assertion: Saved data show the first activity was closed, the second is closed, and the third is closed $this->assertSavedTokens($instance->getId(), [ ['elementId' => 'task1', 'status' => ActivityInterface::TOKEN_STATE_CLOSED], ['elementId' => 'task2', 'status' => ActivityInterface::TOKEN_STATE_CLOSED], ['elementId' => 'task3', 'status' => ActivityInterface::TOKEN_STATE_CLOSED], ]); } /** * Test save execution with an exception. * * @return void */ public function testFailSaveToken() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/LoadTokens.bpmn'); //Call the process $process = $bpmnRepository->getProcess('ParallelProcess'); $instance = $process->call(); $this->engine->runToNextState(); //Completes the first task $firstTask = $bpmnRepository->getActivity('task1'); $token = $firstTask->getTokens($instance)->item(0); //Assertion: Expected Exception when save token $this->expectException(Exception::class); TokenRepository::failNextPersistanceCall(); $firstTask->complete($token); $this->engine->runToNextState(); } /** * Verify if the saved data is the expected. * * @param string $instanceId * @param array $expected * @param string $message */ private function assertSavedTokens($instanceId, array $expected, $message = 'Saved data is not the expected') { $tokens = array_values($this->storage[$instanceId]['tokens']); //Assertion: Verify the saved data $this->assertEquals($expected, $tokens, $message); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/ErrorEndEventTest.php
tests/Feature/Engine/ErrorEndEventTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ErrorEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Test an error end event. */ class ErrorEndEventTest extends EngineTestCase { /** * Test a global Error End Event */ public function testErrorEndEventTopLevel() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Error_EndEvent_TopLevel.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('Error_EndEvent_TopLevel'); //Get start event and event definition references $startActivity = $bpmnRepository->getScriptTask('start'); $endActivity = $bpmnRepository->getScriptTask('end'); $errorEvent = $bpmnRepository->getErrorEventDefinition('TerminateEventDefinition_1'); $error = $bpmnRepository->getError('error'); //Start the process $instance = $process->call(); $this->engine->runToNextState(); //Complete the 'start' activity $token = $startActivity->getTokens($instance)->item(0); $startActivity->complete($token); $this->engine->runToNextState(); //Complete the 'end' activity $token = $endActivity->getTokens($instance)->item(0); $endActivity->complete($token); $this->engine->runToNextState(); //Assertion: Verify that Error End Event was triggered and the process is completed $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, ErrorEventDefinitionInterface::EVENT_THROW_EVENT_DEFINITION, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test a global Error End Event */ public function testErrorEndEventCallActivity() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Error_EndEvent_CallActivity.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $subProcess = $bpmnRepository->getProcess('PROCESS_2'); //Get start event and event definition references $callActivity = $bpmnRepository->getCallActivity('_5'); $subActivity = $bpmnRepository->getActivity('_10'); //Start $instance = $process->call(); $this->engine->runToNextState(); $subInstance = $subProcess->getInstances()->item(0); //Completes 'start' and 'end' activities $token = $subActivity->getTokens($subInstance)->item(0); $subActivity->complete($token); $this->engine->runToNextState(); //Assertion: Verify that ErrorEventDefinition was triggered //Assertion: Verify that the Activity goes to exception state //Assertion: Verify that the subprocess is ended $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, ErrorEventDefinitionInterface::EVENT_THROW_EVENT_DEFINITION, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ActivityInterface::EVENT_ACTIVITY_EXCEPTION, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/ScriptTaskTest.php
tests/Feature/Engine/ScriptTaskTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Bpmn\Models\Process; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface; /** * Tests for the ScriptTask element */ class ScriptTaskTest extends EngineTestCase { // String with the name of the property that will be set/and read to test that a script task has been executed. // The testing script will set the property with this name of the ScriptTask to which it pertains const TEST_PROPERTY = 'scriptTestTaskProp'; /** * Tests the a process with the sequence start->Task1->scriptTask1->End executes correctly */ public function testProcessWithOneScriptTask() { //Load a process $process = $this->getProcessWithOneScriptTask(); $dataStore = $this->repository->createDataStore(); //create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activity1 = $process->getActivities()->item(0); $scriptTask = $process->getActivities()->item(1); //start the process an instance of the process $start->start($instance); $this->engine->runToNextState(); //Assert: that the process is stared and the first activity activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //complete the first activity (that is a manual one) $token = $activity1->getTokens($instance)->item(0); $activity1->complete($token); $this->engine->runToNextState(); //Assertion: The activity1 must be finished and the script task run immediately $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); $token = $scriptTask->getTokens($instance)->item(0); $scriptTask->runScript($token); $scriptTask->complete($token); $this->engine->runToNextState(); $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); $this->assertEquals($scriptTask->getProperty(self::TEST_PROPERTY), 1); } /** * Tests that a process with the sequence start->ScriptTask1->scriptTask2->End runs correctly */ public function testProcessWithScriptTasksOnly() { //Load a process $process = $this->getProcessWithOnlyScriptTasks(); $dataStore = $this->repository->createDataStore(); //create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $scriptTask1 = $process->getActivities()->item(0); $scriptTask2 = $process->getActivities()->item(1); //start the process an instance of the process $start->start($instance); $this->engine->runToNextState(); //Assertion: all activities should run and the process finish immediately $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); $token = $scriptTask1->getTokens($instance)->item(0); $scriptTask1->runScript($token); $scriptTask1->complete($token); $this->engine->runToNextState(); $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); $token = $scriptTask2->getTokens($instance)->item(0); $scriptTask2->runScript($token); $scriptTask2->complete($token); $this->engine->runToNextState(); $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); // Assertion: The first script task should be executed. // This is done by testing that the TEST_PROPERTY of the scriptTask1 was set $this->assertEquals($scriptTask1->getProperty(self::TEST_PROPERTY), 1); // Assertion: The second script task should be executed. // This is done by testing that the TEST_PROPERTY of the scriptTask2 was set $this->assertEquals($scriptTask2->getProperty(self::TEST_PROPERTY), 1); } /** * Tests that when a script fails, the ScriptTask token is set to failed status */ public function testScriptTaskThatFails() { //Load a process $process = $this->getProcessWithOneScriptTask(); $dataStore = $this->repository->createDataStore(); //create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activity1 = $process->getActivities()->item(0); $scriptTask = $process->getActivities()->item(1); //set an script that evaluates with an error $scriptTask->setScript('throw new Exception ("test exception");'); //start the process an instance of the process $start->start($instance); $this->engine->runToNextState(); //Assert: that the process is stared and the first activity activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //complete the first activity (that is a manual one) $token = $activity1->getTokens($instance)->item(0); $activity1->complete($token); $this->engine->runToNextState(); $scriptToken = $scriptTask->getTokens($instance)->item(0); $scriptTask->runScript($scriptToken); //Assertion: Verify that the token was set to a failed state $this->assertEquals($scriptToken->getStatus(), ActivityInterface::TOKEN_STATE_FAILING); } /** * Generates a process with the following elements: start->Task1->scriptTask1->End * @return \ProcessMaker\Models\Process */ private function getProcessWithOneScriptTask() { $process = $this->repository->createProcess(); $process->setEngine($this->engine); //elements $start = $this->repository->createStartEvent(); $activityA = $this->repository->createActivity(); $scriptTask = $this->repository->createScriptTask(); $scriptTask->setScriptFormat('text/php'); $scriptTask->setScript('$this->setProperty("' . self::TEST_PROPERTY . '", 1);'); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($scriptTask); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($activityA, $this->repository); $activityA->createFlowTo($scriptTask, $this->repository); $scriptTask->createFlowTo($end, $this->repository); return $process; } /** * Generates a process with the following elements: start->scriptTask1->scriptTask2->End * @return \ProcessMaker\Models\Process */ private function getProcessWithOnlyScriptTasks() { $process = $this->repository->createProcess(); $process->setEngine($this->engine); //elements $start = $this->repository->createStartEvent(); $scriptTask1 = $this->repository->createScriptTask(); $scriptTask2 = $this->repository->createScriptTask(); $scriptTask1->setScriptFormat('text/php'); $scriptTask1->setScript('$this->setProperty("scriptTestTaskProp", 1);'); $scriptTask2->setScriptFormat('text/php'); $scriptTask2->setScript('$this->setProperty("scriptTestTaskProp", 1);'); $end = $this->repository->createEndEvent(); $process ->addActivity($scriptTask1) ->addActivity($scriptTask2); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($scriptTask1, $this->repository); $scriptTask1->createFlowTo($scriptTask2, $this->repository); $scriptTask2->createFlowTo($end, $this->repository); return $process; } /** * Tests that when a script fails, then it is closed */ public function testScriptTaskThatFailsAndIsClosed() { //Load a process $process = $this->getProcessWithOneScriptTask(); $dataStore = $this->repository->createDataStore(); //create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activity1 = $process->getActivities()->item(0); $scriptTask = $process->getActivities()->item(1); //set an script that evaluates with an error $scriptTask->setScript('throw new Exception ("test exception");'); //start the process an instance of the process $start->start($instance); $this->engine->runToNextState(); //Assert: that the process is stared and the first activity activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //complete the first activity (that is a manual one) $token = $activity1->getTokens($instance)->item(0); $activity1->complete($token); $this->engine->runToNextState(); $scriptToken = $scriptTask->getTokens($instance)->item(0); $scriptTask->runScript($scriptToken); $this->engine->runToNextState(); //Assertion: Verify that the token was set to a failed state $this->assertEquals($scriptToken->getStatus(), ActivityInterface::TOKEN_STATE_FAILING); // Close the script task $scriptToken = $scriptTask->getTokens($instance)->item(0); $scriptToken->setStatus(ActivityInterface::TOKEN_STATE_CLOSED); $this->engine->runToNextState(); //Assertion: Verify that the script was $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_EXCEPTION, ActivityInterface::EVENT_ACTIVITY_CANCELLED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/ExclusiveGatewayDemoTest.php
tests/Feature/Engine/ExclusiveGatewayDemoTest.php
<?php namespace Tests\Feature\Engine; use Exception; use ProcessMaker\Nayra\Bpmn\Models\Flow; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface; use ProcessMaker\Nayra\Contracts\Bpmn\TransitionInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Test transitions */ class ExclusiveGatewayDemoTest extends EngineTestCase { /** * Creates a process where the exclusive gateway has conditioned and simple transitions * ┌─────────┐ * ┌─→│activityA│─┐ * │ └─────────┘ │ * ○─→╱╲─┘ ┌─────────┐ | * ╲╱─┐ │activityB│ +─→● * └─→└─────────┘ | * └─→┌─────────┐ | * │activityC│─┘ * └─────────┘ * @return \ProcessMaker\Models\Process|ProcessInterface */ private function createProcessWithExclusiveGateway() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createExclusiveGateway(); $activityA = $this->repository->createActivity()->setName('Activity A'); $activityB = $this->repository->createActivity()->setName('Activity B'); $activityC = $this->repository->createActivity()->setName('Activity C'); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB) ->addActivity($activityC); $process ->addGateway($gatewayA); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createConditionedFlowTo($activityA, function ($data) { return $data['A'] == '1'; }, false, $this->repository) ->createConditionedFlowTo($activityB, function ($data) { return $data['B'] == '1'; }, false, $this->repository) ->createFlowTo($activityC, $this->repository); $activityA->createFlowTo($end, $this->repository); $activityB->createFlowTo($end, $this->repository); $activityC->createFlowTo($end, $this->repository); return $process; } /** * Creates a process with default transitions * * @return \ProcessMaker\Models\Process */ private function createProcessWithExclusiveGatewayAndDefaultTransition() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createExclusiveGateway(); $activityA = $this->repository->createActivity()->setName('Activity A'); $activityB = $this->repository->createActivity()->setName('Activity B'); $activityC = $this->repository->createActivity()->setName('Activity C'); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB) ->addActivity($activityC); $process ->addGateway($gatewayA); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createConditionedFlowTo($activityC, function ($data) { return true; }, true, $this->repository) ->createConditionedFlowTo($activityA, function ($data) { return $data['A'] == '1'; }, false, $this->repository) ->createConditionedFlowTo($activityB, function ($data) { return $data['B'] == '1'; }, false, $this->repository); $activityA->createFlowTo($end, $this->repository); $activityB->createFlowTo($end, $this->repository); $activityC->createFlowTo($end, $this->repository); return $process; } /** * Parallel diverging Exclusive converging * ┌─────────┐ * ┌─→│activityA│─┐ *  ○─→╱╲─┘ └─────────┘ └─→╱╲ ┌─────────┐ * ╲╱─┐ ┌─────────┐ ┌─→╲╱─→│activityC│─→● * A └─→│activityB│─┘ B └─────────┘ * parallel └─────────┘ exclusive * * @return \ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface */ private function createParallelDivergingExclusiveConverging() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createParallelGateway(); $activityA = $this->repository->createActivity(); $activityB = $this->repository->createActivity(); $activityC = $this->repository->createActivity(); $gatewayB = $this->repository->createExclusiveGateway(); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB) ->addActivity($activityC); $process ->addGateway($gatewayA) ->addGateway($gatewayB); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createFlowTo($activityA, $this->repository) ->createFlowTo($activityB, $this->repository); $activityA->createFlowTo($gatewayB, $this->repository); $activityB->createFlowTo($gatewayB, $this->repository); $gatewayB->createFlowTo($activityC, $this->repository); $activityC->createFlowTo($end, $this->repository); return $process; } /** * Tests the basic functionality of the exclusive gateway */ public function testExclusiveGateway() { // Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('A', '2'); $dataStore->putData('B', '1'); // Condition for activity B is true // Enable demo mode $this->engine->setDemoMode(true); // Run the process $process = $this->createProcessWithExclusiveGateway(); $instance = $this->engine->createExecutionInstance($process, $dataStore); $start = $process->getEvents()->item(0); $start->start($instance); $this->engine->runToNextState(); // Assertion: The process paused in the gateway $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); // Select the flow for the gateway and run the engine $gateway = $process->getGateways()->item(0); $selectedFlow = $gateway->getOutgoingFlows()->item(0); $this->engine->setSelectedDemoFlow($gateway, $selectedFlow); $this->engine->runToNextState(); // Assertion: Engine runs to the next state because a flow was selected manually $this->assertEvents([ GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: The Activity connected to the selected flow was activated $activeTask = $instance->getTokens()->item(0)->getOwnerElement(); $expectedTask = $selectedFlow->getTarget(); $this->assertEquals($expectedTask->getName(), $activeTask->getName()); } /** * Tests that the correct events are triggered when the first flow has a condition evaluated to true */ public function testExclusiveGatewayFirstConditionTrue() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('A', '1'); // Condition for activity A is true $dataStore->putData('B', '1'); // Enable demo mode $this->engine->setDemoMode(true); // Run the process $process = $this->createProcessWithExclusiveGatewayAndDefaultTransition(); $instance = $this->engine->createExecutionInstance($process, $dataStore); $start = $process->getEvents()->item(0); $start->start($instance); $this->engine->runToNextState(); // Assertion: The process paused in the gateway $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); // Select the flow for the gateway and run the engine $gateway = $process->getGateways()->item(0); $selectedFlow = $gateway->getOutgoingFlows()->item(1); $this->engine->setSelectedDemoFlow($gateway, $selectedFlow); $this->engine->runToNextState(); // Assertion: Engine runs to the next state because a flow was selected manually $this->assertEvents([ GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: The Activity connected to the selected flow was activated $activeTask = $instance->getTokens()->item(0)->getOwnerElement(); $expectedTask = $selectedFlow->getTarget(); $this->assertEquals($expectedTask->getName(), $activeTask->getName()); } /** * Tests the exclusive gateway triggering the default transition */ public function testExclusiveGatewayWithDefaultTransition() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('A', '2'); $dataStore->putData('B', '2'); // Enable demo mode $this->engine->setDemoMode(true); // Run the process $process = $this->createProcessWithExclusiveGatewayAndDefaultTransition(); $instance = $this->engine->createExecutionInstance($process, $dataStore); $start = $process->getEvents()->item(0); $start->start($instance); $this->engine->runToNextState(); // Assertion: The process paused in the gateway $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); // Select the flow for the gateway and run the engine $gateway = $process->getGateways()->item(0); $selectedFlow = $gateway->getOutgoingFlows()->item(0); $this->engine->setSelectedDemoFlow($gateway, $selectedFlow); $this->engine->runToNextState(); // Assertion: Engine runs to the next state because a flow was selected manually $this->assertEvents([ GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: The Activity connected to the selected flow was activated $activeTask = $instance->getTokens()->item(0)->getOwnerElement(); $expectedTask = $selectedFlow->getTarget(); $this->assertEquals($expectedTask?->getName(), $activeTask->getName()); } /** * Tests the exclusive gateway triggering the default transition with a * demo mode to an invalid Flow that is not connected to the gateway */ public function testExclusiveGatewayWithDefaultTransitionInvalidDemoFlow() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('A', '2'); $dataStore->putData('B', '2'); // Enable demo mode $this->engine->setDemoMode(true); // Run the process $process = $this->createProcessWithExclusiveGatewayAndDefaultTransition(); $instance = $this->engine->createExecutionInstance($process, $dataStore); $start = $process->getEvents()->item(0); $start->start($instance); $this->engine->runToNextState(); // Assertion: The process paused in the gateway $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); // Select an invalid flow for the gateway and run the engine $gateway = $process->getGateways()->item(0); $selectedFlow = new Flow(); $this->engine->setSelectedDemoFlow($gateway, $selectedFlow); $this->engine->runToNextState(); // Assertion: Engine triggers the gateway but stop because the selected flow is invalid $this->assertEvents([ GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, ]); } /** * Parallel diverging Exclusive converging * * A process with three tasks, a diverging parallelGateway and a converging exclusiveGateway. * Two of the tasks are executed in parallel and then merged by the exclusiveGateway. * As a result, the task following the exclusiveGateway should be followed twice. */ public function testParallelDivergingExclusiveConverging() { // Create a data store with data. $dataStore = $this->repository->createDataStore(); // Load the process $process = $this->createParallelDivergingExclusiveConverging(); $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $process->getEvents()->item(0); $activityA = $process->getActivities()->item(0); $activityB = $process->getActivities()->item(1); $activityC = $process->getActivities()->item(2); // Start the process $start->start($instance); $this->engine->runToNextState(); // Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Enable demo mode $this->engine->setDemoMode(true); // Completes the Activity A $tokenA = $activityA->getTokens($instance)->item(0); $activityA->complete($tokenA); $this->engine->runToNextState(); // Assertion: Verify the triggered engine events. The activity is closed and the gateway is activated. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); // Completes the Activity B $tokenB = $activityB->getTokens($instance)->item(0); $activityB->complete($tokenB); $this->engine->runToNextState(); // Assertion: Verify the triggered engine events. The activity B is closed and the gateway is activated. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); // Select the flow for the gateway B (exclusive one) and run the engine $gatewayB = $process->getGateways()->item(1); $selectedFlow = $gatewayB->getOutgoingFlows()->item(0); $this->engine->setSelectedDemoFlow($gatewayB, $selectedFlow); $this->engine->runToNextState(); $this->assertEvents([ // First token passes through the gateway GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, // Second token passes through the gateway GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: ActivityC has two tokens. $this->assertEquals(2, $activityC->getTokens($instance)->count()); // Continue with the execution completing Activity C // Completes the Activity C for the first token $tokenC = $activityC->getTokens($instance)->item(0); $activityC->complete($tokenC); $this->engine->runToNextState(); // Completes the Activity C for the next token $tokenC = $activityC->getTokens($instance)->item(0); $activityC->complete($tokenC); $this->engine->runToNextState(); // Assertion: ActivityC has no tokens. $this->assertEquals(0, $activityC->getTokens($instance)->count()); // Assertion: ActivityC was completed and closed per each token, then the end event was triggered twice. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test exclusive gateway with custom data and script task */ public function testConditionalExclusiveParameters() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/ExclusiveGateway.bpmn'); // Enable demo mode $this->engine->setDemoMode(true); // Run the process with custom data $dataStore = $this->repository->createDataStore(); $dataStore->putData('Age', '8'); $process = $bpmnRepository->getProcess('ExclusiveGatewayProcess'); $instance = $this->engine->createExecutionInstance($process, $dataStore); $start = $bpmnRepository->getStartEvent('StartEvent'); $activity1 = $bpmnRepository->getStartEvent('Exclusive1'); $start->start($instance); $this->engine->runToNextState(); // Complete the first activity $token0 = $activity1->getTokens($instance)->item(0); $activity1->complete($token0); $this->engine->runToNextState(); // Assertion: Process started, activity completed, gateway executed, script activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); // Select the flow for the gateway and run the engine $gateway = $process->getGateways()->item(0); $selectedFlow = $gateway->getOutgoingFlows()->item(0); $this->engine->setSelectedDemoFlow($gateway, $selectedFlow); $this->engine->runToNextState(); // Assertion: Engine runs to the next state because a flow was selected manually $this->assertEvents([ GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); } /** * Test demo mode with runtime error when evaluating an exclusive gateway */ public function testExclusiveGatewayMissingVariable() { // Enable demo mode $this->engine->setDemoMode(true); // Create a data store with data. $dataStore = $this->repository->createDataStore(); // Load the process $process = $this->createProcessWithExclusiveGateway(); $instance = $this->engine->createExecutionInstance($process, $dataStore); // simulate a formal expression runtime error when evaluating a gateway condition $gatewayA = $process->getGateways()->item(0); $gatewayA->getConditionedTransitions()->item(0)->setCondition(function ($data) { throw new Exception('Variable A is missing'); }); // Get References $start = $process->getEvents()->item(0); // Run the process $start->start($instance); $this->engine->runToNextState(); // Assertion: No RuntimeException expected, Gateway activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); // Select the flow for the gateway and run the engine $gateway = $process->getGateways()->item(0); $selectedFlow = $gateway->getOutgoingFlows()->item(0); $this->engine->setSelectedDemoFlow($gateway, $selectedFlow); $this->engine->runToNextState(); // Assertion: No RuntimeException expected, gateway activated and continue with the process $this->assertEvents([ GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/IntermediateMessageEventTest.php
tests/Feature/Engine/IntermediateMessageEventTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Bpmn\Models\Collaboration; use ProcessMaker\Nayra\Bpmn\Models\Participant; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateCatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateThrowEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ItemDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\MessageEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\MessageFlowInterface; use ProcessMaker\Nayra\Contracts\Bpmn\MessageInterface; use ProcessMaker\Nayra\Contracts\Bpmn\OperationInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\SignalEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\SignalInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface; /** * Test an activity with exception. */ class IntermediateMessageEventTest extends EngineTestCase { /** * Returns an array of processes that contains message events * * @return array */ public function createMessageIntermediateEventProcesses() { $properties = [ 'id' => 'item', 'isCollection' => true, 'itemKind' => ItemDefinitionInterface::ITEM_KIND_INFORMATION, 'structure' => 'String', ]; $item = $this->repository->createItemDefinition($properties); $item->setProperties($properties); $message = $this->repository->createMessage(); $message->setId('MessageA'); $message->setItem($item); //Process A $processA = $this->repository->createProcess(); $processA->setEngine($this->engine); $processA->setRepository($this->repository); $startA = $this->repository->createStartEvent(); $activityA = $this->repository->createActivity(); $eventA = $this->repository->createIntermediateThrowEvent(); $messageEventDefA = $this->repository->createMessageEventDefinition(); $messageEventDefA->setId('MessageEvent1'); $messageEventDefA->setPayload($message); $eventA->getEventDefinitions()->push($messageEventDefA); $activityB = $this->repository->createActivity(); $endA = $this->repository->createEndEvent(); $startA->createFlowTo($activityA, $this->repository); $activityA->createFlowTo($eventA, $this->repository); $eventA->createFlowTo($activityB, $this->repository); $activityB->createFlowTo($endA, $this->repository); $processA->addActivity($activityA) ->addActivity($activityB) ->addEvent($startA) ->addEvent($eventA) ->addEvent($endA); //Process B $processB = $this->repository->createProcess(); $startB = $this->repository->createStartEvent(); $activityC = $this->repository->createActivity(); $eventB = $this->repository->createIntermediateCatchEvent(); $messageEventDefB = $this->repository->createMessageEventDefinition(); $messageEventDefB->setPayload($message); $eventB->getEventDefinitions()->push($messageEventDefB); $activityD = $this->repository->createActivity(); $endB = $this->repository->createEndEvent(); $startB->createFlowTo($activityC, $this->repository); $activityC->createFlowTo($eventB, $this->repository); $eventB->createFlowTo($activityD, $this->repository); $activityD->createFlowTo($endB, $this->repository); $processB->addActivity($activityC) ->addActivity($activityD) ->addEvent($startB) ->addEvent($eventB) ->addEvent($endB); return [$processA, $processB]; } /** * Create signal intermediate event processes */ public function createSignalIntermediateEventProcesses() { $signal = $this->repository->createSignal(); $signal->setId('Signal1'); $signal->setName('SignalName'); //Process A $processA = $this->repository->createProcess(); $startA = $this->repository->createStartEvent(); $activityA = $this->repository->createActivity(); $eventA = $this->repository->createIntermediateThrowEvent(); $signalEventDefA = $this->repository->createSignalEventDefinition(); $signalEventDefA->setId('signalEventDefA'); $signalEventDefA->setPayload($signal); $eventA->getEventDefinitions()->push($signalEventDefA); $activityB = $this->repository->createActivity(); $endA = $this->repository->createEndEvent(); $startA->createFlowTo($activityA, $this->repository); $activityA->createFlowTo($eventA, $this->repository); $eventA->createFlowTo($activityB, $this->repository); $activityB->createFlowTo($endA, $this->repository); $processA->addActivity($activityA) ->addActivity($activityB) ->addEvent($startA) ->addEvent($eventA) ->addEvent($endA); //Process B $processB = $this->repository->createProcess(); $startB = $this->repository->createStartEvent(); $activityC = $this->repository->createActivity(); $eventB = $this->repository->createIntermediateCatchEvent(); $signalEventDefB = $this->repository->createSignalEventDefinition(); $signalEventDefB->setId('signalEventDefB'); $signalEventDefB->setPayload($signal); $eventB->getEventDefinitions()->push($signalEventDefB); $activityD = $this->repository->createActivity(); $endB = $this->repository->createEndEvent(); $startB->createFlowTo($activityC, $this->repository); $activityC->createFlowTo($eventB, $this->repository); $eventB->createFlowTo($activityD, $this->repository); $activityD->createFlowTo($endB, $this->repository); $processB->addActivity($activityC) ->addActivity($activityD) ->addEvent($startB) ->addEvent($eventB) ->addEvent($endB); return [$processA, $processB]; } /** * Test Process Definitions for intermediate messages */ public function testProcessDefinitionForIntermediateMessages() { list($processA, $processB) = $this->createMessageIntermediateEventProcesses(); $eventA = $processA->getEvents()->item(1); $eventB = $processB->getEvents()->item(1); $eventDefA = $eventA->getEventDefinitions()->item(0); $eventDefB = $eventB->getEventDefinitions()->item(0); $message = $eventDefA->getPayload(); $signal = $eventDefB->getPayload(); //Assertion: Validate message element $this->assertNotNull($message, 'Event Definition A should have a message'); $this->assertEquals('item', $message->getItem()->getId()); $this->assertEquals(true, $message->getItem()->isCollection()); $this->assertEquals(ItemDefinitionInterface::ITEM_KIND_INFORMATION, $message->getItem()->getItemKind()); $this->assertEquals('String', $message->getItem()->getStructure()); $this->assertNotNull($signal, 'Event Definition B should have a signal'); $operation = $this->repository->createOperation(); $eventDefA->setOperation($operation); $this->assertEquals($operation, $eventDefA->getOperation(), 'The Event Definition Operation must be equal to the assigned in the test.'); } /** * Test process definitions for intermediate signals */ public function testProcessDefinitionForIntermediateSignals() { list($processA, $processB) = $this->createSignalIntermediateEventProcesses(); $eventA = $processA->getEvents()->item(1); $eventB = $processB->getEvents()->item(1); $eventDefA = $eventA->getEventDefinitions()->item(0); $eventDefB = $eventB->getEventDefinitions()->item(0); $message = $eventDefA->getPayload(); $signal = $eventDefB->getPayload(); $this->assertNotNull($message, 'Event Definition A should have a message'); $this->assertNotNull($signal, 'Event Definition B should have a signal'); } /** * Tests that message events are working correctly */ public function testIntermediateEvent() { //Create two processes list($processA, $processB) = $this->createMessageIntermediateEventProcesses(); //Create a collaboration $collaboration = new Collaboration; //Add process A as participant of the collaboration $participant = new Participant(); $participant->setProcess($processA); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); //Add process B as participant of the collaboration $participant = new Participant(); $participant->setProcess($processB); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); //Create mmessage flow from intemediate events A to B $eventA = $processA->getEvents()->item(1); $eventB = $processB->getEvents()->item(1); $messageFlow = $this->repository->createMessageFlow(); $messageFlow->setCollaboration($collaboration); $messageFlow->setSource($eventA); $messageFlow->setTarget($eventB); $collaboration->addMessageFlow($messageFlow); $eventA = $processA->getEvents()->item(1); $eventB = $processB->getEvents()->item(1); $eventA->collaboration = $collaboration; $eventB->collaboration = $collaboration; $dataStoreA = $this->repository->createDataStore(); $dataStoreA->putData('A', '1'); $dataStoreB = $this->repository->createDataStore(); $dataStoreB->putData('B', '1'); $this->engine->loadCollaboration($collaboration); $instanceA = $this->engine->createExecutionInstance($processA, $dataStoreA); $instanceB = $this->engine->createExecutionInstance($processB, $dataStoreB); $startC = $processB->getEvents()->item(0); $activityC = $processB->getActivities()->item(0); $startC->start($instanceB); $this->engine->runToNextState(); //Assertion: The activity must be activated $this->assertEvents([ //Instance of process A ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, //Instance of process B ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); $tokenC = $activityC->getTokens($instanceB)->item(0); $activityC->complete($tokenC); $this->engine->runToNextState(); //Assertion: $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, ]); $startA = $processA->getEvents()->item(0); $activityA = $processA->getActivities()->item(0); $startA->start($instanceA); $this->engine->runToNextState(); //Assertion: The activity must be activated $this->assertEvents([ EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); $tokenA = $activityA->getTokens($instanceA)->item(0); $activityA->complete($tokenA); $this->engine->runToNextState(); //Assertion: The throwing process must advances to activity B an the catching process to activity D $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CATCH, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, //events triggered when the catching event runs IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_PASSED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); } /** * Tests that the signal event works correctly */ public function testSignalEvent() { //Create two processes list($processA, $processB) = $this->createSignalIntermediateEventProcesses(); //Create a collaboration $collaboration = new Collaboration; //Add process A as participant of the collaboration $participant = new Participant(); $participant->setProcess($processA); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); //Add process B as participant of the collaboration $participant = new Participant(); $participant->setProcess($processB); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); $eventA = $processA->getEvents()->item(1); $eventB = $processB->getEvents()->item(1); $eventA->collaboration = $collaboration; $eventB->collaboration = $collaboration; $dataStoreA = $this->repository->createDataStore(); $dataStoreA->putData('A', '1'); $dataStoreB = $this->repository->createDataStore(); $dataStoreB->putData('B', '1'); $instanceA = $this->engine->createExecutionInstance($processA, $dataStoreA); $instanceB = $this->engine->createExecutionInstance($processB, $dataStoreB); $startC = $processB->getEvents()->item(0); $activityC = $processB->getActivities()->item(0); $startC->start($instanceB); $this->engine->runToNextState(); //Assertion: The first activity of the second flow must be activated $this->assertEvents([ //Instance for process A ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, //Instance for process B ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); $tokenC = $activityC->getTokens($instanceB)->item(0); $activityC->complete($tokenC); $this->engine->runToNextState(); //Assertion: the second flows is stoppen in the catching event $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, ]); $startA = $processA->getEvents()->item(0); $activityA = $processA->getActivities()->item(0); $startA->start($instanceA); $this->engine->runToNextState(); //Assertion: The activity must be activated $this->assertEvents([ EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); $tokenA = $activityA->getTokens($instanceA)->item(0); $activityA->complete($tokenA); $this->engine->runToNextState(); //Assertion: The throwing process must advances to activity B an the catching process to activity D $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CATCH, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, //events triggered when the catching event runs IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_PASSED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/BoundaryEventTest.php
tests/Feature/Engine/BoundaryEventTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Bpmn\Models\DatePeriod; use ProcessMaker\Nayra\Bpmn\Models\ErrorEventDefinition; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\BoundaryEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\CallActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateCatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateThrowEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface; use ProcessMaker\Nayra\Contracts\Bpmn\SignalEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface; use ProcessMaker\Nayra\Contracts\Engine\JobManagerInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Tests for the BoundaryEvent elements */ class BoundaryEventTest extends EngineTestCase { /** * Tests a process with a signal boundary event attached to a task */ public function testSignalBoundaryEvent() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Signal_BoundaryEvent.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $dataStore = $this->repository->createDataStore(); // Create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $process->getEvents()->item(0); $task1 = $bpmnRepository->getActivity('_5'); $task2 = $bpmnRepository->getActivity('_7'); $task3 = $bpmnRepository->getActivity('_12'); // Start a process instance $start->start($instance); $this->engine->runToNextState(); // Assertion: The process is started and two tasks were activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Complete second task $task2->complete($task2->getTokens($instance)->item(0)); $this->engine->runToNextState(); // Assertion: Task 2 is completed, an end event Signal is thrown, then caught by the boundary event $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, SignalEventDefinitionInterface::EVENT_THROW_EVENT_DEFINITION, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, ActivityInterface::EVENT_ACTIVITY_CANCELLED, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: Task 1 does not have tokens $this->assertEquals(0, $task1->getTokens($instance)->count()); // Assertion: Task 3 has one token $this->assertEquals(1, $task3->getTokens($instance)->count()); } /** * Tests a process with a signal boundary event attached to a task */ public function testSignalBoundaryEventInMultiInstance() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Signal_BoundaryEvent_MultiInstance.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('ProcessId'); $dataStore = $this->repository->createDataStore(); $dataStore->setData([ 'array' => [1, 2], ]); // Create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $process->getEvents()->item(0); $task1 = $bpmnRepository->getActivity('node_2'); $task2 = $bpmnRepository->getActivity('node_3'); $task3 = $bpmnRepository->getActivity('node_13'); // Start a process instance $start->start($instance); $this->engine->runToNextState(); // Assertion: The process is started and two tasks were activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, // 2 MultiInstance (task1) and 1 Trigger Task (task2) ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Complete second task $task2->complete($task2->getTokens($instance)->item(0)); $this->engine->runToNextState(); // Assertion: Task 2 is completed, an end event Signal is thrown, then caught by the boundary event $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, SignalEventDefinitionInterface::EVENT_THROW_EVENT_DEFINITION, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_CANCELLED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: Task 1 does not have tokens $this->assertEquals(0, $task1->getTokens($instance)->count()); // Assertion: Task 3 has one token $this->assertEquals(1, $task3->getTokens($instance)->count()); } /** * Tests a process with a cycle timer boundary event attached to a task */ public function testCycleTimerBoundaryEvent() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Timer_BoundaryEvent_Cycle.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $dataStore = $this->repository->createDataStore(); // Create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $bpmnRepository->getStartEvent('_2'); $task1 = $bpmnRepository->getActivity('_5'); $task2 = $bpmnRepository->getActivity('_12'); $boundaryEvent = $bpmnRepository->getBoundaryEvent('_11'); // Start a process instance $start->start($instance); $this->engine->runToNextState(); // Assertion: The process is started, a task is activated and a timer event scheduled $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, JobManagerInterface::EVENT_SCHEDULE_CYCLE, ]); // Boundary event is attached to $task1, its token is associated with the timer event $activeToken = $task1->getTokens($instance)->item(0); // Assertion: The jobs manager receive a scheduling request to trigger the start event time cycle specified in the process $this->assertScheduledCyclicTimer(new DatePeriod('R4/2018-05-01T00:00:00Z/PT1M'), $boundaryEvent, $activeToken); // Trigger the boundary event $boundaryEvent->execute($boundaryEvent->getEventDefinitions()->item(0), $instance); $this->engine->runToNextState(); // Assertion: Boundary event was caught, the first task cancelled and continue to the task 2 $this->assertEvents([ BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, ActivityInterface::EVENT_ACTIVITY_CANCELLED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Complete second task $task2->complete($task2->getTokens($instance)->item(0)); $this->engine->runToNextState(); // Assertion: Task 2 is completed, and the process is completed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Tests a process with an error boundary event attached to a script task */ public function testErrorBoundaryEventScript1Task() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Error_BoundaryEvent_ScriptTask.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $dataStore = $this->repository->createDataStore(); // Create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $bpmnRepository->getStartEvent('_2'); $task1 = $bpmnRepository->getScriptTask('_5'); $task2 = $bpmnRepository->getActivity('_12'); // Start a process instance $start->start($instance); $this->engine->runToNextState(); // Assertion: The process is started and the script activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Run the script task $activeToken = $task1->getTokens($instance)->item(0); $task1->runScript($activeToken); $this->engine->runToNextState(); // Assertion: Script task throws an exception $this->assertEvents([ ScriptTaskInterface::EVENT_ACTIVITY_EXCEPTION, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, ActivityInterface::EVENT_ACTIVITY_CANCELLED, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Complete second task $task2->complete($task2->getTokens($instance)->item(0)); $this->engine->runToNextState(); // Assertion: Task 2 is completed, and the process is completed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Tests a process with a error boundary event attached to a CallActivity */ public function testErrorBoundaryEventCallActivity() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Error_BoundaryEvent_CallActivity.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $dataStore = $this->repository->createDataStore(); // Create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $bpmnRepository->getStartEvent('_4'); $task1 = $bpmnRepository->getCallActivity('_7'); $task2 = $bpmnRepository->getActivity('_13'); // Start a process instance $start->start($instance); $this->engine->runToNextState(); // Assertion: The process is started, then the sub process throw and ErrorEvent, catch by the BoundaryEvent $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EndEventInterface::EVENT_EVENT_TRIGGERED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, ErrorEventDefinition::EVENT_THROW_EVENT_DEFINITION, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ActivityInterface::EVENT_ACTIVITY_EXCEPTION, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, ActivityInterface::EVENT_ACTIVITY_CANCELLED, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Complete second task $task2->complete($task2->getTokens($instance)->item(0)); $this->engine->runToNextState(); // Assertion: Task 2 is completed, and the process is completed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Tests a process with a cycle timer boundary event attached to a CallActivity */ public function testCycleTimerBoundaryEventCallActivity() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Timer_BoundaryEvent_CallActivity.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $dataStore = $this->repository->createDataStore(); // Create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $bpmnRepository->getStartEvent('_4'); $task1 = $bpmnRepository->getCallActivity('_7'); $task2 = $bpmnRepository->getActivity('_13'); $boundaryEvent = $bpmnRepository->getBoundaryEvent('_12'); // Start a process instance $start->start($instance); $this->engine->runToNextState(); // Assertion: The process is started, a task is activated, the sub process is started and a timer event scheduled $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, JobManagerInterface::EVENT_SCHEDULE_CYCLE, StartEventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Boundary event is attached to $task1, its token is associated with the timer event $activeToken = $task1->getTokens($instance)->item(0); // Assertion: The jobs manager receive a scheduling request to trigger the start event time cycle specified in the process $this->assertScheduledCyclicTimer(new DatePeriod('R4/2018-05-01T00:00:00Z/PT1M'), $boundaryEvent, $activeToken); // Trigger the boundary event $boundaryEvent->execute($boundaryEvent->getEventDefinitions()->item(0), $instance); $this->engine->runToNextState(); // Assertion: Boundary event was caught, call activity and subprocess is cancelled, then continue to the task 2 $this->assertEvents([ BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, ActivityInterface::EVENT_ACTIVITY_CANCELLED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_CANCELLED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); // Complete second task $task2->complete($task2->getTokens($instance)->item(0)); $this->engine->runToNextState(); // Assertion: Task 2 is completed, and the process is completed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Tests the a process with a signal boundary event attached to a CallActivity */ public function testSignalBoundaryEventCallActivity() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Signal_BoundaryEvent_CallActivity.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $dataStore = $this->repository->createDataStore(); // Create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $bpmnRepository->getStartEvent('_4'); $task1 = $bpmnRepository->getCallActivity('_7'); $task2 = $bpmnRepository->getActivity('_13'); // Start a process instance $start->start($instance); $this->engine->runToNextState(); // Assertion: The process is started and two tasks were activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, StartEventInterface::EVENT_EVENT_TRIGGERED, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, ActivityInterface::EVENT_ACTIVITY_CANCELLED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, CallActivityInterface::EVENT_ACTIVITY_CANCELLED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); // Complete second task $task2->complete($task2->getTokens($instance)->item(0)); $this->engine->runToNextState(); // Assertion: Task 2 is completed, and the process is completed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Tests a process with a signal boundary non interrupting event attached to a task */ public function testSignalBoundaryEventNonInterrupting() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Signal_BoundaryEvent_NonInterrupting.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $dataStore = $this->repository->createDataStore(); // Create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $process->getEvents()->item(0); $task1 = $bpmnRepository->getActivity('_5'); $task2 = $bpmnRepository->getActivity('_7'); $task3 = $bpmnRepository->getActivity('_12'); $task4 = $bpmnRepository->getActivity('_15'); // Start a process instance $start->start($instance); $this->engine->runToNextState(); // Assertion: The process is started and two tasks were activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Complete second task $task2->complete($task2->getTokens($instance)->item(0)); $this->engine->runToNextState(); // Assertion: Task 2 is completed, an end event Signal is thrown, then caught by the boundary event $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, SignalEventDefinitionInterface::EVENT_THROW_EVENT_DEFINITION, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: Task 1 should keep its token $this->assertEquals(1, $task1->getTokens($instance)->count()); // Assertion: Task 3 has one token $this->assertEquals(1, $task3->getTokens($instance)->count()); // Complete first task $task1->complete($task1->getTokens($instance)->item(0)); $this->engine->runToNextState(); // Assertion: Task 2 is completed, an end event Signal is thrown, then caught by the boundary event $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: Task 1 complete its token $this->assertEquals(0, $task1->getTokens($instance)->count()); // Assertion: Task 4 has one token $this->assertEquals(1, $task4->getTokens($instance)->count()); } /** * Tests a process with a cycle timer boundary non interrupting event attached to a task */ public function testCycleTimerBoundaryEventNonInterrupting() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Timer_BoundaryEvent_Cycle_NonInterrupting.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $dataStore = $this->repository->createDataStore(); // Create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $bpmnRepository->getStartEvent('_2'); $task1 = $bpmnRepository->getActivity('_5'); $task2 = $bpmnRepository->getActivity('_12'); $boundaryEvent = $bpmnRepository->getBoundaryEvent('_11'); // Start a process instance $start->start($instance); $this->engine->runToNextState(); // Assertion: The process is started, a task is activated and a timer event scheduled $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, JobManagerInterface::EVENT_SCHEDULE_CYCLE, ]); // Boundary event is attached to $task1, its token is associated with the timer event $activeToken = $task1->getTokens($instance)->item(0); // Assertion: The jobs manager receive a scheduling request to trigger the start event time cycle specified in the process $this->assertScheduledCyclicTimer(new DatePeriod('R4/2018-05-01T00:00:00Z/PT1M'), $boundaryEvent, $activeToken); // Trigger the boundary event $boundaryEvent->execute($boundaryEvent->getEventDefinitions()->item(0), $instance); $this->engine->runToNextState(); // Assertion: Boundary event was caught, and one token is placed in task 2 $this->assertEvents([ BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Trigger the boundary event $boundaryEvent->execute($boundaryEvent->getEventDefinitions()->item(0), $instance); $this->engine->runToNextState(); // Assertion: Boundary event was caught again, and another token is placed in task 2 $this->assertEvents([ BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: Task 1 has one token and task 2 has two tokens $this->assertEquals(1, $task1->getTokens($instance)->count()); $this->assertEquals(2, $task2->getTokens($instance)->count()); // Complete second task $task1->complete($task1->getTokens($instance)->item(0)); $this->engine->runToNextState(); // Complete second task $task2->complete($task2->getTokens($instance)->item(1)); $this->engine->runToNextState(); $task2->complete($task2->getTokens($instance)->item(0)); $this->engine->runToNextState(); // Assertion: Three tokens completed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Tests a process with an error boundary non interrupting event attached to a script task */ public function testErrorBoundaryEventScriptTaskNonInterrupting() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Error_BoundaryEvent_ScriptTask_NonInterrupting.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $dataStore = $this->repository->createDataStore(); // Create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $bpmnRepository->getStartEvent('_2'); $task1 = $bpmnRepository->getScriptTask('_5'); $task2 = $bpmnRepository->getActivity('_12'); // Start a process instance $start->start($instance); $this->engine->runToNextState(); // Assertion: The process is started and the script activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); // Run the script task $activeToken = $task1->getTokens($instance)->item(0); $task1->runScript($activeToken); $this->engine->runToNextState(); // Assertion: Script task throws an exception $this->assertEvents([ ScriptTaskInterface::EVENT_ACTIVITY_EXCEPTION, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CATCH, BoundaryEventInterface::EVENT_BOUNDARY_EVENT_CONSUMED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Assertion: Task 2 is ACTIVE and Task 1 is in FAILING $this->assertEquals(1, $task2->getTokens($instance)->count()); $this->assertEquals(ActivityInterface::TOKEN_STATE_ACTIVE, $task2->getTokens($instance)->item(0)->getStatus()); $this->assertEquals(1, $task1->getTokens($instance)->count()); $this->assertEquals(ActivityInterface::TOKEN_STATE_FAILING, $task1->getTokens($instance)->item(0)->getStatus()); } /** * Tests a process with an error boundary non interrupting event attached to a CallActivity */ public function testErrorBoundaryEventCallActivityNonInterrupting() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Error_BoundaryEvent_CallActivity_NonInterrupting.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('PROCESS_1'); $dataStore = $this->repository->createDataStore(); // Create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $bpmnRepository->getStartEvent('_4'); $task1 = $bpmnRepository->getCallActivity('_7'); $task2 = $bpmnRepository->getActivity('_13'); // Start a process instance $start->start($instance);
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
true
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/SchemaValidationTest.php
tests/Feature/Engine/SchemaValidationTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Test a terminate event. */ class SchemaValidationTest extends EngineTestCase { /** * Test terminate end event */ public function testValidDefinitions() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); libxml_use_internal_errors(true); $bpmnRepository->load(__DIR__ . '/files/Lanes.bpmn'); $validation = $bpmnRepository->validateBPMNSchema(__DIR__ . '/xsd/BPMN20.xsd'); $this->assertTrue($validation); $this->assertEmpty($bpmnRepository->getValidationErrors()); } /** * Test terminate end event */ public function testInvalidDefinitions() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); libxml_use_internal_errors(true); $bpmnRepository->loadXML('Invalid BPMN'); $validation = $bpmnRepository->validateBPMNSchema(__DIR__ . '/xsd/BPMN20.xsd'); $this->assertFalse($validation); $this->assertNotEmpty($bpmnRepository->getValidationErrors()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/SignalEndEventTest.php
tests/Feature/Engine/SignalEndEventTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Bpmn\Models\Collaboration; use ProcessMaker\Nayra\Bpmn\Models\DataStoreCollection; use ProcessMaker\Nayra\Bpmn\Models\Participant; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateCatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateThrowEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ItemDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\SignalEventDefinitionInterface; /** * Test signal end events */ class SignalEndEventTest extends EngineTestCase { /** * Creates a process with a throwing signal and other with an end signal event * * @return array */ public function createSignalStartEventProcesses() { $item = $this->repository->createItemDefinition([ 'id' => 'item', 'isCollection' => true, 'itemKind' => ItemDefinitionInterface::ITEM_KIND_INFORMATION, 'structure' => 'String', ]); $signal = $this->repository->createMessage(); $signal->setId('SignalA'); $signal->setItem($item); //Process A $processA = $this->repository->createProcess(); $processA->setEngine($this->engine); $processA->setRepository($this->repository); $startA = $this->repository->createStartEvent(); $activityA1 = $this->repository->createActivity(); $eventA = $this->repository->createIntermediateCatchEvent(); $signalEventDefA = $this->repository->createSignalEventDefinition(); $signalEventDefA->setId('signalEvent1'); $signalEventDefA->setPayload($signal); $eventA->getEventDefinitions()->push($signalEventDefA); $activityA2 = $this->repository->createActivity(); $endA = $this->repository->createEndEvent(); $startA->createFlowTo($activityA1, $this->repository); $activityA1->createFlowTo($eventA, $this->repository); $eventA->createFlowTo($activityA2, $this->repository); $activityA2->createFlowTo($endA, $this->repository); $processA->addActivity($activityA1) ->addActivity($activityA2) ->addEvent($startA) ->addEvent($eventA) ->addEvent($endA); //Process B $processB = $this->repository->createProcess(); $processB->setEngine($this->engine); $processB->setRepository($this->repository); $startB = $this->repository->createStartEvent(); $activityB1 = $this->repository->createActivity(); $signalEventDefB = $this->repository->createSignalEventDefinition(); $signalEventDefB->setPayload($signal); $signalEndEventB = $this->repository->createEndEvent(); $signalEndEventB->getEventDefinitions()->push($signalEventDefB); $startB->createFlowTo($activityB1, $this->repository); $activityB1->createFlowTo($signalEndEventB, $this->repository); $processB->addActivity($activityB1) ->addEvent($startB) ->addEvent($signalEndEventB); return [$processA, $processB]; } /** * Tests the signal end event of a process */ public function testSignalEndEvent() { //Create two processes list($processA, $processB) = $this->createSignalStartEventProcesses(); //Create a collaboration $collaboration = new Collaboration; //Add process A as participant of the collaboration $participant = new Participant(); $participant->setProcess($processA); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); //Add process B as participant of the collaboration $participant = new Participant(); $participant->setProcess($processB); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); //Create message flow from intermediate events A to B $eventA = $processA->getEvents()->item(1); $signalEndEventB = $processB->getEvents()->item(1); $messageFlow = $this->repository->createMessageFlow(); $messageFlow->setCollaboration($collaboration); $messageFlow->setSource($signalEndEventB); $messageFlow->setTarget($eventA); $collaboration->addMessageFlow($messageFlow); $eventA = $processA->getEvents()->item(1); $eventB = $processB->getEvents()->item(1); $dataStoreA = $this->repository->createDataStore(); $dataStoreA->putData('A', '1'); $dataStoreB = $this->repository->createDataStore(); $dataStoreB->putData('B', '1'); $dataStoreCollectionA = new DataStoreCollection(); $dataStoreCollectionA->add($dataStoreA); $dataStoreCollectionB = new DataStoreCollection(); $dataStoreCollectionB->add($dataStoreB); $processA->setDataStores($dataStoreCollectionA); $processB->setDataStores($dataStoreCollectionB); $instanceA = $this->engine->createExecutionInstance($processA, $dataStoreA); $instanceB = $this->engine->createExecutionInstance($processB, $dataStoreB); // we start the second process and run it up to the end $startB = $processB->getEvents()->item(0); $activityB1 = $processB->getActivities()->item(0); // we start the process A $startA = $processA->getEvents()->item(0); $activityA1 = $processA->getActivities()->item(0); $startA->start($instanceA); $this->engine->runToNextState(); //Assertion: The activity must be activated $this->assertEvents([ //Instance for process A ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, //Instance for process B ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // we finish the first activity so that the catch signal is activated $tokenA = $activityA1->getTokens($instanceA)->item(0); $activityA1->complete($tokenA); $this->engine->runToNextState(); $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_ARRIVES, ]); //Start the process B $startB->start($instanceB); $this->engine->runToNextState(); //Assertion: Process B - The activity must be activated $this->assertEvents([ EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Complete the activity $tokenB = $activityB1->getTokens($instanceB)->item(0); $activityB1->complete($tokenB); $this->engine->runToNextState(); //Assertion: Process B - The activity is completed and the end event must be activated $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, // the throw token of the end is sent EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, SignalEventDefinitionInterface::EVENT_THROW_EVENT_DEFINITION, // the Process A catching message is activated IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CATCH, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_MESSAGE_CONSUMED, IntermediateCatchEventInterface::EVENT_CATCH_TOKEN_PASSED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, // the Process B end throw event must consume its tokens IntermediateThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/ParallelGatewayTest.php
tests/Feature/Engine/ParallelGatewayTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\InclusiveGatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ParallelGatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface; /** * Test transitions */ class ParallelGatewayTest extends EngineTestCase { /** * Parallel Gateway * ┌─────────┐ * ┌─→│activityA│─┐ *  ○─→╱╲─┘ └─────────┘ └─→╱╲ ┌─────────┐ * ╲╱─┐ ┌─────────┐ ┌─→╲╱─→│activityC│─→● * A └─→│activityB│─┘ B └─────────┘ * └─────────┘ * * @return \ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface */ private function createProcessWithParallelGateway() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createParallelGateway(); $activityA = $this->repository->createActivity(); $activityB = $this->repository->createActivity(); $activityC = $this->repository->createActivity(); $gatewayB = $this->repository->createParallelGateway(); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB) ->addActivity($activityC); $process ->addGateway($gatewayA) ->addGateway($gatewayB); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createFlowTo($activityA, $this->repository) ->createFlowTo($activityB, $this->repository); $activityA->createFlowTo($gatewayB, $this->repository); $activityB->createFlowTo($gatewayB, $this->repository); $gatewayB->createFlowTo($activityC, $this->repository); $activityC->createFlowTo($end, $this->repository); return $process; } /** * Parallel Diverging Inclusive converging * ┌─────────┐ * ┌─→│activityA│─┐ *  ○─→╱╲─┘ └─────────┘ └─→╱╲ ┌─────────┐ * ╲╱─┐ ┌─────────┐ ┌─→╲╱─→│activityC│─→● * A └─→│activityB│─┘ B └─────────┘ * Parallel └─────────┘ Inclusive * * @return \ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface */ private function createParallelDivergingInclusiveConverging() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createParallelGateway(); $activityA = $this->repository->createActivity(); $activityB = $this->repository->createActivity(); $activityC = $this->repository->createActivity(); $gatewayB = $this->repository->createInclusiveGateway(); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB) ->addActivity($activityC); $process ->addGateway($gatewayA) ->addGateway($gatewayB); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createFlowTo($activityA, $this->repository) ->createFlowTo($activityB, $this->repository); $activityA->createFlowTo($gatewayB, $this->repository); $activityB->createFlowTo($gatewayB, $this->repository); $gatewayB->createFlowTo($activityC, $this->repository); $activityC->createFlowTo($end, $this->repository); return $process; } /** * Test a parallel gateway with two outgoing flows. */ public function testParallelGateway() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); //Load the process $process = $this->createProcessWithParallelGateway(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activityA = $process->getActivities()->item(0); $activityB = $process->getActivities()->item(1); $activityC = $process->getActivities()->item(2); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Completes the Activity A $tokenA = $activityA->getTokens($instance)->item(0); $activityA->complete($tokenA); //the run to next state should go false when the max steps is reached. $this->assertFalse($this->engine->runToNextState(1)); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); //Completes the Activity B $tokenB = $activityB->getTokens($instance)->item(0); $activityB->complete($tokenB); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity B is closed and process is ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Assertion: ActivityC has one token. $this->assertEquals(1, $activityC->getTokens($instance)->count()); //Completes the Activity C $tokenC = $activityC->getTokens($instance)->item(0); $activityC->complete($tokenC); $this->engine->runToNextState(); //Assertion: ActivityC has no tokens. $this->assertEquals(0, $activityC->getTokens($instance)->count()); //Assertion: ActivityC was completed and closed, then the process has ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test parallel diverging then inclusive converging. * * Two of the tasks are executed in parallel and merged by the inclusiveGateway. */ public function testParallelDivergingInclusiveConverging() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); //Load the process $process = $this->createParallelDivergingInclusiveConverging(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activityA = $process->getActivities()->item(0); $activityB = $process->getActivities()->item(1); $activityC = $process->getActivities()->item(2); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Completes the Activity A $tokenA = $activityA->getTokens($instance)->item(0); $activityA->complete($tokenA); //the run to next state should go false when the max steps is reached. $this->assertFalse($this->engine->runToNextState(1)); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); //Completes the Activity B $tokenB = $activityB->getTokens($instance)->item(0); $activityB->complete($tokenB); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity B is closed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Assertion: ActivityC has one token. $this->assertEquals(1, $activityC->getTokens($instance)->count()); //Completes the Activity C $tokenC = $activityC->getTokens($instance)->item(0); $activityC->complete($tokenC); $this->engine->runToNextState(); //Assertion: ActivityC has no tokens. $this->assertEquals(0, $activityC->getTokens($instance)->count()); //Assertion: ActivityC was completed and closed, then the process has ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test parallel gateway can not have conditioned outgoing flows. */ public function testParallelCanNotHaveConditionedOutgoingFlow() { //Create a parallel gateway and an activity. $gatewayA = $this->repository->createParallelGateway(); $activityA = $this->repository->createActivity(); //Assertion: Throw exception when creating a conditioned flow from parallel. $this->expectException('ProcessMaker\Nayra\Exceptions\InvalidSequenceFlowException'); $gatewayA->createConditionedFlowTo($activityA, function () { }, false, $this->repository); $process = $this->repository->createProcess(); $process ->addActivity($activityA) ->addGateway($gatewayA); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/BpmnDocumentHtmlEntitiesTest.php
tests/Feature/Engine/BpmnDocumentHtmlEntitiesTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Storage\BpmnDocument; use DOMDocument; /** * Test for handling HTML entities in BPMN files. */ class BpmnDocumentHtmlEntitiesTest extends EngineTestCase { /** * Test the replaceHtmlEntities method directly. */ public function testReplaceHtmlEntities() { // String with HTML entities $source = 'This is a text with &lt;html&gt; entities &amp; special chars like &quot;quotes&quot; and &apos;apostrophes&apos; and &nbsp;spaces.'; // Expected result after replacement $expected = 'This is a text with &#60;html&#62; entities &#38; special chars like &#34;quotes&#34; and &#39;apostrophes&#39; and &#160;spaces.'; // Test the static method $result = BpmnDocument::replaceHtmlEntities($source); // Assert the result matches the expected output $this->assertEquals($expected, $result); } /** * Test loadXML with HTML entities. */ public function testLoadXmlWithHtmlEntities() { // Create a BPMN XML string with HTML entities in the documentation tag $bpmnXml = file_get_contents(__DIR__ . '/files/BpmnWithHtmlEntities.bpmn'); // 1. First try to load with regular DOMDocument - should fail or produce incorrect results $regularDom = new DOMDocument(); $regularLoaded = @$regularDom->loadXML($bpmnXml); // @ to suppress warnings // If it loads without errors, check that the content is different from what we expect if ($regularLoaded) { $startEventDoc = $regularDom->getElementsByTagName('documentation')->item(0); $originalContent = $startEventDoc ? $startEventDoc->textContent : ''; // The content should be mangled or different from what we expect with proper entity handling $expectedContent = 'This contains <b>HTML</b> entities & special chars like "quotes" and \'apostrophes\' and spaces.'; $this->assertNotEquals($expectedContent, $originalContent, 'Standard DOMDocument should not correctly handle HTML entities'); } // 2. Now load with BpmnDocument which should handle HTML entities correctly $bpmnDocument = new BpmnDocument(); $bpmnDocument->setEngine($this->engine); $bpmnDocument->setFactory($this->repository); // Load the XML with HTML entities $result = $bpmnDocument->loadXML($bpmnXml); $this->assertTrue($result, 'BpmnDocument should successfully load the XML with HTML entities'); // Verify that documentation tags contain correctly converted entities $startEventDoc = $bpmnDocument->getElementsByTagName('documentation')->item(0); $this->assertNotNull($startEventDoc, 'Documentation element should exist'); // The text content should have the HTML entities properly converted $nbsp = "\xC2\xA0"; $expectedContent = 'This contains <b>HTML</b> entities & special chars like "quotes" and \'apostrophes\' and ' . $nbsp . 'spaces.'; $this->assertEquals($expectedContent, $startEventDoc->textContent, 'HTML entities should be correctly converted'); // Check the second documentation tag too $taskDoc = $bpmnDocument->getElementsByTagName('documentation')->item(1); $this->assertNotNull($taskDoc, 'Second documentation element should exist'); $expectedTaskContent = 'Another <strong>documentation</strong> with & entities.'; $this->assertEquals($expectedTaskContent, $taskDoc->textContent, 'HTML entities in second documentation should be correctly converted'); } /** * Test loading a complex BPMN with HTML entities in various places. */ public function testLoadComplexBpmnWithHtmlEntities() { // Create a more complex BPMN with HTML entities in various attributes and text content $complexBpmnXml = file_get_contents(__DIR__ . '/files/BpmnWithComplexHtml.bpmn'); // Load with BpmnDocument $bpmnDocument = new BpmnDocument(); $bpmnDocument->setEngine($this->engine); $bpmnDocument->setFactory($this->repository); $result = $bpmnDocument->loadXML($complexBpmnXml); $this->assertTrue($result, 'BpmnDocument should successfully load complex XML with HTML entities'); // Check process name attribute $process = $bpmnDocument->getElementsByTagName('process')->item(0); $this->assertEquals('Process & HTML entities', $process->getAttribute('name'), 'Process name attribute should have entities converted'); // Check start event name attribute $startEvent = $bpmnDocument->getElementsByTagName('startEvent')->item(0); $this->assertEquals('Start <event>', $startEvent->getAttribute('name'), 'Start event name attribute should have entities converted'); // Check documentation content $documentation = $startEvent->getElementsByTagName('documentation')->item(0); $this->assertEquals( 'Documentation with <ul><li>HTML list</li></ul> and & "quotes"', $documentation->textContent, 'Documentation should have entities converted' ); // Check sequence flow name attribute $sequenceFlow = $bpmnDocument->getElementsByTagName('sequenceFlow')->item(0); $this->assertEquals( 'Flow with & special "chars"', $sequenceFlow->getAttribute('name'), 'Sequence flow name attribute should have entities converted' ); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/InclusiveGatewayTest.php
tests/Feature/Engine/InclusiveGatewayTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Bpmn\DefaultTransition; use ProcessMaker\Nayra\Bpmn\Models\InclusiveGateway; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\InclusiveGatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface; /** * Test transitions */ class InclusiveGatewayTest extends EngineTestCase { /** * Inclusive Gateway * ┌─────────┐ * ┌─→│activityA│─┐ *  ○─→╱╲─┘ └─────────┘ └─→╱╲ * ╲╱─┐ ┌─────────┐ ┌─→╲╱─→● * A └─→│activityB│─┘ B * └─────────┘ * * @return \ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface */ private function createProcessWithInclusiveGateway() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createInclusiveGateway(); $activityA = $this->repository->createActivity(); $activityB = $this->repository->createActivity(); $gatewayB = $this->repository->createInclusiveGateway(); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB); $process ->addGateway($gatewayA) ->addGateway($gatewayB); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createConditionedFlowTo($activityA, function ($data) { return $data['A'] == '1'; }, false, $this->repository) ->createConditionedFlowTo($activityB, function ($data) { return $data['B'] == '1'; }, false, $this->repository); $activityA->createFlowTo($gatewayB, $this->repository); $activityB->createFlowTo($gatewayB, $this->repository); $gatewayB->createFlowTo($end, $this->repository); return $process; } /** * Creates a process that has a default transition * * @return \ProcessMaker\Models\Process */ private function createProcessWithDefaultTransition() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createInclusiveGateway(); $gatewayB = $this->repository->createInclusiveGateway(); $gatewayA->name = 'A'; $gatewayB->name = 'B'; $activityA = $this->repository->createActivity(); $activityB = $this->repository->createActivity(); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB); $process ->addGateway($gatewayA) ->addGateway($gatewayB); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createConditionedFlowTo($activityA, function ($data) { return $data['A'] == '1'; }, false, $this->repository) ->createConditionedFlowTo($activityB, function ($data) { return true; }, true, $this->repository); $activityA->createFlowTo($gatewayB, $this->repository); $activityB->createFlowTo($gatewayB, $this->repository); $gatewayB->createFlowTo($end, $this->repository); return $process; } /** * Test a inclusive gateway with two outgoing flows. * * Test transitions from start event, inclusive gateways, activities and end event, * with two activities activated. */ public function testInclusiveGatewayAllPaths() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('A', '1'); $dataStore->putData('B', '1'); //Load the process $process = $this->createProcessWithInclusiveGateway(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activityA = $process->getActivities()->item(0); $activityB = $process->getActivities()->item(1); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Completes the Activity A $tokenA = $activityA->getTokens($instance)->item(0); $activityA->complete($tokenA); //the run to next state should go false when the max steps is reached. $this->assertFalse($this->engine->runToNextState(1)); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); //Completes the Activity B $tokenB = $activityB->getTokens($instance)->item(0); $activityB->complete($tokenB); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed and process is ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test a inclusive gateway with one activated outgoing flow. * * Test transitions from start event, inclusive gateways, two activities and one end event, * with only one activity (B) activated. */ public function testInclusiveGatewayOnlyB() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('A', '0'); $dataStore->putData('B', '1'); $process = $this->createProcessWithInclusiveGateway(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activityA = $process->getActivities()->item(0); $activityB = $process->getActivities()->item(1); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. One activity is activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Completes the Activity B $tokenB = $activityB->getTokens($instance)->item(0); $activityB->complete($tokenB); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed and process is ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test that a process with a default transition is created and run correctly */ public function testDefaultTransition() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('A', '2'); $process = $this->createProcessWithDefaultTransition(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: The correct events of the default transition should be triggered $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, DefaultTransition::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); $dataStore->putData('A', '1'); $process = $this->createProcessWithDefaultTransition(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: The correct events of the default transition should be triggered $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/InclusiveGatewayDemoTest.php
tests/Feature/Engine/InclusiveGatewayDemoTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; /** * Test transitions */ class InclusiveGatewayDemoTest extends EngineTestCase { /** * Inclusive Gateway * ┌─────────┐ * ┌─→│activityA│─┐ *  ○─→╱╲─┘ └─────────┘ └─→╱╲ * ╲╱─┐ ┌─────────┐ ┌─→╲╱─→● * A └─→│activityB│─┘ B * └─────────┘ * * @return \ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface */ private function createProcessWithInclusiveGateway() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createInclusiveGateway()->setId('GatewayA'); $activityA = $this->repository->createActivity()->setName('Activity A'); $activityB = $this->repository->createActivity()->setName('Activity B'); $gatewayB = $this->repository->createInclusiveGateway()->setId('GatewayB'); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB); $process ->addGateway($gatewayA) ->addGateway($gatewayB); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createConditionedFlowTo($activityA, function ($data) { return $data['A'] == '1'; }, false, $this->repository) ->createConditionedFlowTo($activityB, function ($data) { return $data['B'] == '1'; }, false, $this->repository); $activityA->createFlowTo($gatewayB, $this->repository); $activityB->createFlowTo($gatewayB, $this->repository); $gatewayB->createFlowTo($end, $this->repository); return $process; } /** * Creates a process that has a default transition * * @return \ProcessMaker\Models\Process */ private function createProcessWithDefaultTransition() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createInclusiveGateway(); $gatewayB = $this->repository->createInclusiveGateway(); $gatewayA->name = 'A'; $gatewayB->name = 'B'; $activityA = $this->repository->createActivity()->setName('Activity A'); $activityB = $this->repository->createActivity()->setName('Activity B'); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB); $process ->addGateway($gatewayA) ->addGateway($gatewayB); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createConditionedFlowTo($activityA, function ($data) { return $data['A'] == '1'; }, false, $this->repository) ->createConditionedFlowTo($activityB, function ($data) { return true; }, true, $this->repository); $activityA->createFlowTo($gatewayB, $this->repository); $activityB->createFlowTo($gatewayB, $this->repository); $gatewayB->createFlowTo($end, $this->repository); return $process; } /** * Test a inclusive gateway with two outgoing flows. * * Test transitions from start event, inclusive gateways, activities and end event, * with two activities activated. */ public function testInclusiveGatewayAllPaths() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); $dataStore->putData('A', '1'); $dataStore->putData('B', '1'); // Enable demo mode $this->engine->setDemoMode(true); //Load the process $process = $this->createProcessWithInclusiveGateway(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activityA = $process->getActivities()->item(0); $activityB = $process->getActivities()->item(1); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, // GatewayInterface::EVENT_GATEWAY_ACTIVATED, // GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, // GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, // GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, // ActivityInterface::EVENT_ACTIVITY_ACTIVATED, // ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // Select the flow for the gateway and run the engine $gateway = $process->getGateways()->item(0); $selectedFlow = $gateway->getOutgoingFlows()->item(0); $this->engine->setSelectedDemoFlow($gateway, $selectedFlow); $this->engine->runToNextState(); // Assertion: Engine runs to the next state because a flow was selected manually $this->assertEvents([ GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Only one activity is activated because only one flow was selected manually $this->assertCount(1, $activityA->getTokens($instance)); //Completes the Activity A $tokenA = $activityA->getTokens($instance)->item(0); $activityA->complete($tokenA); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); // Select the flow for the gateway B and run the engine $gateway = $process->getGateways()->item(1); $selectedFlow = $gateway->getOutgoingFlows()->item(0); $this->engine->setSelectedDemoFlow($gateway, $selectedFlow); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed and process is ended. $this->assertEvents([ GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/ParallelGatewayDemoTest.php
tests/Feature/Engine/ParallelGatewayDemoTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; /** * Test transitions */ class ParallelGatewayDemoTest extends EngineTestCase { /** * Parallel Gateway * ┌─────────┐ * ┌─→│activityA│─┐ *  ○─→╱╲─┘ └─────────┘ └─→╱╲ ┌─────────┐ * ╲╱─┐ ┌─────────┐ ┌─→╲╱─→│activityC│─→● * A └─→│activityB│─┘ B └─────────┘ * └─────────┘ * * @return \ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface */ private function createProcessWithParallelGateway() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent()->setId('start'); $gatewayA = $this->repository->createParallelGateway()->setId('gatewayA'); $activityA = $this->repository->createActivity()->setId('ActivityA'); $activityB = $this->repository->createActivity()->setId('ActivityB'); $activityC = $this->repository->createActivity()->setId('ActivityC'); $gatewayB = $this->repository->createParallelGateway()->setId('gatewayB'); $end = $this->repository->createEndEvent()->setId('end'); $process ->addActivity($activityA) ->addActivity($activityB) ->addActivity($activityC); $process ->addGateway($gatewayA) ->addGateway($gatewayB); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createFlowTo($activityA, $this->repository) ->createFlowTo($activityB, $this->repository); $activityA->createFlowTo($gatewayB, $this->repository); $activityB->createFlowTo($gatewayB, $this->repository); $gatewayB->createFlowTo($activityC, $this->repository); $activityC->createFlowTo($end, $this->repository); return $process; } /** * Parallel Diverging Inclusive converging * ┌─────────┐ * ┌─→│activityA│─┐ *  ○─→╱╲─┘ └─────────┘ └─→╱╲ ┌─────────┐ * ╲╱─┐ ┌─────────┐ ┌─→╲╱─→│activityC│─→● * A └─→│activityB│─┘ B └─────────┘ * Parallel └─────────┘ Inclusive * * @return \ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface */ private function createParallelDivergingInclusiveConverging() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $gatewayA = $this->repository->createParallelGateway(); $activityA = $this->repository->createActivity(); $activityB = $this->repository->createActivity(); $activityC = $this->repository->createActivity(); $gatewayB = $this->repository->createInclusiveGateway(); $end = $this->repository->createEndEvent(); $process ->addActivity($activityA) ->addActivity($activityB) ->addActivity($activityC); $process ->addGateway($gatewayA) ->addGateway($gatewayB); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $this->repository); $gatewayA ->createFlowTo($activityA, $this->repository) ->createFlowTo($activityB, $this->repository); $activityA->createFlowTo($gatewayB, $this->repository); $activityB->createFlowTo($gatewayB, $this->repository); $gatewayB->createFlowTo($activityC, $this->repository); $activityC->createFlowTo($end, $this->repository); return $process; } /** * Test a parallel gateway with two outgoing flows. */ public function testParallelGateway() { //Create a data store with data. $dataStore = $this->repository->createDataStore(); // Enable demo mode $this->engine->setDemoMode(true); //Load the process $process = $this->createProcessWithParallelGateway(); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); $activityA = $process->getActivities()->item(0); $activityB = $process->getActivities()->item(1); $activityC = $process->getActivities()->item(2); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); // Select the flow for the gateway and run the engine $gateway = $process->getGateways()->item(0); $selectedFlow = $gateway->getOutgoingFlows()->item(0); $this->engine->setSelectedDemoFlow($gateway, $selectedFlow); $this->engine->runToNextState(); //Assertion: Verify the Activity A was activated $this->assertEvents([ GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Completes the Activity A $tokenA = $activityA->getTokens($instance)->item(0); $activityA->complete($tokenA); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); // Select the flow for the gateway B and run the engine $gateway = $process->getGateways()->item(1); $selectedFlow = $gateway->getOutgoingFlows()->item(0); $this->engine->setSelectedDemoFlow($gateway, $selectedFlow); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed. $this->assertEvents([ GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Assertion: ActivityC has one token. $this->assertEquals(1, $activityC->getTokens($instance)->count()); //Completes the Activity C $tokenC = $activityC->getTokens($instance)->item(0); $activityC->complete($tokenC); $this->engine->runToNextState(); //Assertion: ActivityC has no tokens. $this->assertEquals(0, $activityC->getTokens($instance)->count()); //Assertion: ActivityC was completed and closed, then the process has ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/BasicsTest.php
tests/Feature/Engine/BasicsTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DiagramInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface; use ProcessMaker\Nayra\Exceptions\InvalidSequenceFlowException; /** * Test transitions */ class BasicsTest extends EngineTestCase { /** * Create a simple process * * ┌────────┐ *  ○─→│activity│─→● * └────────┘ * * * @return \ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface */ private function createSimpleProcessInstance() { $process = $this->repository->createProcess(); //elements $start = $this->repository->createStartEvent(); $activity = $this->repository->createActivity(); $end = $this->repository->createEndEvent(); $process->addActivity($activity); $process->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($activity, $this->repository); $activity->createFlowTo($end, $this->repository); return $process; } /** * Sequence flow * * Test transitions between start event, activity and end event. */ public function testSimpleTransitions() { //Create a data store $dataStore = $this->repository->createDataStore(); //Load the process $process = $this->createSimpleProcessInstance(); //Create a process instance with the data store $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get references to start event and activity $start = $process->getEvents()->item(0); $activity = $process->getActivities()->item(0); //Assertion: Verify the activity has no tokens $this->assertEquals(0, $activity->getTokens($instance)->count()); //Trigger start event $start->start($instance); $this->engine->runToNextState(); $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, StartEventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Assertion: Verify the activity has one token $this->assertEquals(1, $activity->getTokens($instance)->count()); //Get the current token $token = $activity->getTokens($instance)->item(0); //Assertion: Verify the token refers to the activity $this->assertEquals($activity, $token->getOwnerElement()); //Complete the activity $activity->complete($token); $this->engine->runToNextState(); //Assertion: Verify the close events $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); //Assertion: Verify the activity has no tokens $this->assertEquals(0, $activity->getTokens($instance)->count()); } /** * Tests that a process structure has been configured correctly */ public function testProcessConfiguration() { //Create a data store $dataStore = $this->repository->createDataStore(); //Load the process $process = $this->createSimpleProcessInstance(); //Create a process instance with the data store $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get references to start event and activity $start = $process->getEvents()->item(0); $activity = $process->getActivities()->item(0); $end = $process->getEvents()->item(1); //Assertion: no tokens are returned from the end event $this->assertCount(0, $end->getTokens($instance)); //Assertion: neither targets nor origins should be null $this->assertNotNull($start->getTransitions()[0]->outgoing()->item(0)->target()); $this->assertNotNull($start->getTransitions()[0]->outgoing()->item(0)->origin()); //Assertion: the start event should not have tokens $this->assertCount(0, $start->getTokens($instance)); //Assertion: the set/get methods of the diagram should work $diagram = $this->getMockForAbstractClass(DiagramInterface::class); $process->setDiagram($diagram); $this->assertEquals($diagram, $process->getDiagram()); } /** * Tests that a process structure has been configured incorrectly */ public function testProcessIncorrectConfiguration() { //Create a data store $dataStore = $this->repository->createDataStore(); //Load the process $process = $this->createSimpleProcessInstance(); //Get reference to end event and activity $end = $process->getEvents()->item(1); $activity = $process->getActivities()->item(0); //Try to add and invalid flow to the end event try { $end->createFlowTo($activity, $this->repository); $this->engine->createExecutionInstance($process, $dataStore); } catch (InvalidSequenceFlowException $e) { $this->assertNotNull($e->getMessage()); } } /** * Tests that when a script fails, then it is closed */ public function testCloseDirectlyActiveTask() { //Load a process $process = $this->createSimpleProcessInstance(); $dataStore = $this->repository->createDataStore(); //create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); //Get References $start = $process->getEvents()->item(0); //start the process an instance of the process $start->start($instance); $this->engine->runToNextState(); //Assert: that the process is stared and the first activity activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //close the process instance $instance->close(); $this->engine->runToNextState(); //Assertion: Verify that the process instance was completed $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_CANCELLED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Test next state callback method. */ public function testEngineNextStateCallback() { // Register a next state callback $this->checked = false; $this->engine->nextState(function () { $this->checked = true; }); // Load a process $process = $this->createSimpleProcessInstance(); $dataStore = $this->repository->createDataStore(); // create an instance of the process $instance = $this->engine->createExecutionInstance($process, $dataStore); // Get References $start = $process->getEvents()->item(0); //start the process an instance of the process $start->start($instance); $this->engine->runToNextState(); // Assertion: Next state callback was executed $this->assertTrue($this->checked); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/NayraModelTest.php
tests/Feature/Engine/NayraModelTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Bpmn\Models\Collaboration; use ProcessMaker\Nayra\Bpmn\Models\DataStoreCollection; use ProcessMaker\Nayra\Bpmn\Models\EventDefinitionBus; use ProcessMaker\Nayra\Bpmn\Models\Participant; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ExclusiveGatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\InclusiveGatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateCatchEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateThrowEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\SignalEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\TransitionInterface; use ProcessMaker\Nayra\Contracts\RepositoryInterface; /** * Tests for the Nayra/Bpmn/Model classes */ class NayraModelTest extends EngineTestCase { /** * Tests a process with exclusive gateways that uses the Nayra/Bpmn/Model classes */ public function testProcessWithExclusiveGateway() { $processData = $this->createProcessWithExclusiveGateway($this->repository); $process = $processData['process']; $start = $processData['start']; $activityA = $processData['activityA']; $activityB = $processData['activityB']; $activityC = $processData['activityC']; $dataStore = $processData['dataStore']; $dataStore->putData('A', '2'); $dataStore->putData('B', '1'); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, TransitionInterface::EVENT_CONDITIONED_TRANSITION, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); $tokenB = $activityB->getTokens($instance)->item(0); $activityB->complete($tokenB); //the run to next state should go false when the max steps is reached. $this->assertFalse($this->engine->runToNextState(1)); } /** * Tests a process with inclusive gateways that uses the Nayra/Bpmn/Model classes */ public function testProcessWithInclusiveGateway() { $processData = $this->createProcessWithInclusiveGateway($this->repository); $process = $processData['process']; $start = $processData['start']; $activityA = $processData['activityA']; $activityB = $processData['activityB']; $dataStore = $processData['dataStore']; $dataStore->putData('A', '1'); $dataStore->putData('B', '1'); $instance = $this->engine->createExecutionInstance($process, $dataStore); //Start the process $start->start($instance); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. Two activities are activated. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); //Completes the Activity A $tokenA = $activityA->getTokens($instance)->item(0); $activityA->complete($tokenA); //the run to next state should go false when the max steps is reached. $this->assertFalse($this->engine->runToNextState(1)); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, ]); //Completes the Activity B $tokenB = $activityB->getTokens($instance)->item(0); $activityB->complete($tokenB); $this->engine->runToNextState(); //Assertion: Verify the triggered engine events. The activity is closed and process is ended. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Tests a event bus with a collaboration */ public function testEventBusSetAndGetCollaboration() { //Create a collaboration $collaboration = new Collaboration; $eventBus = new EventDefinitionBus; $eventBus->setCollaboration($collaboration); //Assert that the collaboration is correctly set $this->assertEquals($collaboration, $eventBus->getCollaboration()); } /** * Creates a process that contains an exclusive gateway, start, end events and activities * * @param RepositoryInterface $factory * * @return array */ private function createProcessWithExclusiveGateway(RepositoryInterface $factory) { $process = $factory->createProcess(); $start = $factory->createStartEvent(); $gatewayA = $factory->createExclusiveGateway(); $activityA = $factory->createActivity(); $activityB = $factory->createActivity(); $activityC = $factory->createActivity(); $end = $factory->createEndEvent(); $dataStore = $factory->createDataStore(); $process ->addActivity($activityA) ->addActivity($activityB) ->addActivity($activityC); $process ->addGateway($gatewayA); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $factory); $gatewayA ->createConditionedFlowTo($activityA, function ($data) { return $data['A'] == '1'; }, false, $factory) ->createConditionedFlowTo($activityB, function ($data) { return $data['B'] == '1'; }, false, $factory) ->createFlowTo($activityC, $factory); $activityA->createFlowTo($end, $factory); $activityB->createFlowTo($end, $factory); $activityC->createFlowTo($end, $factory); return [ 'process' => $process, 'start' => $start, 'gatewayA' => $gatewayA, 'activityA' => $activityA, 'activityB' => $activityB, 'activityC' => $activityC, 'end' => $end, 'dataStore' => $dataStore, ]; } /** * Creates a process that contains an inclusive gateway, start, end events and activities * * @param FactoryInterface $factory * * @return array */ private function createProcessWithInclusiveGateway($factory) { $process = $factory->createProcess(); $start = $factory->createStartEvent(); $gatewayA = $factory->createInclusiveGateway(); $gatewayB = $factory->createInclusiveGateway(); $activityA = $factory->createActivity(); $activityB = $factory->createActivity(); $end = $factory->createEndEvent(); $dataStore = $factory->createDataStore(); $process ->addActivity($activityA) ->addActivity($activityB); $process ->addGateway($gatewayA) ->addGateway($gatewayB); $process ->addEvent($start) ->addEvent($end); //flows $start->createFlowTo($gatewayA, $factory); $gatewayA ->createConditionedFlowTo($activityA, function ($data) { return $data['A'] == '1'; }, false, $factory) ->createConditionedFlowTo($activityB, function ($data) { return $data['B'] == '1'; }, false, $factory); $activityA->createFlowTo($gatewayB, $factory); $activityB->createFlowTo($gatewayB, $factory); $gatewayB->createFlowTo($end, $factory); return [ 'process' => $process, 'start' => $start, 'gatewayA' => $gatewayA, 'gatewayB' => $gatewayB, 'activityA' => $activityA, 'activityB' => $activityB, 'end' => $end, 'dataStore' => $dataStore, ]; } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/SignalStartEventTest.php
tests/Feature/Engine/SignalStartEventTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Bpmn\Models\Collaboration; use ProcessMaker\Nayra\Bpmn\Models\DataStoreCollection; use ProcessMaker\Nayra\Bpmn\Models\Participant; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateThrowEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ItemDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Test signal start events */ class SignalStartEventTest extends EngineTestCase { /** * Creates a process with a throwing signal and other with a start signal event * * @return array */ public function createSignalStartEventProcesses() { $item = $this->repository->createItemDefinition([ 'id' => 'item', 'isCollection' => true, 'itemKind' => ItemDefinitionInterface::ITEM_KIND_INFORMATION, 'structure' => 'String', ]); $signal = $this->repository->createMessage(); $signal->setId('SignalA'); $signal->setItem($item); //Process A $processA = $this->repository->createProcess(); $processA->setEngine($this->engine); $processA->setRepository($this->repository); $startA = $this->repository->createStartEvent(); $activityA1 = $this->repository->createActivity(); $eventA = $this->repository->createIntermediateThrowEvent(); $signalEventDefA = $this->repository->createSignalEventDefinition(); $signalEventDefA->setId('signalEvent1'); $signalEventDefA->setPayload($signal); $eventA->getEventDefinitions()->push($signalEventDefA); $activityA2 = $this->repository->createActivity(); $endA = $this->repository->createEndEvent(); $startA->createFlowTo($activityA1, $this->repository); $activityA1->createFlowTo($eventA, $this->repository); $eventA->createFlowTo($activityA2, $this->repository); $activityA2->createFlowTo($endA, $this->repository); $processA->addActivity($activityA1) ->addActivity($activityA2) ->addEvent($startA) ->addEvent($eventA) ->addEvent($endA); //Process B $processB = $this->repository->createProcess(); $processB->setEngine($this->engine); $processB->setRepository($this->repository); $activityB1 = $this->repository->createActivity(); $signalEventDefB = $this->repository->createSignalEventDefinition(); $signalEventDefB->setPayload($signal); $signalStartEventB = $this->repository->createStartEvent(); $signalStartEventB->getEventDefinitions()->push($signalEventDefB); $endB = $this->repository->createEndEvent(); $signalStartEventB->createFlowTo($activityB1, $this->repository); $activityB1->createFlowTo($endB, $this->repository); $processB->addActivity($activityB1) ->addEvent($signalStartEventB) ->addEvent($endB); return [$processA, $processB]; } /** * Tests the start of a process when it receives a signal */ public function testSignalStartEvent() { //Create two processes list($processA, $processB) = $this->createSignalStartEventProcesses(); //Create a collaboration $collaboration = new Collaboration; //Add process A as participant of the collaboration $participant = new Participant(); $participant->setProcess($processA); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); //Add process B as participant of the collaboration $participant = new Participant(); $participant->setProcess($processB); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); //Create message flow from intermediate events A to B $eventA = $processA->getEvents()->item(1); $signalStartEventB = $processB->getEvents()->item(0); $messageFlow = $this->repository->createMessageFlow(); $messageFlow->setCollaboration($collaboration); $messageFlow->setSource($eventA); $messageFlow->setTarget($signalStartEventB); $collaboration->addMessageFlow($messageFlow); $eventA = $processA->getEvents()->item(1); $eventB = $processB->getEvents()->item(1); $dataStoreA = $this->repository->createDataStore(); $dataStoreA->putData('A', '1'); $dataStoreB = $this->repository->createDataStore(); $dataStoreB->putData('B', '1'); $dataStoreCollectionA = new DataStoreCollection(); $dataStoreCollectionA->add($dataStoreA); $dataStoreCollectionB = new DataStoreCollection(); $dataStoreCollectionB->add($dataStoreB); $processA->setDataStores($dataStoreCollectionA); $processB->setDataStores($dataStoreCollectionB); $this->engine->loadProcess($processB); $instanceA = $this->engine->createExecutionInstance($processA, $dataStoreA); // we start the process A $startA = $processA->getEvents()->item(0); $activityA1 = $processA->getActivities()->item(0); $startA->start($instanceA); $this->engine->runToNextState(); //Assertion: The activity must be activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // we finish the first activity so that a new event should be created in the second process $tokenA = $activityA1->getTokens($instanceA)->item(0); $activityA1->complete($tokenA); $this->engine->runToNextState(); //Assertion: The process1 activity should be finished and a new instance of the second process must be created $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, //Events triggered when the catching event runs IntermediateThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_PASSED, //Next activity should be activated in the first process ActivityInterface::EVENT_ACTIVITY_ACTIVATED, //It must trigger the start event of the second process EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); } /** * Tests DoNotTriggerStartEvents */ public function testSkipStartSignalEvent() { // Load the process from a BPMN file $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Signal_Start_Event.bpmn'); // Get the process by Id $process = $bpmnRepository->getProcess('ProcessId'); $this->engine->loadProcess($process); // Prepare a Signal Event to trigger $signalRef = 'signal1'; $eventDefinition = $this->repository->createSignalEventDefinition(); $signal = $this->repository->createSignal(); $signal->setId($signalRef); $eventDefinition->setPayload($signal); $eventDefinition->setProperty('signalRef', $signalRef); // Set Do not triggers signal start events with this signal $eventDefinition->setDoNotTriggerStartEvents(true); // Dispatch the signal to the engine $this->engine->getEventDefinitionBus()->dispatchEventDefinition( null, $eventDefinition, null ); $this->engine->runToNextState(); // Assertion: The start event was not triggered $this->assertCount(0, $process->getInstances()); // Set Do not triggers signal start events to FALSE to trigger the start event as usual $eventDefinition->setDoNotTriggerStartEvents(false); // Dispatch the signal to the engine $this->engine->getEventDefinitionBus()->dispatchEventDefinition( null, $eventDefinition, null ); $this->engine->runToNextState(); // Assertion: The start event was not triggered $this->assertCount(1, $process->getInstances()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/CallActivityTest.php
tests/Feature/Engine/CallActivityTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Test call activity element. */ class CallActivityTest extends EngineTestCase { /** * Test a call activity collaboration. */ public function testCallActivity() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/CallActivity_Process.bpmn'); //Load a process from a bpmn repository by Id $bpmnRepository->getCollaboration('collaboration'); $process = $bpmnRepository->getProcess('CallActivity_Process'); $calledProcess = $bpmnRepository->getProcess('CalledProcess'); $start = $bpmnRepository->getStartEvent('StartEvent_2'); $task = $bpmnRepository->getActivity('ScriptTask_4'); $subtask = $bpmnRepository->getScriptTask('ScriptTask_1'); $endTask = $bpmnRepository->getScriptTask('ScriptTask_5'); $callParticipant = $bpmnRepository->getParticipant('Participant_2'); $calledParticipant = $bpmnRepository->getParticipant('Participant_1'); //Assertion: Verify $callParticipant refers to $process $this->assertEquals($process, $callParticipant->getProcess()); $this->assertEquals($calledProcess, $calledParticipant->getProcess()); //Assertion: Verify default participant multiplicity ['maximum' => 1, 'minimum' => 0] $this->assertEquals(['maximum' => 1, 'minimum' => 0], $callParticipant->getParticipantMultiplicity()); $this->assertEquals(['maximum' => 1, 'minimum' => 0], $calledParticipant->getParticipantMultiplicity()); //Call a process $instance = $process->call(); $this->engine->runToNextState(); //Assertion: Expects that $process has one instance and $calledProcess does not have instances $this->assertEquals(1, $process->getInstances()->count()); $this->assertEquals(0, $calledProcess->getInstances()->count()); //Complete task $token = $task->getTokens($instance)->item(0); $task->complete($token); $this->engine->runToNextState(); //Assertion: Expects that $calledProcess has one instance $this->assertEquals(1, $calledProcess->getInstances()->count()); //Get instance of the process called by the CallActivity $subInstance = $calledProcess->getInstances()->item(0); //Assertion: Expects that $subtask owned by the $calledProcess has one token $this->assertEquals(1, $subtask->getTokens($subInstance)->count()); //Assertion: $process is started, first activity completed and starts the subtask. $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); //Complete the subtask $token = $subtask->getTokens($subInstance)->item(0); $subtask->complete($token); $this->engine->runToNextState(); //Assertion: Subtask is completed, $calledProcess is completed, and next task is activated. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); //Complete the last task $token = $endTask->getTokens($instance)->item(0); $endTask->complete($token); $this->engine->runToNextState(); //Assertion: End Task is completed and $process is completed. $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/ConditionalStartEventTest.php
tests/Feature/Engine/ConditionalStartEventTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; /** * Test a condition start event. */ class ConditionalStartEventTest extends EngineTestCase { /** * Test conditional start event */ public function testConditionalStartEvent() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Conditional_StartEvent.bpmn'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('Conditional_StartEvent'); // When the process is loaded into the engine, the conditional start event is evaluated $this->engine->loadProcess($process); $this->engine->runToNextState(); // Assertion: No process was started $this->assertEquals(0, $process->getInstances()->count()); // Add the environmental data required by the condition $this->engine->getDataStore()->putData('a', '1'); $this->engine->runToNextState(); // Assertion: One process was started $this->assertEquals(1, $process->getInstances()->count()); } /** * Test conditional start event should not trigger when empty condition */ public function testConditionalStartEventShouldNotTriggerWhenEmptyCondition() { // Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Conditional_StartEvent_Empty_Condition.bpmn'); // Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('Conditional_StartEvent'); // When the process is loaded into the engine, the conditional start event is evaluated $this->engine->loadProcess($process); $this->engine->runToNextState(); // Assertion: No process was started $this->assertEquals(0, $process->getInstances()->count()); // Add the environmental data required by the condition $this->engine->getDataStore()->putData('a', '1'); $this->engine->runToNextState(); // Assertion: One process was started $this->assertEquals(0, $process->getInstances()->count()); } public function testConditionalStartEventReturnSameId() { //Load a BpmnFile Repository (ONE) $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Conditional_StartEvent_NoID.bpmn'); // Load a process from a bpmn repository by Id $startEvent = $bpmnRepository->getStartEvent('StartEvent_1'); $conditionalEventDefId_One = $startEvent->getEventDefinitions()->item(0)->getId(); // Load a BpmnFile Repository (TWO) $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Conditional_StartEvent_NoID.bpmn'); // Load a process from a bpmn repository by Id $startEvent = $bpmnRepository->getStartEvent('StartEvent_1'); $conditionalEventDefId_Two = $startEvent->getEventDefinitions()->item(0)->getId(); $this->assertEquals($conditionalEventDefId_One, $conditionalEventDefId_Two); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/LanesTest.php
tests/Feature/Engine/LanesTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EndEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface; use ProcessMaker\Nayra\Contracts\Engine\ExecutionInstanceInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; use ProcessMaker\Repositories\BpmnFileRepository; /** * Test pools lane sets and lanes. */ class LanesTest extends EngineTestCase { /** * Test loading a collaboration with a single participant with two lanes * and a child lane set with two lanes. */ public function testLoadingLanes() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Lanes.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('PROCESS_1'); //Assertion: The process has a collection of LaneSets $this->assertNotEmpty($process->getLaneSets()); //Assertion: The loaded process has one LaneSet $this->assertEquals(1, $process->getLaneSets()->count()); //Assertion: The loaded LaneSet has three lanes $laneSet = $process->getLaneSets()->item(0); $this->assertEquals(3, $laneSet->getLanes()->count()); //Assertion: The first lane has 3 flow nodes $firstLane = $laneSet->getLanes()->item(0); $this->assertEquals(3, $firstLane->getFlowNodes()->count()); //Assertion: The second lane has 3 flow nodes $secondLane = $laneSet->getLanes()->item(1); $this->assertEquals(3, $secondLane->getFlowNodes()->count()); //Assertion: The third lane has one child lane with two lanes $thirdLane = $laneSet->getLanes()->item(2); $this->assertEquals(1, $thirdLane->getChildLaneSets()->count()); $childLaneSet = $thirdLane->getChildLaneSets()->item(0); $this->assertEquals(2, $childLaneSet->getLanes()->count()); //Assertion: Verify the name of the lane set. $this->assertEquals('Process Lane Set', $laneSet->getName()); //Assertion: Verify the name of the lanes. $this->assertEquals('Lane 1', $firstLane->getName()); $this->assertEquals('Lane 2', $secondLane->getName()); $this->assertEquals('Lane 3', $thirdLane->getName()); } /** * Lanes have no effect on the execution and should be ignored. */ public function testExecutionWithLanes() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Lanes.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('PROCESS_1'); //Execute the process $instance = $process->call(); $this->engine->runToNextState(); //Assertion: A process instance has started $this->assertEquals(1, $process->getInstances()->count()); //Complete the Task A $taksA = $bpmnRepository->getActivity('_7'); $this->completeTask($taksA, $instance); //Complete the Task B $taksB = $bpmnRepository->getActivity('_13'); $this->completeTask($taksB, $instance); //Complete the Task C $taksC = $bpmnRepository->getActivity('_15'); $this->completeTask($taksC, $instance); //Complete the Task D $taksD = $bpmnRepository->getActivity('_9'); $this->completeTask($taksD, $instance); //Assertion: All the process was executed $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, StartEventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, EndEventInterface::EVENT_THROW_TOKEN_ARRIVES, EndEventInterface::EVENT_THROW_TOKEN_CONSUMED, EndEventInterface::EVENT_EVENT_TRIGGERED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } /** * Helper to complete a task. * * @param ActivityInterface $task * @param ExecutionInstanceInterface $instance */ private function completeTask(ActivityInterface $task, ExecutionInstanceInterface $instance) { $token = $task->getTokens($instance)->item(0); $task->complete($token); $this->engine->runToNextState(); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/TerminateEventTest.php
tests/Feature/Engine/TerminateEventTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface; use ProcessMaker\Nayra\Contracts\Bpmn\TerminateEventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ThrowEventInterface; use ProcessMaker\Nayra\Storage\BpmnDocument; use ProcessMaker\Repositories\BpmnFileRepository; /** * Test a terminate event. */ class TerminateEventTest extends EngineTestCase { /** * Test terminate end event */ public function testTerminateEndEvent() { //Load a BpmnFile Repository $bpmnRepository = new BpmnDocument(); $bpmnRepository->setEngine($this->engine); $bpmnRepository->setFactory($this->repository); $bpmnRepository->load(__DIR__ . '/files/Terminate_Event.bpmn'); //Load a process from a bpmn repository by Id $process = $bpmnRepository->getProcess('Terminate_Event'); //Get 'start' activity of the process $activity = $bpmnRepository->getActivity('start'); //Get the terminate event $terminateEvent = $bpmnRepository->getEndEvent('EndEvent_1'); //Start the process $instance = $process->call(); $this->engine->runToNextState(); //Assertion: A process has started. $this->assertEquals(1, $process->getInstances()->count()); //Assertion: The process has started and the first activity was actived $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ]); //Complete the first activity. $token = $activity->getTokens($instance)->item(0); $activity->complete($token); $this->engine->runToNextState(); //Assertion: The activity was completed //Assertion: The gateway was activated //Assertion: The second activity was activated //Assertion: The terminate event was activated and the process was ended $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, GatewayInterface::EVENT_GATEWAY_TOKEN_ARRIVES, GatewayInterface::EVENT_GATEWAY_ACTIVATED, GatewayInterface::EVENT_GATEWAY_TOKEN_CONSUMED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, GatewayInterface::EVENT_GATEWAY_TOKEN_PASSED, ThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, TerminateEventDefinitionInterface::EVENT_THROW_EVENT_DEFINITION, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ScriptTaskInterface::EVENT_SCRIPT_TASK_ACTIVATED, ThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_CANCELLED, ProcessInterface::EVENT_PROCESS_INSTANCE_COMPLETED, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/Feature/Engine/MessageStartEventTest.php
tests/Feature/Engine/MessageStartEventTest.php
<?php namespace Tests\Feature\Engine; use ProcessMaker\Nayra\Bpmn\Models\Collaboration; use ProcessMaker\Nayra\Bpmn\Models\DataStoreCollection; use ProcessMaker\Nayra\Bpmn\Models\Participant; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\IntermediateThrowEventInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ItemDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; /** * Test the message start event */ class MessageStartEventTest extends EngineTestCase { /** * Returns an array of processes where the second process has a message start event * * @return array */ public function createMessageStartEventProcesses() { $item = $this->repository->createItemDefinition([ 'id' => 'item', 'isCollection' => true, 'itemKind' => ItemDefinitionInterface::ITEM_KIND_INFORMATION, 'structure' => 'String', ]); $message = $this->repository->createMessage(); $message->setId('MessageA'); $message->setItem($item); //Process A $processA = $this->repository->createProcess(); $processA->setEngine($this->engine); $processA->setRepository($this->repository); $startA = $this->repository->createStartEvent(); $activityA1 = $this->repository->createActivity(); $eventA = $this->repository->createIntermediateThrowEvent(); $messageEventDefA = $this->repository->createMessageEventDefinition(); $messageEventDefA->setId('MessageEvent1'); $messageEventDefA->setPayload($message); $eventA->getEventDefinitions()->push($messageEventDefA); $activityA2 = $this->repository->createActivity(); $endA = $this->repository->createEndEvent(); $startA->createFlowTo($activityA1, $this->repository); $activityA1->createFlowTo($eventA, $this->repository); $eventA->createFlowTo($activityA2, $this->repository); $activityA2->createFlowTo($endA, $this->repository); $processA->addActivity($activityA1) ->addActivity($activityA2) ->addEvent($startA) ->addEvent($eventA) ->addEvent($endA); //Process B $processB = $this->repository->createProcess(); $processB->setEngine($this->engine); $processB->setRepository($this->repository); $activityB1 = $this->repository->createActivity(); $messageEventDefB = $this->repository->createMessageEventDefinition(); $messageEventDefB->setPayload($message); $messageStartEventB = $this->repository->createStartEvent(); $messageStartEventB->getEventDefinitions()->push($messageEventDefB); $endB = $this->repository->createEndEvent(); $messageStartEventB->createFlowTo($activityB1, $this->repository); $activityB1->createFlowTo($endB, $this->repository); $processB->addActivity($activityB1) ->addEvent($messageStartEventB) ->addEvent($endB); return [$processA, $processB]; } /** * Tests the start of a process when it receives a message */ public function testMessageStartEvent() { //Create two processes list($processA, $processB) = $this->createMessageStartEventProcesses(); //Create a collaboration $collaboration = new Collaboration; //Add process A as participant of the collaboration $participant = new Participant(); $participant->setProcess($processA); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); //Add process B as participant of the collaboration $participant = new Participant(); $participant->setProcess($processB); $participant->setParticipantMultiplicity(['maximum' => 1, 'minimum' => 0]); $collaboration->getParticipants()->push($participant); //Create message flow from intermediate events A to B $eventA = $processA->getEvents()->item(1); $messageStartEventB = $processB->getEvents()->item(0); $messageFlow = $this->repository->createMessageFlow(); $messageFlow->setCollaboration($collaboration); $messageFlow->setSource($eventA); $messageFlow->setTarget($messageStartEventB); $collaboration->addMessageFlow($messageFlow); $eventA = $processA->getEvents()->item(1); $eventB = $processB->getEvents()->item(1); $eventA->collaboration = $collaboration; $eventB->collaboration = $collaboration; $dataStoreA = $this->repository->createDataStore(); $dataStoreA->putData('A', '1'); $dataStoreB = $this->repository->createDataStore(); $dataStoreB->putData('B', '1'); $dataStoreCollectionA = new DataStoreCollection(); $dataStoreCollectionA->add($dataStoreA); $dataStoreCollectionB = new DataStoreCollection(); $dataStoreCollectionB->add($dataStoreB); $processA->setDataStores($dataStoreCollectionA); $processB->setDataStores($dataStoreCollectionB); $this->engine->loadCollaboration($collaboration); $this->engine->loadProcess($processB); $instanceA = $this->engine->createExecutionInstance($processA, $dataStoreA); // we start the process A $startA = $processA->getEvents()->item(0); $activityA1 = $processA->getActivities()->item(0); $startA->start($instanceA); $this->engine->runToNextState(); //Assertion: messageFlow resources set and get should be equal $this->assertEquals($messageFlow->getSource(), $eventA); //Assertion: The activity must be activated $this->assertEvents([ ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); // we finish the first activity so that a new event should be created in the second process $tokenA = $activityA1->getTokens($instanceA)->item(0); $activityA1->complete($tokenA); $this->engine->runToNextState(); //Assertion: The process1 activity should be finished and a new instance of the second process must be created $this->assertEvents([ ActivityInterface::EVENT_ACTIVITY_COMPLETED, ActivityInterface::EVENT_ACTIVITY_CLOSED, ProcessInterface::EVENT_PROCESS_INSTANCE_CREATED, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_ARRIVES, //events triggered when the catching event runs IntermediateThrowEventInterface::EVENT_THROW_TOKEN_CONSUMED, IntermediateThrowEventInterface::EVENT_THROW_TOKEN_PASSED, //Actibity activated in the first process ActivityInterface::EVENT_ACTIVITY_ACTIVATED, //It must be triggered the start event of the second process EventInterface::EVENT_EVENT_TRIGGERED, ActivityInterface::EVENT_ACTIVITY_ACTIVATED, ]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/RepositoryTest.php
tests/unit/ProcessMaker/Nayra/RepositoryTest.php
<?php namespace ProcessMaker\Nayra; use InvalidArgumentException; use PHPUnit\Framework\TestCase; use ProcessMaker\Test\Contracts\TestOneInterface; use ProcessMaker\Test\Contracts\TestTwoInterface; use ProcessMaker\Test\Models\Repository; use ProcessMaker\Test\Models\TestOneClassWithEmptyConstructor; use ProcessMaker\Test\Models\TestTwoClassWithArgumentsConstructor; /** * Test Repository implementation */ class RepositoryTest extends TestCase { /** * Tests that the repository creates classes whose constructors have and don't have arguments */ public function testInstantiation() { $factory = new Repository(); //instantiate an object that implementes a TestOneInterface $object1 = $factory->create(TestOneInterface::class); //Assertion: The instantiated object is not null $this->assertNotNull($object1); //Assertion: The instantiated object implementes the TestOneInterface $this->assertInstanceOf(TestOneInterface::class, $object1); //instantiate an object that implementes a TestTwoInterface $object2 = $factory->create(TestTwoInterface::class, 'passedField1Value', 'passedField2Value'); //Assertion: The instantiated object has uses its constructor $this->assertEquals($object2->aField, 'passedField1Value'); //Assertion: The instantiated object implements the TestTwoInterface $this->assertInstanceOf(TestTwoInterface::class, $object2); $this->expectException(InvalidArgumentException::class); //Assertion: when trying to instantiate an interface that is not mapped an argument exception should be thrown $object3 = $factory->create('NonExistentInterface'); } /** * Creates factory mappings for the test * * @return array */ private function createMappingConfiguration() { return [ TestOneInterface::class => TestOneClassWithEmptyConstructor::class, TestTwoInterface::class => TestTwoClassWithArgumentsConstructor::class, ]; } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/ArtifactCollectionTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/ArtifactCollectionTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Artifact; use ProcessMaker\Nayra\Bpmn\Models\ArtifactCollection; /** * Tests for the artifact collection */ class ArtifactCollectionTest extends TestCase { /** * Test the adding of items to the collection */ public function testAdd() { // create and element $element = new Artifact(); $collection = new ArtifactCollection(); // add the element to the collection $collection->add($element); //Assertion: the first element of the collection should be the added element $this->assertEquals($element, $collection->item(0)); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/CollectionTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/CollectionTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; class CollectionTest extends TestCase { /** * @var Collection */ private $object; public function setUp(): void { parent::setUp(); $this->object = new Collection([1, 2, 3]); } /** * Test count. */ public function testCount() { $this->assertEquals(3, $this->object->count()); } /** * Find elements of the collection that match the $condition. */ public function testFind() { $this->assertEquals(1, $this->object->find(function ($item) { return $item === 2; })->count()); $this->assertEquals(2, $this->object->find(function ($item) { return $item % 2; })->count()); } /** * Test push item. */ public function testPush() { $this->object->push(4); $this->assertEquals(4, $this->object->count()); } /** * Test pop item. */ public function testPop() { $this->assertEquals(3, $this->object->pop()); $this->assertEquals(2, $this->object->count()); } /** * Test unshift. */ public function testUnshift() { $this->object->unshift(0); $this->assertEquals(0, $this->object->item(0)); $this->assertEquals(4, $this->object->count()); } /** * Test indexOf. */ public function testIndexOf() { $this->assertEquals(1, $this->object->indexOf(2)); } /** * Sum the $callback result for each element. */ public function testSum() { $this->assertEquals(6, $this->object->sum(function ($item) { return $item; })); } /** * Test get item. */ public function testItem() { $this->assertEquals(2, $this->object->item(1)); } /** * Test splice. */ public function testSplice() { $this->object->splice(1, 1, [20]); $this->assertEquals(20, $this->object->item(1)); $this->object->splice(1, 1, [20]); $this->assertEquals(20, $this->object->item(1)); $this->object->splice(1, 1, [20, 21]); $this->assertEquals(20, $this->object->item(1)); $this->assertEquals(21, $this->object->item(2)); $this->assertEquals(3, $this->object->item(3)); } /** * Test current */ public function testCurrent() { foreach ($this->object as $item) { $this->assertEquals($item, $this->object->current()); } } /** * Test next */ public function testNext() { $this->assertEquals(1, $this->object->current()); $this->object->next(); $this->assertEquals(2, $this->object->current()); } /** * Test get key. */ public function testKey() { $this->assertEquals(0, $this->object->key()); $this->object->next(); $this->assertEquals(1, $this->object->key()); $this->assertEquals(2, $this->object->current()); } /** * Test valid. */ public function testValid() { $this->assertTrue($this->object->valid()); $this->object->next(); $this->object->next(); $this->object->next(); $this->assertFalse($this->object->valid()); } /** * Test rewind */ public function testRewind() { $this->object->next(); $this->object->next(); $this->object->rewind(); $this->assertEquals(0, $this->object->key()); } /** * Test seek */ public function testSeek() { $this->object->seek(1); $this->assertEquals(1, $this->object->key()); $this->assertEquals(2, $this->object->current()); } /** * Find first element of the collection that match the $condition. */ public function testFindFirst() { $this->assertEquals(2, $this->object->findFirst(function ($item) { return $item === 2; })); $this->assertEquals(1, $this->object->findFirst(function ($item) { return $item % 2; })); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/ErrorTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/ErrorTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Error; use ProcessMaker\Nayra\Bpmn\Models\MessageFlow; use ProcessMaker\Nayra\Contracts\Bpmn\ErrorInterface; /** * Tests for the Error class */ class ErrorTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testSettersAndGetters() { // Create the objects that will be set in the data store $error = new Error(); $message = new MessageFlow(); $testString = 'oneString'; //set process and state object to the data store $error->setProperty(ErrorInterface::BPMN_PROPERTY_NAME, $testString); $error->setProperty(ErrorInterface::BPMN_PROPERTY_ERROR_CODE, $testString); //Assertion: The get name must be equal to the set one $this->assertEquals($testString, $error->getName()); //Assertion: The get error code must be equal to the set one $this->assertEquals($testString, $error->getErrorCode()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/InputOutputSpecificationTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/InputOutputSpecificationTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\InputOutputSpecification; use ProcessMaker\Nayra\Bpmn\Models\InputSet; use ProcessMaker\Nayra\Bpmn\Models\OutputSet; /** * Tests InputOutputSpecification class implementation */ class InputOutputSpecificationTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testSettersAndGetters() { // Create the objects that will be set in the data store $ioSpecification = new InputOutputSpecification(); $dataOutput = new Collection(); $ioSpecification->setDataOutput($dataOutput); $this->assertEquals($dataOutput, $ioSpecification->getDataOutput()); $dataInput = new Collection(); $ioSpecification->setDataInput($dataInput); $this->assertEquals($dataInput, $ioSpecification->getDataInput()); $outputSet = new OutputSet(); $ioSpecification->setOutputSet($outputSet); $this->assertEquals($outputSet, $ioSpecification->getOutputSet()); $inputSet = new InputSet(); $ioSpecification->setInputSet($inputSet); $this->assertEquals($inputSet, $ioSpecification->getInputSet()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/ProcessTraitTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/ProcessTraitTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Process; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityCollectionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ArtifactCollectionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DataStoreCollectionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\EventCollectionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\FlowCollectionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\GatewayCollectionInterface; /** * Test the process base behavior. */ class ProcessTraitTest extends TestCase { /** * @var ProcessTrait */ private $object; /** * Initialize process object * * @return void */ public function setUp(): void { parent::setUp(); $this->object = new Process(); } /** * Test get process collection of elements by type */ public function testCollections() { $this->assertInstanceOf(ActivityCollectionInterface::class, $this->object->getActivities()); $this->assertInstanceOf(FlowCollectionInterface::class, $this->object->getFlows()); $this->assertInstanceOf(GatewayCollectionInterface::class, $this->object->getGateways()); $this->assertInstanceOf(EventCollectionInterface::class, $this->object->getEvents()); $this->assertInstanceOf(ArtifactCollectionInterface::class, $this->object->getArtifacts()); $this->assertInstanceOf(DataStoreCollectionInterface::class, $this->object->getDataStores()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/PathTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/PathTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Path; class PathTest extends TestCase { /** * Tests that a path stores and returns correctly its elements */ public function testGetElement() { //Create a new empty path $path = new Path([]); //Assertion: as the path is empty, the number of elements should be 0 $this->assertCount(0, $path->getElements()); //Create a new path with one element $path = new Path([1]); //Assertion: the created path should have one element $this->assertCount(1, $path->getElements()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/ScriptTaskTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/ScriptTaskTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\ScriptTask; /** * Tests for the Operation class */ class ScriptTaskTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testSettersAndGetters() { // Create the objects that will be set in the script task $script = new ScriptTask(); //set properties of the script task $testFormat = 'testFormat'; $script->setScriptFormat($testFormat); //Assertion: the get format must be equal to the set one $this->assertEquals($testFormat, $script->getScriptFormat()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/DatePeriodTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/DatePeriodTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use DateInterval; use DatePeriod as GlobalDatePeriod; use DateTime; use DateTimeZone; use Exception; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\DatePeriod; /** * Tests for the DatePeriod class */ class DatePeriodTest extends TestCase { public function assertArraySubset2($subset, $array) { foreach ($subset as $key => $value) { $this->assertArrayHasKey($key, $array); $this->assertEquals($value, $array[$key]); } } /** * Tests DatePeriod with different time zones */ public function testPeriodsWithDifferentTimeZones() { $cycle = new DatePeriod('R/2018-10-02T08:00:00Z/P1D/2018-10-07T08:00:00-04:00'); $this->assertEquals('2018-10-02 08:00:00', $cycle->start->format('Y-m-d H:i:s')); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals('2018-10-07 12:00:00', $cycle->end->setTimeZone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s')); $this->assertEquals(DatePeriod::INF_RECURRENCES, $cycle->recurrences); $cycle = new DatePeriod($cycle->start, $cycle->interval, $cycle->end); $this->assertEquals('2018-10-02 08:00:00', $cycle->start->format('Y-m-d H:i:s')); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals('2018-10-07 12:00:00', $cycle->end->setTimeZone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s')); $this->assertEquals(DatePeriod::INF_RECURRENCES, $cycle->recurrences); } /** * Tests DatePeriod of type R[n]/start/interval/end */ public function testPeriodsCompleteIso8601String() { $cycle = new DatePeriod('R3/2018-10-02T08:00:00Z/P1D/2018-10-07T08:00:00-04:00'); $this->assertEquals('2018-10-02 08:00:00', $cycle->start->format('Y-m-d H:i:s')); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals('2018-10-07 12:00:00', $cycle->end->setTimeZone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s')); $this->assertEquals(4, $cycle->recurrences); $cycle = new DatePeriod($cycle->start, $cycle->interval, [$cycle->end, $cycle->recurrences - 1]); $this->assertEquals('2018-10-02 08:00:00', $cycle->start->format('Y-m-d H:i:s')); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals('2018-10-07 12:00:00', $cycle->end->setTimeZone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s')); $this->assertEquals(4, $cycle->recurrences); } /** * Tests DatePeriod without end */ public function testPeriodsWithoutEnd() { $cycle = new DatePeriod('R/2018-10-02T08:00:00Z/P1D'); $this->assertEquals('2018-10-02 08:00:00', $cycle->start->format('Y-m-d H:i:s')); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals(null, $cycle->end); $this->assertEquals(DatePeriod::INF_RECURRENCES, $cycle->recurrences); $cycle = new DatePeriod($cycle->start, $cycle->interval); $this->assertEquals('2018-10-02 08:00:00', $cycle->start->format('Y-m-d H:i:s')); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals(null, $cycle->end); $this->assertEquals(DatePeriod::INF_RECURRENCES, $cycle->recurrences); } /** * Tests DatePeriod without start */ public function testPeriodsWithoutStart() { $cycle = new DatePeriod('R/P1D/2018-10-02T08:00:00Z'); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals('2018-10-02 08:00:00', $cycle->end->format('Y-m-d H:i:s')); $this->assertEquals(DatePeriod::INF_RECURRENCES, $cycle->recurrences); $cycle = new DatePeriod($cycle->start, $cycle->interval, $cycle->end); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals('2018-10-02 08:00:00', $cycle->end->format('Y-m-d H:i:s')); $this->assertEquals(DatePeriod::INF_RECURRENCES, $cycle->recurrences); } /** * Tests DatePeriod without start nor end */ public function testPeriodsWithoutStartNorEnd() { $cycle = new DatePeriod('R/P1D'); $this->assertEquals(null, $cycle->start); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals(null, $cycle->end); $this->assertEquals(DatePeriod::INF_RECURRENCES, $cycle->recurrences); $cycle = new DatePeriod($cycle->start, $cycle->interval, $cycle->end); $this->assertEquals(null, $cycle->start); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals(null, $cycle->end); $this->assertEquals(DatePeriod::INF_RECURRENCES, $cycle->recurrences); } /** * Tests DatePeriod with different time zones, and with repeating number */ public function testPeriodsWithRepeatingNumber() { $cycle = new DatePeriod('R3/2018-10-02T08:00:00Z/P1D'); $this->assertEquals('2018-10-02 08:00:00', $cycle->start->format('Y-m-d H:i:s')); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals(null, $cycle->end); // Assertion: Recurrences = Repetitions -1 $this->assertEquals(4, $cycle->recurrences); $cycle = new DatePeriod($cycle->start, $cycle->interval, $cycle->recurrences - 1); $this->assertEquals('2018-10-02 08:00:00', $cycle->start->format('Y-m-d H:i:s')); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals(null, $cycle->end); $this->assertEquals(4, $cycle->recurrences); } /** * Tests DatePeriod without end, but with repeating number */ public function testPeriodsWithoutEndWithRepeatingNumber() { $cycle = new DatePeriod('R3/2018-10-02T08:00:00Z/P1D'); $this->assertEquals('2018-10-02 08:00:00', $cycle->start->format('Y-m-d H:i:s')); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals(null, $cycle->end); $this->assertEquals(4, $cycle->recurrences); $cycle = new DatePeriod($cycle->start, $cycle->interval, $cycle->recurrences - 1); $this->assertEquals('2018-10-02 08:00:00', $cycle->start->format('Y-m-d H:i:s')); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals(null, $cycle->end); $this->assertEquals(4, $cycle->recurrences); } /** * Tests DatePeriod without start, but with repeating number */ public function testPeriodsWithoutStartWithRepeatingNumber() { $cycle = new DatePeriod('R3/P1D/2018-10-02T08:00:00Z'); $this->assertEquals(null, $cycle->start); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals('2018-10-02 08:00:00', $cycle->end->format('Y-m-d H:i:s')); $this->assertEquals(4, $cycle->recurrences); $cycle = new DatePeriod($cycle->start, $cycle->interval, [$cycle->end, $cycle->recurrences - 1]); $this->assertEquals(null, $cycle->start); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals('2018-10-02 08:00:00', $cycle->end->format('Y-m-d H:i:s')); $this->assertEquals(4, $cycle->recurrences); } /** * Tests DatePeriod without start nor end, but with repeating number */ public function testPeriodsWithoutStartNorEndWithRepeatingNumber() { $cycle = new DatePeriod('R3/P1D'); $this->assertEquals(null, $cycle->start); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals(null, $cycle->end); $this->assertEquals(4, $cycle->recurrences); $cycle = new DatePeriod($cycle->start, $cycle->interval, $cycle->recurrences - 1); $this->assertEquals(null, $cycle->start); $this->assertArraySubset2(['y' => 0, 'm' => 0, 'd' => 1, 'h' => 0, 'i' => 0, 's' => 0], (array) $cycle->interval); $this->assertEquals(null, $cycle->end); $this->assertEquals(4, $cycle->recurrences); } /** * Compare DatePeriod with GlobalDatePeriod */ public function testStandardDatePeriod() { // Compare standar initialization $cycle0 = new GlobalDatePeriod('R3/2018-10-02T08:00:00Z/P1D'); $cycle = new DatePeriod('R3/2018-10-02T08:00:00Z/P1D'); //new DateTime('2018-10-02 08:00:00Z'), new DateInterval('P1D'), 2); $this->assertEquals($cycle0->start, $cycle->start); $this->assertEquals($cycle0->interval, $cycle->interval); $this->assertEquals($cycle0->end, $cycle->end); $this->assertEquals($cycle0->recurrences, $cycle->recurrences); // Compare parameter initialization $cycle0 = new GlobalDatePeriod(new DateTime('2018-10-02 08:00:00Z'), new DateInterval('P1D'), 2); $cycle = new DatePeriod(new DateTime('2018-10-02 08:00:00Z'), new DateInterval('P1D'), 2); $this->assertEquals($cycle0->start, $cycle->start); $this->assertEquals($cycle0->interval, $cycle->interval); $this->assertEquals($cycle0->end, $cycle->end); $this->assertEquals($cycle0->recurrences, $cycle->recurrences); // Compare json_encode $this->assertEquals(json_encode($cycle), json_encode($cycle0)); } /** * Invalid DatePeriod initialization. Only start */ public function testInvalidInitializationStart() { $this->expectException(Exception::class); new DatePeriod(new DateTime('2018-10-02 08:00:00Z')); } /** * Invalid DatePeriod initialization. Only interval */ public function testInvalidInitializationInterval() { $this->expectException(Exception::class); new DatePeriod(null, new DateInterval('2018-10-02 08:00:00Z')); } /** * Invalid DatePeriod initialization. Invalid start */ public function testInvalidInitializationInvalidStart() { $this->expectException(Exception::class); new DatePeriod('', new DateInterval('P1D'), [new DateTime('2018-10-02 08:00:00Z'), 0]); } /** * Invalid DatePeriod initialization. Invalid interval */ public function testInvalidInitializationInvalidInterval() { $this->expectException(Exception::class); new DatePeriod(new DateTime('2018-10-02 08:00:00Z'), '', [new DateTime('2018-10-02 08:00:00Z'), 0]); } /** * Invalid DatePeriod initialization. Invalid end */ public function testInvalidInitializationInvalidEnd() { $this->expectException(Exception::class); new DatePeriod(new DateTime('2018-10-02 08:00:00Z'), new DateInterval('P1D'), ['', 0]); } /** * Invalid DatePeriod initialization. Invalid recurrence */ public function testInvalidInitializationInvalidRecurrence() { $this->expectException(Exception::class); new DatePeriod(new DateTime('2018-10-02 08:00:00Z'), new DateInterval('P1D'), [new DateTime('2018-10-02 08:00:00Z'), -2]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/EventCollectionTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/EventCollectionTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\EventCollection; use ProcessMaker\Nayra\Bpmn\Models\StartEvent; /** * Tests for the event collection */ class EventCollectionTest extends TestCase { /** * Test the adding of items to the collection */ public function testAdd() { // create and element $element = new StartEvent(); $collection = new EventCollection(); // add the element to the collection $collection->add($element); //Assertion: the first element of the collection should be the added element $this->assertEquals($element, $collection->item(0)); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/IntermediateThrowEventTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/IntermediateThrowEventTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\IntermediateThrowEvent; /** * Tests for the IntermediateThrowEvent class */ class IntermediateThrowEventTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testSettersAndGetters() { // Create the objects that will be set in the data store $event = new IntermediateThrowEvent(); //Assertion: The collections getters must be not null $this->assertEquals(0, $event->getDataInputAssociations()->count()); $this->assertEquals(0, $event->getDataInputs()->count()); //Assertion: input set was not initialized so it must be null $this->assertNull($event->getInputSet()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/ObservableTraitTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/ObservableTraitTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\InclusiveGateway; use ProcessMaker\Nayra\Contracts\Bpmn\TransitionInterface; /** * Test attach/detach observers. */ class ObservableTraitTest extends TestCase { /** * Dummy function to test if a callback function is attached/detached */ public function dummyFunction() { return 'dummy'; } /** * Tests that a callback function used to observe an entity is attached/detached correctly */ public function testAttachDetach() { $dummyGateway = new InclusiveGateway(); //The activity transition will be the object to observe $transition = new ActivityCompletedTransition($dummyGateway); //Assertion: once attached to an event the observer count should be incremented by one $transition->attachEvent(TransitionInterface::EVENT_AFTER_CONSUME, [$this, 'dummyFunction']); $this->assertCount(1, $transition->getObservers()[TransitionInterface::EVENT_AFTER_CONSUME]); //Assertion: once attached to an event the observer count should be reduced by one $transition->detachEvent(TransitionInterface::EVENT_AFTER_CONSUME, [$this, 'dummyFunction']); $this->assertCount(0, $transition->getObservers()[TransitionInterface::EVENT_AFTER_CONSUME]); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/CollaborationTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/CollaborationTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Collaboration; use ProcessMaker\Nayra\Bpmn\Models\StartEvent; /** * Tests for the Collaboration class */ class CollaborationTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testSettersAndGetters() { // Create the objects that will be set $testMessageId = 'testMessageId'; $collaboration = new Collaboration(); $messageCollection = new Collection(); $listener = new StartEvent(); // Use the setters of the collaboration $collaboration->setClosed(false); $collaboration->setMessageFlows($messageCollection); //Assertion: The properties must be accessible with the getters $this->assertEquals(0, $collaboration->getCorrelationKeys()->count()); $this->assertEquals(0, $collaboration->getMessageFlows()->count()); $this->assertFalse($collaboration->isClosed()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/BoundaryEventTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/BoundaryEventTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\BoundaryEvent; /** * Unit tests for the BoundaryEvent class */ class BoundaryEventTest extends TestCase { /** * Tests that the input place of a boundary event must be null */ public function testGetInputPlaceOfNewElement() { $boundaryEvent = new BoundaryEvent(); //the input place should be null in a start event $this->assertNull($boundaryEvent->getInputPlace()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/MessageEventDefinitionTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/MessageEventDefinitionTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\MessageEventDefinition; use ProcessMaker\Nayra\Bpmn\Models\Message; use ProcessMaker\Nayra\Bpmn\Collection; use ProcessMaker\Nayra\Contracts\Bpmn\EventDefinitionInterface; use ProcessMaker\Nayra\Contracts\Bpmn\FlowNodeInterface; use ProcessMaker\Nayra\Contracts\Engine\ExecutionInstanceInterface; /** * Tests for the MessageEventDefinition class */ class MessageEventDefinitionTest extends TestCase { /** * Test that execute method handles null token gracefully * * This test ensures that when execute is called with a null token * (which can happen in message start events), the method doesn't * throw an error and returns successfully. */ public function testExecuteWithNullToken() { $messageEventDef = new MessageEventDefinition(); $message = new Message(); $messageEventDef->setPayload($message); // Create a mock event definition $event = $this->createMock(EventDefinitionInterface::class); // Create a mock target (catch event) $target = $this->createMock(FlowNodeInterface::class); // Create a mock instance $instance = $this->createMock(ExecutionInstanceInterface::class); // Execute with null token - should not throw an error $result = $messageEventDef->execute($event, $target, $instance, null); // Assert that the method returns the instance $this->assertSame($messageEventDef, $result); } /** * Test that execute method works correctly with a valid token */ public function testExecuteWithValidToken() { $messageEventDef = new MessageEventDefinition(); $message = new Message(); $messageEventDef->setPayload($message); // Create a mock event definition $event = $this->createMock(EventDefinitionInterface::class); // Create a mock instance $instance = $this->createMock(ExecutionInstanceInterface::class); // Create a mock token $token = $this->createMock(\ProcessMaker\Nayra\Contracts\Bpmn\TokenInterface::class); // Mock getOwnerElement to return a throw event $throwEvent = $this->createMock(\ProcessMaker\Nayra\Contracts\Bpmn\ThrowEventInterface::class); $token->expects($this->once()) ->method('getOwnerElement') ->willReturn($throwEvent); // Mock getInstance to return an instance $tokenInstance = $this->createMock(ExecutionInstanceInterface::class); $token->expects($this->any()) ->method('getInstance') ->willReturn($tokenInstance); // Mock throw event methods $throwEvent->expects($this->once()) ->method('getDataInputAssociations') ->willReturn(new Collection()); // Mock target as catch event $catchEvent = $this->createMock(\ProcessMaker\Nayra\Contracts\Bpmn\CatchEventInterface::class); $catchEvent->expects($this->once()) ->method('getDataOutputAssociations') ->willReturn(new Collection()); // Mock instance data store $dataStore = $this->createMock(\ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface::class); $dataStore->expects($this->any()) ->method('getData') ->willReturn([]); $instance->expects($this->any()) ->method('getDataStore') ->willReturn($dataStore); // Mock token instance data store $tokenDataStore = $this->createMock(\ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface::class); $tokenDataStore->expects($this->any()) ->method('getData') ->willReturn([]); $tokenInstance->expects($this->any()) ->method('getDataStore') ->willReturn($tokenDataStore); // Execute with valid token $result = $messageEventDef->execute($event, $catchEvent, $instance, $token); // Assert that the method returns the instance $this->assertSame($messageEventDef, $result); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/MessageFlowTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/MessageFlowTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Collaboration; use ProcessMaker\Nayra\Bpmn\Models\EndEvent; use ProcessMaker\Nayra\Bpmn\Models\IntermediateCatchEvent; use ProcessMaker\Nayra\Bpmn\Models\Message; use ProcessMaker\Nayra\Bpmn\Models\MessageEventDefinition; use ProcessMaker\Nayra\Bpmn\Models\MessageFlow; /** * Tests for the MessageFlow class */ class MessageFlowTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testSettersAndGetters() { // Create the objects that will be set in the data store $msgFlow = new MessageFlow(); $collaboration = new Collaboration(); $target = new IntermediateCatchEvent(); $source = new EndEvent(); $message = new Message(); $messageEventDef = new MessageEventDefinition(); $messageEventDef->setPayload($message); $source->getEventDefinitions()->push($messageEventDef); // Use the setters $msgFlow->setCollaboration($collaboration); $msgFlow->setSource($source); $msgFlow->setTarget($target); $msgFlow->setMessage($message); //Assertion: The get message must be equal to the set one $this->assertEquals($message, $msgFlow->getMessage()); //Assertion: The get target must be equal to the set one $this->assertEquals($target, $msgFlow->getTarget()); //Assertion: The get collaboration must be equal to the set one $this->assertEquals($collaboration, $msgFlow->getCollaboration()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/SignalTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/SignalTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Signal; /** * Tests for the Signal class */ class SignalTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testSettersAndGetters() { // Create the objects that will be set in the data store $signal = new Signal(); $testString = 'testString'; // Use setters $signal->setId($testString); $signal->setName($testString); //Assertion: The getters should return the set objects $this->assertEquals($testString, $signal->getId()); $this->assertEquals($testString, $signal->getName()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/GatewayCollectionTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/GatewayCollectionTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\GatewayCollection; use ProcessMaker\Nayra\Bpmn\Models\InclusiveGateway; /** * Tests for the gateway collection */ class GatewayCollectionTest extends TestCase { /** * Test the adding of items to the collection */ public function testAdd() { // create and element $element = new InclusiveGateway(); $collection = new GatewayCollection(); // add the element to the collection $collection->add($element); //Assertion: the first element of the collection should be the added element $this->assertEquals($element, $collection->item(0)); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/MessageTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/MessageTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Message; /** * Tests for the Message class */ class MessageTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testSettersAndGetters() { // Create the objects that will be set in the data store $message = new Message(); $testString = 'testString'; //set process and state object to the data store $message->setId($testString); //Assertion: The get id must be equal to the set one $this->assertEquals($testString, $message->getId()); //Assertion: The name was not set so it must be null $this->assertNull($message->getName()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/MultiInstanceLoopCharacteristicsTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/MultiInstanceLoopCharacteristicsTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\DataInput; use ProcessMaker\Nayra\Bpmn\Models\DataOutput; use ProcessMaker\Nayra\Bpmn\Models\MultiInstanceLoopCharacteristics; use ProcessMaker\Nayra\Contracts\Bpmn\ComplexBehaviorDefinitionInterface; use ProcessMaker\Test\Models\FormalExpression; /** * Tests MultiInstanceLoopCharacteristics class getter/setters */ class MultiInstanceLoopCharacteristicsTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testSettersAndGetters() { // Create the objects that will be set in the data store $object = new MultiInstanceLoopCharacteristics(); $isSequential = true; $object->setIsSequential($isSequential); $this->assertEquals($isSequential, $object->getIsSequential()); $behavior = 'All'; $object->setBehavior($behavior); $this->assertEquals($behavior, $object->getBehavior()); $oneBehaviorEventRef = 'event_1'; $object->setOneBehaviorEventRef($oneBehaviorEventRef); $this->assertEquals($oneBehaviorEventRef, $object->getOneBehaviorEventRef()); $noneBehaviorEventRef = 'event_2'; $object->setNoneBehaviorEventRef($noneBehaviorEventRef); $this->assertEquals($noneBehaviorEventRef, $object->getNoneBehaviorEventRef()); $loopCardinality = new FormalExpression('3'); $object->setLoopCardinality($loopCardinality); $this->assertEquals($loopCardinality, $object->getLoopCardinality()); $loopDataInputRef = 'data_input_1'; $object->setLoopDataInputRef($loopDataInputRef); $this->assertEquals($loopDataInputRef, $object->getLoopDataInputRef()); $loopDataInput = new DataInput(); $object->setLoopDataInput($loopDataInput); $this->assertEquals($loopDataInput, $object->getLoopDataInput()); $loopDataOutputRef = 'data_output_1'; $object->setLoopDataOutputRef($loopDataOutputRef); $this->assertEquals($loopDataOutputRef, $object->getLoopDataOutputRef()); $loopDataOutput = new DataOutput(); $object->setLoopDataOutput($loopDataOutput); $this->assertEquals($loopDataOutput, $object->getLoopDataOutput()); $inputDataItem = new DataInput(); $object->setInputDataItem($inputDataItem); $this->assertEquals($inputDataItem, $object->getInputDataItem()); $outputDataItem = new DataOutput(); $object->setOutputDataItem($outputDataItem); $this->assertEquals($outputDataItem, $object->getOutputDataItem()); $complexBehaviorDefinition = $this->createMock(ComplexBehaviorDefinitionInterface::class); $object->setComplexBehaviorDefinition($complexBehaviorDefinition); $this->assertEquals($complexBehaviorDefinition, $object->getComplexBehaviorDefinition()); $completionCondition = new FormalExpression('true'); $object->setCompletionCondition($completionCondition); $this->assertEquals($completionCondition, $object->getCompletionCondition()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/ConditionedTransitionTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/ConditionedTransitionTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\DataStore; use ProcessMaker\Nayra\Bpmn\Models\ExclusiveGateway; use ProcessMaker\Nayra\Bpmn\Models\Process; use ProcessMaker\Nayra\Contracts\Engine\EngineInterface; /** * Tests for the ConditionedTransition class */ class ConditionedTransitionTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testAssertCondition() { $gateway = new ExclusiveGateway(); $conditionedTransition = new ConditionedTransition($gateway); $conditionedTransition->setCondition(function ($data) { return $data['foo']; }); // Mock a engine data store $process = new Process(); $engine = $this->getMockBuilder(EngineInterface::class)->getMock(); $dataStore = new DataStore(); $dataStore->setData(['foo' => 'bar']); $engine->method('getDataStore')->willReturn($dataStore); $process->setEngine($engine); $conditionedTransition->setOwnerProcess($process); // Assertion: The condition should return 'bar' $this->assertEquals('bar', $conditionedTransition->assertCondition()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/FlowCollectionTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/FlowCollectionTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Flow; use ProcessMaker\Nayra\Bpmn\Models\FlowCollection; /** * Tests for the flow collection */ class FlowCollectionTest extends TestCase { /** * Test the adding of items to the collection */ public function testAdd() { // create and element $element = new Flow(); $collection = new FlowCollection(); // add the element to the collection $collection->add($element); //Assertion: the first element of the collection should be the added element $this->assertEquals($element, $collection->item(0)); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/StartEventTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/StartEventTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\StartEvent; /** * StartEvent unit test. */ class StartEventTest extends TestCase { /** * Tests that the input place of a start event must be null */ public function testGetInputPlaceOfNewElement() { $start = new StartEvent(); // Assertion: the input place should be null in a start event $this->assertNull($start->getInputPlace()); // Assertion: the active state is null $this->assertNull($start->getActiveState()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/ActivityCollectionTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/ActivityCollectionTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Activity; use ProcessMaker\Nayra\Bpmn\Models\ActivityCollection; /** * Tests the activity collection */ class ActivityCollectionTest extends TestCase { /** * Test the adding of items to the collection */ public function testAdd() { // create and element $element = new Activity(); $collection = new ActivityCollection(); // add the element to the collection $collection->add($element); //Assertion: the first element of the collection should be the added element $this->assertEquals($element, $collection->item(0)); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/DataStoreTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/DataStoreTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface; use ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\Bpmn\StateInterface; use Tests\Feature\Engine\EngineTestCase; /** * Tests for the DataStore class */ class DataStoreTest extends EngineTestCase { /** * Tests that setters and getters are working properly */ public function testDataStoreSettersAndGetters() { // Create the objects that will be set in the data store $dataStore = $this->repository->createDataStore(); $process = $this->repository->createProcess(); $process->setRepository($this->repository); $dummyActivity = $this->repository->createActivity(); $dummyActivity->setRepository($this->repository); $state = $this->repository->createState($dummyActivity, ''); // Set process and state object to the data store $dataStore->setOwnerProcess($process); //Assertion: The get process must be equal to the set process $this->assertEquals($process, $dataStore->getOwnerProcess()); //Assertion: the data store should have a non initialized item subject $this->assertNull($dataStore->getItemSubject()); } /** * Tests the setDotData function with various scenarios */ public function testSetDotData() { $dataStore = $this->repository->createDataStore(); // Test simple dot notation $dataStore->setDotData('user.name', 'John Doe'); $userData = $dataStore->getData('user'); $this->assertEquals('John Doe', $userData['name']); // Test nested dot notation $dataStore->setDotData('user.profile.email', 'john@example.com'); $userData = $dataStore->getData('user'); $this->assertEquals('john@example.com', $userData['profile']['email']); // Test deeply nested structure $dataStore->setDotData('company.departments.engineering.team.lead', 'Jane Smith'); $companyData = $dataStore->getData('company'); $this->assertEquals('Jane Smith', $companyData['departments']['engineering']['team']['lead']); // Test numeric keys $dataStore->setDotData('items.0.name', 'First Item'); $dataStore->setDotData('items.1.name', 'Second Item'); $itemsData = $dataStore->getData('items'); $this->assertEquals('First Item', $itemsData[0]['name']); $this->assertEquals('Second Item', $itemsData[1]['name']); // Test numeric final key (to cover the is_numeric check for finalKey) $dataStore->setDotData('scores.0', 100); $dataStore->setDotData('scores.1', 200); $scoresData = $dataStore->getData('scores'); $this->assertEquals(100, $scoresData[0]); $this->assertEquals(200, $scoresData[1]); // Test overwriting existing values $dataStore->setDotData('user.name', 'Jane Doe'); $userData = $dataStore->getData('user'); $this->assertEquals('Jane Doe', $userData['name']); // Test setting complex values $complexValue = ['type' => 'admin', 'permissions' => ['read', 'write']]; $dataStore->setDotData('user.role', $complexValue); $userData = $dataStore->getData('user'); $this->assertEquals($complexValue, $userData['role']); // Test setting null values $dataStore->setDotData('user.middleName', null); $userData = $dataStore->getData('user'); $this->assertNull($userData['middleName']); // Test setting boolean values $dataStore->setDotData('user.active', true); $userData = $dataStore->getData('user'); $this->assertTrue($userData['active']); // Test setting numeric values $dataStore->setDotData('user.age', 30); $userData = $dataStore->getData('user'); $this->assertEquals(30, $userData['age']); // Test that the method returns the data store instance for chaining $result = $dataStore->setDotData('test.chain', 'value'); $this->assertSame($dataStore, $result); // Verify the complete data structure $expectedData = [ 'user' => [ 'name' => 'Jane Doe', 'profile' => [ 'email' => 'john@example.com' ], 'role' => [ 'type' => 'admin', 'permissions' => ['read', 'write'] ], 'middleName' => null, 'active' => true, 'age' => 30 ], 'company' => [ 'departments' => [ 'engineering' => [ 'team' => [ 'lead' => 'Jane Smith' ] ] ] ], 'items' => [ 0 => [ 'name' => 'First Item' ], 1 => [ 'name' => 'Second Item' ] ], 'scores' => [ 0 => 100, 1 => 200 ], 'test' => [ 'chain' => 'value' ] ]; $this->assertEquals($expectedData, $dataStore->getData()); } /** * Tests the getDotData function with various scenarios */ public function testGetDotData() { $dataStore = $this->repository->createDataStore(); // Set up test data using setDotData $dataStore->setDotData('user.name', 'John Doe'); $dataStore->setDotData('user.profile.email', 'john@example.com'); $dataStore->setDotData('user.profile.age', 30); $dataStore->setDotData('user.active', true); $dataStore->setDotData('user.role', ['type' => 'admin', 'permissions' => ['read', 'write']]); $dataStore->setDotData('company.departments.engineering.team.lead', 'Jane Smith'); $dataStore->setDotData('items.0.name', 'First Item'); $dataStore->setDotData('items.1.name', 'Second Item'); $dataStore->setDotData('scores.0', 100); $dataStore->setDotData('scores.1', 200); $dataStore->setDotData('user.middleName', null); // Test simple dot notation retrieval $this->assertEquals('John Doe', $dataStore->getDotData('user.name')); $this->assertEquals('john@example.com', $dataStore->getDotData('user.profile.email')); $this->assertEquals(30, $dataStore->getDotData('user.profile.age')); $this->assertTrue($dataStore->getDotData('user.active')); // Test nested dot notation retrieval $this->assertEquals('Jane Smith', $dataStore->getDotData('company.departments.engineering.team.lead')); // Test numeric keys $this->assertEquals('First Item', $dataStore->getDotData('items.0.name')); $this->assertEquals('Second Item', $dataStore->getDotData('items.1.name')); // Test numeric final keys $this->assertEquals(100, $dataStore->getDotData('scores.0')); $this->assertEquals(200, $dataStore->getDotData('scores.1')); // Test complex values $expectedRole = ['type' => 'admin', 'permissions' => ['read', 'write']]; $this->assertEquals($expectedRole, $dataStore->getDotData('user.role')); // Test null values $this->assertNull($dataStore->getDotData('user.middleName')); // Test non-existent paths with default values $this->assertNull($dataStore->getDotData('non.existent.path')); $this->assertEquals('default', $dataStore->getDotData('non.existent.path', 'default')); $this->assertEquals('fallback', $dataStore->getDotData('user.nonExistent', 'fallback')); // Test partial path that doesn't exist $this->assertNull($dataStore->getDotData('user.profile.nonExistent')); $this->assertEquals('not found', $dataStore->getDotData('user.profile.nonExistent', 'not found')); // Test deeply nested non-existent path $this->assertNull($dataStore->getDotData('company.departments.marketing.team.lead')); $this->assertEquals('no lead', $dataStore->getDotData('company.departments.marketing.team.lead', 'no lead')); // Test numeric key that doesn't exist $this->assertNull($dataStore->getDotData('items.2.name')); $this->assertEquals('missing', $dataStore->getDotData('items.2.name', 'missing')); // Test empty path $this->assertNull($dataStore->getDotData('')); $this->assertEquals('empty', $dataStore->getDotData('', 'empty')); // Test single key that exists (returns the entire user array) $userData = $dataStore->getDotData('user'); $this->assertIsArray($userData); $this->assertEquals('John Doe', $userData['name']); $this->assertEquals('john@example.com', $userData['profile']['email']); $this->assertEquals(30, $userData['profile']['age']); $this->assertTrue($userData['active']); $this->assertNull($userData['middleName']); // Test single key that doesn't exist $this->assertNull($dataStore->getDotData('nonexistent')); $this->assertEquals('not found', $dataStore->getDotData('nonexistent', 'not found')); // Test boolean false value $dataStore->setDotData('user.disabled', false); $this->assertFalse($dataStore->getDotData('user.disabled')); // Test zero value $dataStore->setDotData('user.score', 0); $this->assertEquals(0, $dataStore->getDotData('user.score')); // Test empty string $dataStore->setDotData('user.description', ''); $this->assertEquals('', $dataStore->getDotData('user.description')); // Test empty array $dataStore->setDotData('user.tags', []); $this->assertEquals([], $dataStore->getDotData('user.tags')); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/ArtifactTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/ArtifactTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Artifact; use ProcessMaker\Nayra\Bpmn\Models\Process; class ArtifactTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testSettersAndGetters() { // Create the objects that will be set $process = new Process(); $artifact = new Artifact(); //use the setters $artifact->setProcess($process); //Assertion: The set process must be equal to the created process $this->assertEquals($process, $artifact->getProcess()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/ConditionedExclusiveTransitionTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/ConditionedExclusiveTransitionTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\DataStore; use ProcessMaker\Nayra\Bpmn\Models\ExclusiveGateway; use ProcessMaker\Nayra\Bpmn\Models\Process; use ProcessMaker\Nayra\Contracts\Engine\EngineInterface; /** * Tests for the ConditionedTransition class */ class ConditionedExclusiveTransitionTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testAssertCondition() { $gateway = new ExclusiveGateway(); $conditionedTransition = new ConditionedExclusiveTransition($gateway); $conditionedTransition->setCondition(function ($data) { return $data['foo']; }); // Mock a engine data store $process = new Process(); $engine = $this->getMockBuilder(EngineInterface::class)->getMock(); $dataStore = new DataStore(); $dataStore->setData(['foo' => 'bar']); $engine->method('getDataStore')->willReturn($dataStore); $process->setEngine($engine); $conditionedTransition->setOwnerProcess($process); // Assertion: The condition should return 'bar' $this->assertEquals('bar', $conditionedTransition->assertCondition()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/OperationTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/OperationTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Message; use ProcessMaker\Nayra\Bpmn\Models\Operation; use ProcessMaker\Nayra\Contracts\Bpmn\OperationInterface; /** * Tests for the Operation class */ class OperationTest extends TestCase { /** * Tests that setters and getters are working properly */ public function testSettersAndGetters() { // Create the objects that will be set in the data store $operation = new Operation(); $dummyFunction = function () { return true; }; $dummyMessage = new Message(); // Use the setters $operation->setProperty(OperationInterface::BPMN_PROPERTY_IMPLEMENTATION, $dummyFunction); $operation->setProperty(OperationInterface::BPMN_PROPERTY_IN_MESSAGE, $dummyMessage); $operation->setProperty(OperationInterface::BPMN_PROPERTY_OUT_MESSAGE, $dummyMessage); $operation->setProperty(OperationInterface::BPMN_PROPERTY_ERRORS, []); //Assertion: The getters should return the set objects $this->assertEquals($dummyFunction, $operation->getImplementation()); $this->assertEquals($dummyMessage, $operation->getInMessage()); $this->assertEquals($dummyMessage, $operation->getOutMessage()); $this->assertEquals([], $operation->getErrors()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Bpmn/BaseTraitTest.php
tests/unit/ProcessMaker/Nayra/Bpmn/BaseTraitTest.php
<?php namespace ProcessMaker\Nayra\Bpmn; use PHPUnit\Framework\TestCase; use ProcessMaker\Nayra\Bpmn\Models\Process; use ProcessMaker\Nayra\Contracts\Bpmn\EntityInterface; /** * Test the base trait behavior. */ class BaseTraitTest extends TestCase { /** * Test ID property getter and setter */ public function testSetGetId() { $testId = 'testId'; $process = new Process(); $originalNumberOfProperties = count($process->getProperties()); $process->setId($testId); $this->assertEquals( $testId, $process->getId(), 'The stored id must be equal to the testId' ); $this->assertCount( $originalNumberOfProperties + 1, $process->getProperties(), 'The properties array must have one item' ); $this->assertEquals( $testId, $process->getProperties()[EntityInterface::BPMN_PROPERTY_ID], 'The properties array must have one item (the id)' ); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
ProcessMaker/nayra
https://github.com/ProcessMaker/nayra/blob/19d721d6bd27f80d33288125488b244e83b6e191/tests/unit/ProcessMaker/Nayra/Engine/ExecutionInstanceTest.php
tests/unit/ProcessMaker/Nayra/Engine/ExecutionInstanceTest.php
<?php namespace ProcessMaker\Nayra\Engine; use PHPUnit\Framework\TestCase; use ProcessMaker\Bpmn\TestEngine; use ProcessMaker\Nayra\Contracts\Bpmn\DataStoreInterface; use ProcessMaker\Nayra\Contracts\Bpmn\ProcessInterface; use ProcessMaker\Nayra\Contracts\EventBusInterface; use ProcessMaker\Test\Models\Repository; /** * Execution Instance tests */ class ExecutionInstanceTest extends TestCase { /** * Tests that a new ExecutionInstance is initialized correctly */ public function testExecutionInstanceInitialization() { // mocks to be used in the ExecutionInstance constructor $mockDispatcher = $this->getMockBuilder(EventBusInterface::class) ->getMock(); $engine = new TestEngine(new Repository(), $mockDispatcher); $mockProcess = $this->getMockForAbstractClass(ProcessInterface::class); $mockStore = $this->getMockForAbstractClass(DataStoreInterface::class); $instance = new ExecutionInstance(); $instance->linkTo($engine, $mockProcess, $mockStore); //Assertion: the getProcess method should return the same injected process $this->assertEquals($mockProcess, $instance->getProcess()); //Assertion: the getDataStore method should return the same injected data store $this->assertEquals($mockStore, $instance->getDataStore()); } }
php
Apache-2.0
19d721d6bd27f80d33288125488b244e83b6e191
2026-01-05T05:04:52.897638Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/src/Vote.php
src/Vote.php
<?php namespace Jcc\LaravelVote; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Support\Facades\Auth; use Jcc\LaravelVote\Events\CancelVoted; use Jcc\LaravelVote\Events\Voted; /** * Class Vote * * @property string $vote_type * @property string $votable_type */ class Vote extends Model { protected $guarded = []; protected $dispatchesEvents = [ 'created' => Voted::class, 'updated' => Voted::class, 'deleted' => CancelVoted::class, ]; /** * @param array $attributes */ public function __construct(array $attributes = []) { $this->table = \config('vote.votes_table'); parent::__construct($attributes); } protected static function boot() { parent::boot(); self::creating(function (Vote $vote) { $userForeignKey = \config('vote.user_foreign_key'); $vote->{$userForeignKey} = $vote->{$userForeignKey} ?: Auth::id(); }); } public function votable(): MorphTo { return $this->morphTo(); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo(\config('auth.providers.users.model'), \config('vote.user_foreign_key')); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function voter() { return $this->user(); } /** * @param \Illuminate\Database\Eloquent\Builder $query * @param string $type * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeWithVotableType(Builder $query, string $type) { return $query->where('votable_type', \app($type)->getMorphClass()); } /** * @param \Illuminate\Database\Eloquent\Builder $query * @param string $type * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeWithVoteType(Builder $query, string $type) { return $query->where('vote_type', (string)new VoteItems($type)); } public function isUp(): bool { return $this->vote_type === VoteItems::UP; } public function isDown(): bool { return $this->vote_type === VoteItems::DOWN; } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/src/VoteItems.php
src/VoteItems.php
<?php namespace Jcc\LaravelVote; use Jcc\LaravelVote\Exceptions\UnexpectValueException; use Stringable; final class VoteItems implements Stringable { /** * @var string */ protected $value; public const UP = 'up_vote'; public const DOWN = 'down_vote'; public function __construct(string $value) { if (!in_array($value, self::getValues(), true)) { throw new UnexpectValueException("Unexpect Value: {$value}"); } $this->value = $value; } /** * @return string[] */ public static function getValues(): array { return [self::UP, self::DOWN]; } /** * @return string */ public function __toString() { return $this->value; } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/src/VoteServiceProvider.php
src/VoteServiceProvider.php
<?php /* * This file is part of the jcc/laravel-vote. * * (c) jcc <changejian@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Jcc\LaravelVote; use Illuminate\Support\ServiceProvider; class VoteServiceProvider extends ServiceProvider { /** * Application bootstrap event. */ public function boot() { $this->publishes([ \dirname(__DIR__) . '/config/vote.php' => config_path('vote.php'), ], 'config'); $this->publishes([ \dirname(__DIR__) . '/migrations/' => database_path('migrations'), ], 'migrations'); if ($this->app->runningInConsole()) { $this->loadMigrationsFrom(\dirname(__DIR__) . '/migrations/'); } } /** * Register the service provider. */ public function register() { $this->mergeConfigFrom( \dirname(__DIR__) . '/config/vote.php', 'vote' ); } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/src/Exceptions/UnexpectValueException.php
src/Exceptions/UnexpectValueException.php
<?php namespace Jcc\LaravelVote\Exceptions; use Exception; class UnexpectValueException extends Exception { }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/src/Traits/Votable.php
src/Traits/Votable.php
<?php namespace Jcc\LaravelVote\Traits; use Illuminate\Database\Eloquent\Model; use Jcc\LaravelVote\VoteItems; /** * Trait Votable * * @mixin \Illuminate\Database\Eloquent\Model */ trait Votable { /** * @param \Illuminate\Database\Eloquent\Model $user * * @return bool */ public function isVotedBy(Model $user, ?string $type = null): bool { if (\is_a($user, \config('auth.providers.users.model'))) { if ($this->relationLoaded('voters')) { return $this->voters->contains($user); } return $this->voters() ->where(\config('vote.user_foreign_key'), $user->getKey()) ->when(\is_string($type), function ($builder) use ($type) { $builder->where('vote_type', (string)new VoteItems($type)); }) ->exists(); } return false; } /** * Return voters. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function voters(): \Illuminate\Database\Eloquent\Relations\BelongsToMany { return $this->belongsToMany( \config('auth.providers.users.model'), \config('vote.votes_table'), 'votable_id', \config('vote.user_foreign_key') ) ->where('votable_type', $this->getMorphClass()); } /** * @param \Illuminate\Database\Eloquent\Model $user * * @return bool */ public function isUpVotedBy(Model $user) { return $this->isVotedBy($user, VoteItems::UP); } /** * Return up voters. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function upVoters(): \Illuminate\Database\Eloquent\Relations\BelongsToMany { return $this->voters()->where('vote_type', VoteItems::UP); } /** * @param \Illuminate\Database\Eloquent\Model $user * * @return bool */ public function isDownVotedBy(Model $user) { return $this->isVotedBy($user, VoteItems::DOWN); } /** * Return down voters. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function downVoters(): \Illuminate\Database\Eloquent\Relations\BelongsToMany { return $this->voters()->where('vote_type', VoteItems::DOWN); } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/src/Traits/Voter.php
src/Traits/Voter.php
<?php namespace Jcc\LaravelVote\Traits; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Jcc\LaravelVote\Vote; use Jcc\LaravelVote\VoteItems; /** * Trait Voter * * @mixin \Illuminate\Database\Eloquent\Model */ trait Voter { /** * @param Model $object * @param string $type * @return \Jcc\LaravelVote\Vote * @throws \Jcc\LaravelVote\Exceptions\UnexpectValueException */ public function vote(Model $object, string $type): Vote { $attributes = [ 'votable_type' => $object->getMorphClass(), 'votable_id' => $object->getKey(), \config('vote.user_foreign_key') => $this->getKey(), ]; /* @var \Illuminate\Database\Eloquent\Model $vote */ $vote = \app(\config('vote.vote_model')); $type = (string)new VoteItems($type); /* @var \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder $vote */ return tap($vote->where($attributes)->firstOr( function () use ($vote, $attributes, $type) { $vote->unguard(); if ($this->relationLoaded('votes')) { $this->unsetRelation('votes'); } return $vote->create(\array_merge($attributes, [ 'vote_type' => $type, ])); } ), function (Model $model) use ($type) { $model->update(['vote_type' => $type]); }); } /** * @param \Illuminate\Database\Eloquent\Model $object * * @return bool */ public function hasVoted(Model $object, ?string $type = null): bool { return ($this->relationLoaded('votes') ? $this->votes : $this->votes()) ->where('votable_id', $object->getKey()) ->where('votable_type', $object->getMorphClass()) ->when(\is_string($type), function ($builder) use ($type) { $builder->where('vote_type', (string)new VoteItems($type)); }) ->count() > 0; } /** * @param Model $object * @return bool * @throws \Exception */ public function cancelVote(Model $object): bool { /* @var \Jcc\LaravelVote\Vote $relation */ $relation = \app(\config('vote.vote_model')) ->where('votable_id', $object->getKey()) ->where('votable_type', $object->getMorphClass()) ->where(\config('vote.user_foreign_key'), $this->getKey()) ->first(); if ($relation) { if ($this->relationLoaded('votes')) { $this->unsetRelation('votes'); } return $relation->delete(); } return true; } /** * @return HasMany */ public function votes(): HasMany { return $this->hasMany(\config('vote.vote_model'), \config('vote.user_foreign_key'), $this->getKeyName()); } /** * Get Query Builder for votes * * @return \Illuminate\Database\Eloquent\Builder */ public function getVotedItems(string $model, ?string $type = null) { return \app($model)->whereHas( 'voters', function ($builder) use ($type) { return $builder->where(\config('vote.user_foreign_key'), $this->getKey())->when( \is_string($type), function ($builder) use ($type) { $builder->where('vote_type', (string)new VoteItems($type)); } ); } ); } public function upVote(Model $object): Vote { return $this->vote($object, VoteItems::UP); } public function downVote(Model $object): Vote { return $this->vote($object, VoteItems::DOWN); } public function hasUpVoted(Model $object) { return $this->hasVoted($object, VoteItems::UP); } public function hasDownVoted(Model $object) { return $this->hasVoted($object, VoteItems::DOWN); } public function toggleUpVote(Model $object) { return $this->hasUpVoted($object) ? $this->cancelVote($object) : $this->upVote($object); } public function toggleDownVote(Model $object) { return $this->hasDownVoted($object) ? $this->cancelVote($object) : $this->downVote($object); } public function getUpVotedItems(string $model) { return $this->getVotedItems($model, VoteItems::UP); } public function getDownVotedItems(string $model) { return $this->getVotedItems($model, VoteItems::DOWN); } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/src/Events/CancelVoted.php
src/Events/CancelVoted.php
<?php namespace Jcc\LaravelVote\Events; class CancelVoted extends Event { }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/src/Events/Event.php
src/Events/Event.php
<?php namespace Jcc\LaravelVote\Events; use Illuminate\Database\Eloquent\Model; class Event { /** * @var \Illuminate\Database\Eloquent\Model */ public $vote; /** * Event constructor. * * @param \Illuminate\Database\Eloquent\Model $vote */ public function __construct(Model $vote) { $this->vote = $vote; } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/src/Events/Voted.php
src/Events/Voted.php
<?php namespace Jcc\LaravelVote\Events; class Voted extends Event { }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/tests/User.php
tests/User.php
<?php namespace Jcc\LaravelVote\Tests; use Illuminate\Database\Eloquent\Model; use Jcc\LaravelVote\Traits\Votable; use Jcc\LaravelVote\Traits\Voter; class User extends Model { use Voter; use Votable; protected $fillable = ['name']; }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/tests/TestCase.php
tests/TestCase.php
<?php namespace Jcc\LaravelVote\Tests; use Jcc\LaravelVote\VoteServiceProvider; abstract class TestCase extends \Orchestra\Testbench\TestCase { /** * Load package service provider. * * @param \Illuminate\Foundation\Application $app * * @return array */ protected function getPackageProviders($app) { return [VoteServiceProvider::class]; } /** * Define environment setup. * * @param \Illuminate\Foundation\Application $app */ protected function getEnvironmentSetUp($app) { // Setup default database to use sqlite :memory: $app['config']->set('database.default', 'testing'); $app['config']->set('database.connections.testing', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } /** * run package database migrations. */ public function setUp(): void { parent::setUp(); $this->loadMigrationsFrom(__DIR__ . '/migrations'); $this->loadMigrationsFrom(dirname(__DIR__) . '/migrations'); } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/tests/FeatureTest.php
tests/FeatureTest.php
<?php namespace Jcc\LaravelVote\Tests; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; use Jcc\LaravelVote\Events\Voted; use Jcc\LaravelVote\Exceptions\UnexpectValueException; use Jcc\LaravelVote\VoteItems; class FeatureTest extends TestCase { public function setUp(): void { parent::setUp(); Event::fake(); config(['auth.providers.users.model' => User::class]); } public function test_voteItems() { self::assertEquals('up_vote', (string)(new VoteItems('up_vote'))); self::assertEquals('down_vote', (string)(new VoteItems('down_vote'))); $invalidValue = 'foobar'; $this->expectException(UnexpectValueException::class); $this->expectDeprecationMessage("Unexpect Value: {$invalidValue}"); new VoteItems($invalidValue); } public function test_basic_features() { /** @var User $user */ $user = User::create(['name' => 'jcc']); /** @var Post $post */ $post = Post::create(['title' => 'Hello world!']); $user->vote($post, VoteItems::UP); Event::assertDispatched(Voted::class, function ($event) use ($user, $post) { $vote = $event->vote; self::assertTrue($vote->isUp()); self::assertFalse($vote->isDown()); return $vote->votable instanceof Post && $vote->user instanceof User && $vote->user->id === $user->id && $vote->votable->id === $post->id; }); self::assertTrue($user->hasVoted($post)); self::assertTrue($user->hasUpVoted($post)); self::assertFalse($user->hasDownVoted($post)); self::assertTrue($post->isVotedBy($user)); self::assertTrue($post->isUpVotedBy($user)); self::assertFalse($post->isDownVotedBy($user)); self::assertTrue($user->cancelVote($post)); Event::fake(); $user->vote($post, VoteItems::DOWN); Event::assertDispatched(Voted::class, function ($event) use ($user, $post) { $vote = $event->vote; self::assertFalse($vote->isUp()); self::assertTrue($vote->isDown()); return $vote->votable instanceof Post && $vote->user instanceof User && $vote->user->id === $user->id && $vote->votable->id === $post->id; }); self::assertTrue($user->hasVoted($post)); self::assertFalse($user->hasUpVoted($post)); self::assertTrue($user->hasDownVoted($post)); self::assertTrue($post->isVotedBy($user)); self::assertFalse($post->isUpVotedBy($user)); self::assertTrue($post->isDownVotedBy($user)); /** @var User $user */ $user = User::create(['name' => 'jcc']); /** @var Post $post */ $post = Post::create(['title' => 'Hello world!']); $user->vote($post, VoteItems::UP); Event::fake(); $user->vote($post, VoteItems::DOWN); Event::assertDispatched(Voted::class, function ($event) use ($user, $post) { $vote = $event->vote; self::assertFalse($vote->isUp()); self::assertTrue($vote->isDown()); return $vote->votable instanceof Post && $vote->user instanceof User && $vote->user->id === $user->id && $vote->votable->id === $post->id; }); } public function test_cancelVote_features() { $user1 = User::create(['name' => 'jcc']); $user2 = User::create(['name' => 'allen']); $post = Post::create(['title' => 'Hello world!']); $user1->vote($post, VoteItems::DOWN); $user2->vote($post, VoteItems::UP); $user1->cancelVote($post); $user2->cancelVote($post); self::assertFalse($user1->hasVoted($post)); self::assertFalse($user1->hasDownVoted($post)); self::assertFalse($user1->hasUpVoted($post)); self::assertFalse($user1->hasVoted($post)); self::assertFalse($user2->hasUpVoted($post)); self::assertFalse($user2->hasDownVoted($post)); } public function test_upVoted_to_downVoted_each_other_features() { $user1 = User::create(['name' => 'jcc']); $user2 = User::create(['name' => 'allen']); $post = Post::create(['title' => 'Hello world!']); $upModel = $user1->vote($post, VoteItems::UP); self::assertTrue($user1->hasUpVoted($post)); self::assertFalse($user1->hasDownVoted($post)); $downModel = $user1->vote($post, VoteItems::DOWN); self::assertFalse($user1->hasUpVoted($post)); self::assertTrue($user1->hasDownVoted($post)); self::assertTrue($user1->hasDownVoted($post)); self::assertEquals($upModel->id, $downModel->id); $downModel = $user2->vote($post, VoteItems::DOWN); self::assertFalse($user2->hasUpVoted($post)); self::assertTrue($user2->hasDownVoted($post)); $upModel = $user2->vote($post, VoteItems::UP); self::assertTrue($user2->hasUpVoted($post)); self::assertFalse($user2->hasDownVoted($post)); self::assertEquals($upModel->id, $downModel->id); } public function test_aggregations() { $user = User::create(['name' => 'jcc']); $post1 = Post::create(['title' => 'Hello world!']); $post2 = Post::create(['title' => 'Hello everyone!']); $post3 = Post::create(['title' => 'Hello players!']); $book1 = Book::create(['title' => 'Learn laravel.']); $book2 = Book::create(['title' => 'Learn symfony.']); $book3 = Book::create(['title' => 'Learn yii2.']); $user->vote($post1, VoteItems::UP); $user->vote($post2, VoteItems::UP); $user->vote($post3, VoteItems::DOWN); $user->vote($book1, VoteItems::UP); $user->vote($book2, VoteItems::UP); $user->vote($book3, VoteItems::DOWN); self::assertSame(6, $user->votes()->count()); self::assertSame(4, $user->votes()->withVoteType(VoteItems::UP)->count()); self::assertSame(2, $user->votes()->withVoteType(VoteItems::DOWN)->count()); self::assertSame(3, $user->votes()->withVotableType(Book::class)->count()); self::assertSame(1, $user->votes()->withVoteType(VoteItems::DOWN)->withVotableType(Book::class)->count()); } public function test_vote_same_model() { $user1 = User::create(['name' => 'jcc']); $user2 = User::create(['name' => 'allen']); $user3 = User::create(['name' => 'taylor']); $user1->vote($user2, VoteItems::UP); $user3->vote($user1, VoteItems::DOWN); self::assertTrue($user1->hasVoted($user2)); self::assertTrue($user2->isVotedBy($user1)); self::assertTrue($user1->hasUpVoted($user2)); self::assertTrue($user2->isUpVotedBy($user1)); self::assertTrue($user3->hasVoted($user1)); self::assertTrue($user1->isVotedBy($user3)); self::assertTrue($user3->hasDownVoted($user1)); self::assertTrue($user1->isDownVotedBy($user3)); } public function test_object_voters() { $user1 = User::create(['name' => 'jcc']); $user2 = User::create(['name' => 'allen']); $user3 = User::create(['name' => 'taylor']); $post = Post::create(['title' => 'Hello world!']); $user1->vote($post, VoteItems::UP); $user2->vote($post, VoteItems::DOWN); self::assertCount(2, $post->voters); self::assertSame('jcc', $post->voters[0]['name']); self::assertSame('allen', $post->voters[1]['name']); $sqls = $this->getQueryLog(function () use ($post, $user1, $user2, $user3) { self::assertTrue($post->isVotedBy($user1)); self::assertTrue($post->isVotedBy($user2)); self::assertFalse($post->isVotedBy($user3)); }); self::assertEmpty($sqls->all()); } public function test_object_votes_with_custom_morph_class_name() { $user1 = User::create(['name' => 'jcc']); $user2 = User::create(['name' => 'allen']); $user3 = User::create(['name' => 'taylor']); $post = Post::create(['title' => 'Hello world!']); Relation::morphMap([ 'posts' => Post::class, ]); $user1->vote($post, VoteItems::UP); $user2->vote($post, VoteItems::DOWN); self::assertCount(2, $post->voters); self::assertSame('jcc', $post->voters[0]['name']); self::assertSame('allen', $post->voters[1]['name']); } public function test_eager_loading() { $user = User::create(['name' => 'jcc']); $post1 = Post::create(['title' => 'Hello world!']); $post2 = Post::create(['title' => 'Hello everyone!']); $book1 = Book::create(['title' => 'Learn laravel.']); $book2 = Book::create(['title' => 'Learn symfony.']); $user->vote($post1, VoteItems::UP); $user->vote($post2, VoteItems::DOWN); $user->vote($book1, VoteItems::UP); $user->vote($book2, VoteItems::DOWN); // start recording $sqls = $this->getQueryLog(function () use ($user) { $user->load('votes.votable'); }); self::assertSame(3, $sqls->count()); // from loaded relations $sqls = $this->getQueryLog(function () use ($user, $post1) { $user->hasVoted($post1); }); self::assertEmpty($sqls->all()); } /** * @param \Closure $callback * * @return \Illuminate\Support\Collection */ protected function getQueryLog(\Closure $callback): \Illuminate\Support\Collection { $sqls = \collect([]); DB::listen(function ($query) use ($sqls) { $sqls->push(['sql' => $query->sql, 'bindings' => $query->bindings]); }); $callback(); return $sqls; } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/tests/Post.php
tests/Post.php
<?php namespace Jcc\LaravelVote\Tests; use Illuminate\Database\Eloquent\Model; use Jcc\LaravelVote\Traits\Votable; class Post extends Model { use Votable; protected $fillable = ['title']; }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/tests/Book.php
tests/Book.php
<?php namespace Jcc\LaravelVote\Tests; use Illuminate\Database\Eloquent\Model; use Jcc\LaravelVote\Traits\Votable; class Book extends Model { use Votable; protected $fillable = ['title']; }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/tests/migrations/2021_03_13_000000_create_posts_table.php
tests/migrations/2021_03_13_000000_create_posts_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostsTable extends Migration { /** * Run the migrations. */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down() { Schema::dropIfExists('posts'); } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/tests/migrations/2021_03_13_000000_create_books_table.php
tests/migrations/2021_03_13_000000_create_books_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateBooksTable extends Migration { /** * Run the migrations. */ public function up() { Schema::create('books', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down() { Schema::dropIfExists('books'); } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/tests/migrations/2021_03_13_000000_create_users_table.php
tests/migrations/2021_03_13_000000_create_users_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down() { Schema::dropIfExists('users'); } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/migrations/2021_03_13_000000_create_votes_table.php
migrations/2021_03_13_000000_create_votes_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVotesTable extends Migration { /** * Run the migrations. */ public function up() { Schema::create(config('vote.votes_table'), function (Blueprint $table) { $table->increments('id'); $table->unsignedBigInteger(config('vote.user_foreign_key'))->index(); $table->morphs('votable'); $table->string('vote_type', 16)->default('up_vote'); // 'up_vote'/'down_vote' $table->timestamps(); }); } /** * Reverse the migrations. */ public function down() { Schema::dropIfExists(config('vote.votes_table')); } }
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
jcc/laravel-vote
https://github.com/jcc/laravel-vote/blob/b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330/config/vote.php
config/vote.php
<?php return [ 'votes_table' => 'votes', 'user_foreign_key' => 'user_id', 'vote_model' => \Jcc\LaravelVote\Vote::class, ];
php
MIT
b2ff453c2e8bbb5b9620e1a75f8dcddd6e1bd330
2026-01-05T05:05:05.783905Z
false
hooklife/thinkphp5-wechat
https://github.com/hooklife/thinkphp5-wechat/blob/a66a075a9c52cd7dadfe357ad88ac2fc20193fa6/src/Wechat.php
src/Wechat.php
<?php /** * Created by PhpStorm. * User: hooklife * Date: 2017/1/12 * Time: 12:00 */ namespace Hooklife\ThinkphpWechat; use EasyWeChat\Foundation\Application; use think\Config; /** * Class Wechat 微信类 * @package Hooklife\ThinkphpWechat * @method static \EasyWeChat\Core\AccessToken access_token * @method static \EasyWeChat\Server\Guard server * @method static \EasyWeChat\User\User user * @method static \EasyWeChat\User\Tag user_tag * @method static \EasyWeChat\User\Group user_group * @method static \EasyWeChat\Js\Js js * @method static \Overtrue\Socialite\SocialiteManager oauth * @method static \EasyWeChat\Menu\Menu menu * @method static \EasyWeChat\Notice\Notice notice * @method static \EasyWeChat\Material\Material material * @method static \EasyWeChat\Material\Temporary material_temporary * @method static \EasyWeChat\Staff\Staff staff * @method static \EasyWeChat\Url\Url url * @method static \EasyWeChat\QRCode\QRCode qrcode * @method static \EasyWeChat\Semantic\Semantic semantic * @method static \EasyWeChat\Stats\Stats stats * @method static \EasyWeChat\Payment\Merchant merchant * @method static \EasyWeChat\Payment\Payment payment * @method static \EasyWeChat\Payment\LuckyMoney\LuckyMoney lucky_money * @method static \EasyWeChat\Payment\MerchantPay\MerchantPay merchant_pay * @method static \EasyWeChat\Reply\Reply reply * @method static \EasyWeChat\Broadcast\Broadcast broadcast * @method static \EasyWeChat\Card\Card card * @method static \EasyWeChat\Device\Device device * @method static \EasyWeChat\ShakeAround\ShakeAround shakearound * @method static \EasyWeChat\User\MiniAppUser mini_app_user * @method static \EasyWeChat\OpenPlatform\OpenPlatform open_platform * */ class Wechat { protected static $app; public static function app() { if (!isset(self::$app)) { $options = Config::get('wechat'); if(!$options){ throw new \InvalidArgumentException("missing wechat config"); } self::$app = new Application($options); } return self::$app; } public static function __callStatic($name, $arguments) { return self::app()->$name; } }
php
Apache-2.0
a66a075a9c52cd7dadfe357ad88ac2fc20193fa6
2026-01-05T05:05:14.818097Z
false
hooklife/thinkphp5-wechat
https://github.com/hooklife/thinkphp5-wechat/blob/a66a075a9c52cd7dadfe357ad88ac2fc20193fa6/src/config.php
src/config.php
<?php /** * Created by PhpStorm. * User: hooklife * Date: 2017/1/12 * Time: 11:52 */ return [ /** * Debug 模式,bool 值:true/false * * 当值为 false 时,所有的日志都不会记录 */ 'debug' => true, /** * 账号基本信息,请从微信公众平台/开放平台获取 */ 'app_id' => 'your-app-id', // AppID 'secret' => 'your-app-secret', // AppSecret 'token' => 'your-token', // Token 'aes_key' => '', // EncodingAESKey,安全模式下请一定要填写!!! /** * 日志配置 * * level: 日志级别, 可选为: * debug/info/notice/warning/error/critical/alert/emergency * permission:日志文件权限(可选),默认为null(若为null值,monolog会取0644) * file:日志文件位置(绝对路径!!!),要求可写权限 */ 'log' => [ 'level' => 'debug', 'permission' => 0777, 'file' => LOG_PATH.'easywechat.log', ], /** * OAuth 配置 * * scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login * callback:OAuth授权完成后的回调页地址 */ 'oauth' => [ 'scopes' => ['snsapi_userinfo'], 'callback' => '/examples/oauth_callback.php', ], /** * 微信支付 */ 'payment' => [ 'merchant_id' => 'your-mch-id', 'key' => 'key-for-signature', 'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径!!!! 'key_path' => 'path/to/your/key', // XXX: 绝对路径!!!! // 'device_info' => '013467007045764', // 'sub_app_id' => '', // 'sub_merchant_id' => '', // ... ], /** * Guzzle 全局设置 * * 更多请参考: http://docs.guzzlephp.org/en/latest/request-options.html */ 'guzzle' => [ 'timeout' => 3.0, // 超时时间(秒) //'verify' => false, // 关掉 SSL 认证(强烈不建议!!!) ], ];
php
Apache-2.0
a66a075a9c52cd7dadfe357ad88ac2fc20193fa6
2026-01-05T05:05:14.818097Z
false
hooklife/thinkphp5-wechat
https://github.com/hooklife/thinkphp5-wechat/blob/a66a075a9c52cd7dadfe357ad88ac2fc20193fa6/src/helper.php
src/helper.php
<?php /** * Created by PhpStorm. * User: hooklife * Date: 2017/1/12 * Time: 15:32 */ \think\Console::addDefaultCommands([ \Hooklife\ThinkphpWechat\Command\SendConfig::class ]); if (!function_exists('wechat')) { /** * @param $name * @return mixed */ function wechat($name) { return call_user_func([\Hooklife\ThinkphpWechat\Wechat::class,$name]); } }
php
Apache-2.0
a66a075a9c52cd7dadfe357ad88ac2fc20193fa6
2026-01-05T05:05:14.818097Z
false
hooklife/thinkphp5-wechat
https://github.com/hooklife/thinkphp5-wechat/blob/a66a075a9c52cd7dadfe357ad88ac2fc20193fa6/src/Command/SendConfig.php
src/Command/SendConfig.php
<?php namespace Hooklife\ThinkphpWechat\Command; /** * Created by PhpStorm. * User: hooklife * Date: 2017/1/12 * Time: 15:39 */ use think\console\Command; use think\console\Input; use think\console\Output; class SendConfig extends Command { public function configure() { $this->setName('wechat:config') ->setDescription('send config to tp folder'); } public function execute(Input $input, Output $output) { //获取默认配置文件 $content = file_get_contents(VENDOR_PATH .'hooklife/thinkphp5-wechat/src/config.php'); $configPath = CONF_PATH.'extra/'; $configFile = $configPath.'wechat.php'; //判断目录是否存在 if (!file_exists($configPath)) { mkdir($configPath, 0755, true); } //判断文件是否存在 if (is_file($configFile)) { throw new \InvalidArgumentException(sprintf('The config file "%s" already exists', $configFile)); } if (false === file_put_contents($configFile, $content)) { throw new \RuntimeException(sprintf('The config file "%s" could not be written to "%s"', $configFile,$configPath)); } $output->writeln('create wechat config ok'); } }
php
Apache-2.0
a66a075a9c52cd7dadfe357ad88ac2fc20193fa6
2026-01-05T05:05:14.818097Z
false
luxixing/swoole-task
https://github.com/luxixing/swoole-task/blob/4f60a6f8185983c956d7c26f16c5819a58b96a71/src/HttpServer.php
src/HttpServer.php
<?php /** * 基于swoole扩展的http-server封装的一个接受异步任务请求的http服务器 */ namespace Ping\SwooleTask; use Ping\SwooleTask\Base\App as BaseApp; class HttpServer { /** * swoole http-server 实例 * * @var null | swoole_http_server */ private $server = null; /** * 应用实例 * * @var null | BaseApp */ private $app = null; /** * swoole 配置 * * @var array */ private $setting = []; /** * 加载框架[Base/*.php] */ private function loadFramework() { //TODO 未来可扩展内容继续完善 //框架核心文件 $coreFiles = [ 'Base' . DS . 'App.php', 'Base' . DS . 'Ctrl.php', 'Base' . DS . 'Dao.php', 'Base' . DS . 'Helper.php', ]; foreach ($coreFiles as $v) { include SW_SRC_ROOT . DS . 'src' . DS . $v; } } /** * 修改swooleTask进程名称,如果是macOS 系统,则忽略(macOS不支持修改进程名称) * * @param $name 进程名称 * * @return bool * @throws \Exception */ private function setProcessName($name) { if (PHP_OS == 'Darwin') { return false; } if (function_exists('cli_set_process_title')) { cli_set_process_title($name); } else { if (function_exists('swoole_set_process_name')) { swoole_set_process_name($name); } else { throw new \Exception(__METHOD__ . "failed,require cli_set_process_title|swoole_set_process_name"); } } } public function __construct($conf) { //TODO conf配置检查 $this->setting = $conf; } public function getSetting() { return $this->setting; } public function run() { $this->server = new \swoole_http_server($this->setting['host'], $this->setting['port']); $this->loadFramework(); $this->server->set($this->setting); //回调函数 $call = [ 'start', 'workerStart', 'managerStart', 'request', 'task', 'finish', 'workerStop', 'shutdown', ]; //事件回调函数绑定 foreach ($call as $v) { $m = 'on' . ucfirst($v); if (method_exists($this, $m)) { $this->server->on($v, [$this, $m]); } } //注入框架 常驻内存 $this->app = BaseApp::getApp($this->server); $this->server->start(); } /** * swoole-server master start * * @param $server */ public function onStart($server) { echo 'Date:' . date('Y-m-d H:i:s') . "\t swoole_http_server master worker start\n"; $this->setProcessName($server->setting['ps_name'] . '-master'); //记录进程id,脚本实现自动重启 $pid = "{$this->server->master_pid}\n{$this->server->manager_pid}"; file_put_contents($this->setting['pid_file'], $pid); } /** * manager worker start * * @param $server */ public function onManagerStart($server) { echo 'Date:' . date('Y-m-d H:i:s') . "\t swoole_http_server manager worker start\n"; $this->setProcessName($server->setting['ps_name'] . '-manager'); } /** * swoole-server master shutdown */ public function onShutdown() { unlink($this->setting['pid_file']); echo 'Date:' . date('Y-m-d H:i:s') . "\t swoole_http_server shutdown\n"; } /** * worker start 加载业务脚本常驻内存 * * @param $server * @param $workerId */ public function onWorkerStart($server, $workerId) { if ($workerId >= $this->setting['worker_num']) { $this->setProcessName($server->setting['ps_name'] . '-task'); } else { $this->setProcessName($server->setting['ps_name'] . '-work'); } } /** * worker 进程停止 * * @param $server * @param $workerId */ public function onWorkerStop($server, $workerId) { echo 'Date:' . date('Y-m-d H:i:s') . "\t swoole_http_server[{$server->setting['ps_name']}] worker:{$workerId} shutdown\n"; } /** * http请求处理 * * @param $request * @param $response * * @return mixed */ public function onRequest($request, $response) { //获取swoole服务的当前状态 if (isset($request->get['cmd']) && $request->get['cmd'] == 'status') { $res = $this->server->stats(); $res['start_time'] = date('Y-m-d H:i:s', $res['start_time']); $response->end(json_encode($res)); return true; } //TODO 非task请求处理 $this->server->task($request); $out = '[' . date('Y-m-d H:i:s') . '] ' . json_encode($request) . PHP_EOL; //INFO 立即返回 非阻塞 $response->end($out); return true; } /** * 任务处理 * * @param $server * @param $taskId * @param $fromId * @param $request * * @return mixed */ public function onTask($server, $taskId, $fromId, $request) { //任务执行 worker_pid实际上是就是处理任务进程的task进程id $ret = $this->app->run($request, $taskId, $fromId); if (!isset($ret['workerPid'])) { //处理此任务的task-worker-id $ret['workerPid'] = $server->worker_pid; } //INFO swoole-1.7.18之后return 就会自动调用finish return $ret; } /** * 任务结束回调函数 * * @param $server * @param $taskId * @param $ret */ public function onFinish($server, $taskId, $ret) { $fromId = $server->worker_id; if (!empty($ret['errno'])) { //任务成功运行不再提示 //echo "\tTask[taskId:{$taskId}] success" . PHP_EOL; $error = PHP_EOL . var_export($ret, true); echo "\tTask[taskId:$fromId#{$taskId}] failed, Error[$error]" . PHP_EOL; } } }
php
MIT
4f60a6f8185983c956d7c26f16c5819a58b96a71
2026-01-05T05:05:27.542964Z
false
luxixing/swoole-task
https://github.com/luxixing/swoole-task/blob/4f60a6f8185983c956d7c26f16c5819a58b96a71/src/Base/Helper.php
src/Base/Helper.php
<?php namespace Ping\SwooleTask\Base; /** * Class UtilsHelper * 一些通用方法 */ class Helper { public static function convertSize($size) { //FIXME size 负数是记录异常 $size = abs($size); $unit = ['b', 'kb', 'mb', 'gb', 'tb', 'pb']; return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i]; } /** * 递归的获取某个目录指定的文件 * * @param $dir * * @return array */ public static function getFiles($dir) { $files = []; if (!is_dir($dir) || !file_exists($dir)) { return $files; } $directory = new \RecursiveDirectoryIterator($dir); $iterator = new \RecursiveIteratorIterator($directory); foreach ($iterator as $info) { $file = $info->getFilename(); if ($file == '.' || $file == '..') { continue; } $files[] = $info->getPathname(); } return $files; } public static function curl($url, $data, $method = 'post', $port = 9510) { $url = $method == 'post' ? $url : $url . '?' . http_build_query($data); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_PORT, $port); curl_setopt($curl, CURLOPT_USERAGENT, LOG_AGENT); if ($method == 'post') { curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } $response = curl_exec($curl); if (curl_errno($curl)) { echo 'Curl error: ' . curl_error($curl); } curl_close($curl); } }
php
MIT
4f60a6f8185983c956d7c26f16c5819a58b96a71
2026-01-05T05:05:27.542964Z
false
luxixing/swoole-task
https://github.com/luxixing/swoole-task/blob/4f60a6f8185983c956d7c26f16c5819a58b96a71/src/Base/App.php
src/Base/App.php
<?php /** * 应用入口App,框架的唯一入口 */ namespace Ping\SwooleTask\Base; class App { /** * 当前请求协议 key="fromId#taskId" value="ctrl.action" * * @var array */ private $_op = []; /** * 当前请求ctrl,key="fromId#taskId" value=CtrlClass(包括namespace) * * @var array */ private $_ctrl = []; /** * 当前请求action, key="fromId#taskId" value=actionName * * @var array */ private $_action = []; /** * 当前请求 get+post数据 key="fromId#taskId" * * @var array */ private $_request = []; /** * 当前请求是否debug模式 * * @var array */ private $_debug = []; /** * 返回App的单例实例,swoole-httpServer启动加载在内存不再改变 * * @var null */ private static $_app = null; /** * 读取Conf/http_server中的env配置的值 * 当前环境 dev,test,product * * @var string */ public static $env; /** * swoole-http-server * * @var object */ public static $server; /** * 常驻内存 * app 默认配置&加载config目录配置 * * @var array */ public static $conf = [ //config 目录配置加载(Conf/env/*.php) 'conf' => [], //公共默认配置 Conf/app.php 'app' => [], ]; //单例需要 private function __construct() { } //单例需要 private function __clone() { } /** * TODO 继续完善优化规则 * 简单路由规则实现 * * @param $request * @param $id * * @return mixed 错误返回代码 成功返回op */ private function route($request, $id) { $this->_request[$id] = []; if (!empty($request->get)) { $this->_request[$id] = array_merge($this->_request[$id], $request->get); } if (!empty($request->post)) { $this->_request[$id] = array_merge($this->_request[$id], $request->post); } $route = ['index', 'index']; if (!empty($request->server['path_info'])) { $route = explode('/', trim($request->server['path_info'], '/')); } if (!empty($this->_request[$id]['op'])) { //请求显式的指定路由:op=ctrl.action $route = explode('.', $this->_request[$id]['op']); } if (count($route) < 2) { return 1; } $this->_op[$id] = implode('.', $route); $ctrl = '\\' . self::$conf['app']['ns_pre'] . '\\' . self::$conf['app']['ns_ctrl'] . '\\' . ucfirst($route[0]) . 'Ctrl'; $action = lcfirst($route[1]) . 'Action'; if (!class_exists($ctrl) || !method_exists($ctrl, $action)) { return 2; } $this->_ctrl[$id] = $ctrl; $this->_action[$id] = $action; //设置请求调试模式 $debug = false; if (!empty($this->_request[$id]['debug'])) { //请求中携带 debug 标识,优先级最高 $debug = $this->_request[$id]['debug']; } $debug = ($debug === true || $debug === 'yes' || $debug === 'true' || $debug === 1 || $debug === '1') ? true : false; $this->_debug[$id] = $debug; return $this->_op[$id]; } /** * app conf 获取 首先加载内置配置 * * @param string $key * $param mixed $default * * @return array */ public static function getConfig($key = '', $default = '') { if ($key === '') { return self::$conf; } $value = []; $keyList = explode('.', $key); $firstKey = array_shift($keyList); if (isset(self::$conf[$firstKey])) { $value = self::$conf[$firstKey]; } else { if (!isset(self::$conf['conf'][$firstKey])) { return $value; } $value = self::$conf['conf'][$firstKey]; } //递归深度最大5层 $i = 0; do { if ($i > 5) { break; } $k = array_shift($keyList); if (!isset($value[$k])) { $value = empty($default) ? [] : $default; return $value; } $value = $value[$k]; $i++; } while ($keyList); return $value; } /** * 获取一个app的实例 * * @param $server * * @return App|null */ public static function getApp($server = null) { if (self::$_app) { return self::$_app; } //swoole-httpServer self::$server = $server; //swoole-app运行环境 dev|test|prod self::$env = self::$server->setting['app_env']; /** * 配置加载 */ //默认app配置加载 $configDir = self::$server->setting['app_dir'] . DS . SW_APP_CONF; self::$conf['app'] = include $configDir . DS . 'app.php'; self::$conf['app']['conf'] = SW_APP_CONF; self::$conf['app']['runtime'] = SW_APP_RUNTIME; //根据环境加载不同的配置 $confFiles = []; if (file_exists($configDir . DS . self::$env)) { $confFiles = Helper::getFiles($configDir); } foreach ($confFiles as $inc) { $file = pathinfo($inc); self::$conf['conf'][$file['filename']] = include $inc; } //vendor目录加载,支持composer $vendorFile = self::$server->setting['app_dir'] . DS . 'vendor' . DS . 'autoload.php'; if (file_exists($vendorFile)) { include $vendorFile; } //自动加载机制实现,遵循psr4 spl_autoload_register(function ($className) { $path = array_filter(explode('\\', $className)); $className = array_pop($path); $realPath = str_replace(self::$conf['app']['ns_pre'], '', implode(DS, $path)); include self::$server->setting['app_dir'] . $realPath . DS . $className . '.php'; return true; }); self::$_app = new self(); return self::$_app; } /** * 获取当前请求调试模式的值 * * @param $id * * @return bool */ public function getDebug($id) { return $this->_debug[$id]; } public function logger($msg, $type = null) { if (empty($msg)) { return false; } //参数处理 $type = $type ? $type : 'debug'; if (!is_string($msg)) { $msg = var_export($msg, true); } $msg = '[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL; $maxSize = 2097152;//2M list($y, $m, $d) = explode('-', date('Y-m-d')); $dir = self::$server->setting['app_dir'] . DS . self::$conf['app']['runtime'] . DS . 'log' . DS . $y . $m; $file = "{$dir}/{$type}-{$d}.log"; if (!file_exists($dir)) { mkdir($dir, 0777); } if (file_exists($file) && filesize($file) >= $maxSize) { $a = pathinfo($file); $bak = $a['dirname'] . DIRECTORY_SEPARATOR . $a['filename'] . '-bak.' . $a['extension']; if (!rename($file, $bak)) { echo "rename file:{$file} to {$bak} failed"; } } error_log($msg, 3, $file); } public function debug($msg) { $this->logger($msg, 'debug'); } public function error($msg) { $this->logger($msg, 'error'); } public function warn($msg) { $this->logger($msg, 'warn'); } public function info($msg) { $this->logger($msg, 'info'); } public function sql($msg) { $this->logger($msg, 'sql'); } public function op($msg) { $this->logger($msg, 'op'); } /** * 执行一个请求 * * @param $request * @param $taskId * @param $fromId * * @return mixed */ public function run($request, $taskId, $fromId) { //id由 workid#taskId组成,能唯一标识一个请求的来源 $id = "{$fromId}#{$taskId}"; //请求运行开始时间 $runStart = time(); //请求运行开始内存 $mem = memory_get_usage(); //TODO before route $op = $this->route($request, $id); if (is_int($op)) { if ($op == 1) { $error = '缺少路由'; $this->error($error); return false; } if ($op == 2) { $error = "路由解析失败:{$this->_op[$id]}"; $this->error($error); return false; } } //TODO after route try { $ctrl = new $this->_ctrl[$id]($this->_request[$id], $this->_op[$id], $id); //before action:比如一些ctrl的默认初始化动作,加载dao等 if (method_exists($ctrl, 'init')) { //执行action之前进行init $ctrl->init(); } $res = $ctrl->{$this->_action[$id]}(); //FIXME $res 返回如果不是数组会报错 //after action if (method_exists($ctrl, 'done')) { //执行完action之后要做的事情 $ctrl->done(); } //请求运行时间和内存记录 $runSpend = time() - $runStart;//请求花费时间 $info = "op:{$op}, spend: {$runSpend}s, memory:" . Helper::convertSize(memory_get_usage() - $mem) . ", peak memory:" . Helper::convertSize(memory_get_peak_usage()); $info .= ",date:{$ctrl->date}"; $this->op($info); return $res; } catch (\Exception $e) { $this->error($e->getMessage() . PHP_EOL . $e->getTraceAsString()); } finally { //WARN 请求结束后必须释放相关的数据,避免内存使用的无限增长 unset($this->_op[$id], $this->_ctrl[$id], $this->_action[$id], $this->_request[$id], $this->_debug[$id]); } } }
php
MIT
4f60a6f8185983c956d7c26f16c5819a58b96a71
2026-01-05T05:05:27.542964Z
false
luxixing/swoole-task
https://github.com/luxixing/swoole-task/blob/4f60a6f8185983c956d7c26f16c5819a58b96a71/src/Base/Dao.php
src/Base/Dao.php
<?php namespace Ping\SwooleTask\Base; /** * Class Dao * * @package base */ class Dao { /** * 当前所有连接实例 * * @var \PDO[] */ private static $_pdo = []; /** * 执行日志记录 * * @var array */ private static $_log = []; /** * 是否调试模式 * * @var bool */ protected $debug; /** * 当前连接 * * @var \PDO | null */ protected $pdo; /** * 当前连接名称 * * @var string */ protected $pdoName; public function __construct($debug = false) { //设置debug模式 $this->debug = $debug; } /** * 非dao类调用进行数据库操作,比如helper类 * * @param $name * * @return null|\PDO * @throws \Exception */ public static function getPdoX($name) { $pdo = null; if (!empty(self::$_pdo[$name])) { self::ping(self::$_pdo[$name], $name); $pdo = self::$_pdo[$name]; } else { $pdo = self::$_pdo[$name] = self::getPdoInstance($name); } return $pdo; } /** * 如果mysql go away,连接重启 * * @param \PDO $pdo * @param $name * * @return bool * @throws \Exception */ private static function ping($pdo, $name) { //是否重新连接 0 => ping连接正常, 没有重连 1=>ping 连接超时, 重新连接 $isReconnect = 0; if (!is_object($pdo)) { $isReconnect = 1; self::$_pdo[$name] = self::getPdoInstance($name); App::getApp()->sql("mysql ping:pdo instance [{$name}] is null, reconnect"); } else { try { //warn 此处如果mysql gone away会有一个警告,此处屏蔽继续重连 @$pdo->query('SELECT 1'); } catch (\PDOException $e) { //WARN 非超时连接错误 if ($e->getCode() != 'HY000' || !stristr($e->getMessage(), 'server has gone away')) { throw $e; } //手动重连 self::$_pdo[$name] = self::getPdoInstance($name); $isReconnect = 1; } finally { if ($isReconnect) { APP::getApp()->sql("mysql ping: reconnect {$name}"); } } } return $isReconnect; } /** * 创建数据库连接实例 * * @param $name * * @return \PDO * @throws \Exception */ private static function getPdoInstance($name) { $default = [ //连接成功默认执行的命令 'commands' => [ 'set time_zone="+8:00"', ], 'host' => '127.0.0.1', //unix_socket 'socket' => '', 'username' => 'root', 'password' => '', //默认字符编码 'charset' => 'utf8', 'port' => '3306', 'dbname' => 'mysql', 'options' => [ \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'", \PDO::ATTR_CASE => \PDO::CASE_LOWER, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, // 默认以数组方式提取数据 \PDO::ATTR_ORACLE_NULLS => \PDO::NULL_TO_STRING, // 所有 null 转换为 string ], ]; try { $conf = App::getApp()->getConfig("conf.db.{$name}"); if (empty($conf)) { throw new \Exception("pdo config: conf.db.{$name} not found"); } foreach ($default as $k => $v) { $default[$k] = isset($conf[$k]) ? $conf[$k] : $v; } //PDO错误处理模式强制设定为exception, 连接强制设定为持久连接 $default['options'][\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_EXCEPTION; $default['options'][\PDO::ATTR_PERSISTENT] = false; $default['options'][\PDO::ATTR_TIMEOUT] = 200; $dsn = "mysql:dbname={$default['dbname']}"; if ($default['host']) { $dsn .= ";host={$default['host']};port={$default['port']}"; } else { $dsn .= ";unix_socket={$default['socket']}"; } //create pdo connection $pdo = new \PDO( $dsn, $default['username'], $default['password'], $default['options'] ); if (!empty($default['commands'])) { $commands = is_array($default['commands']) ? $default['commands'] : [$default['commands']]; foreach ($commands as $v) { $pdo->exec($v); } } return $pdo; } catch (\Exception $e) { App::getApp()->error($e->getMessage()); throw $e; } } /** * 获取当前请求执行的所有sql * * @return array */ public static function logs() { return self::$_log; } /** * 设定数据库连接,可执行链式操作 * * @param $name * * @return $this * @throws \Exception */ public function getPdo($name) { $this->pdoName = $name; if (!empty(self::$_pdo[$name])) { $this->ping(self::$_pdo[$name], $name); $this->pdo = self::$_pdo[$name]; } else { $this->pdo = self::$_pdo[$name] = $this->getPdoInstance($name); } return $this; } /** * 执行一条sql * * @param $sql * * @return int|string */ final public function query($sql) { $lastId = 0; try { $this->debug($sql); $sth = $this->pdo->prepare($sql); if ($sth) { $sth->execute(); $lastId = $this->pdo->lastInsertId(); } } catch (\PDOException $e) { $this->getApp()->error($e->getMessage() . PHP_EOL . $this->lastQuery()); } return $lastId; } private function debug($sql, $data = []) { //WARN sql记录最多保持100条,防止内存占用过多 $max = 100; $query = $this->buildQuery($sql, $data); if (count(self::$_log) > $max) { array_shift(self::$_log); } self::$_log[] = $query; if ($this->debug) { $this->getApp()->sql($query); } } /** * prepare语句真实执行的sql * * @param $sql * @param array $data * * @return mixed */ private function buildQuery($sql, $data = []) { $placeholder = []; $params = []; if (empty($data) || !is_array($data)) { return $sql; } foreach ($data as $k => $v) { $placeholder[] = is_numeric($k) ? '/[?]/' : ($k[0] === ':' ? "/{$k}/" : "/:{$k}/"); $params[] = is_numeric($v) ? (int)$v : "'{$v}'"; } return preg_replace($placeholder, $params, $sql, 1, $count); } /** * @return App|null */ public function getApp() { return App::getApp(); } /** * 最近一次sql查询 * * @return mixed */ public function lastQuery() { return end(self::$_log); } /** * 执行一个sql,获取一条结果 * * @param string $sql * @param array $data * * @return array */ final public function getOne($sql, $data = []) { return $this->baseGet($sql, $data, 'fetch'); } /** * @param string $sql 要执行的sql * @param array $data 绑定参数 * @param string $method [fetch|fetchAll|fetchColumn|fetchObject] * @param mixed $pdo \PDO|null * * @return array * @throws \Exception */ private function baseGet($sql, $data, $method, $pdo = null) { $ret = []; try { $this->debug($sql, $data); $pdo = $pdo instanceof \PDO ? $pdo : $this->pdo; $sth = $pdo->prepare($sql); if ($sth) { $sth->execute($data); if ($rows = $sth->$method(\PDO::FETCH_ASSOC)) { $ret = $rows; } } } catch (\PDOException $e) { $this->getApp()->error($e->getMessage() . PHP_EOL . $this->lastQuery()); } return $ret; } /** * 执行一个sql,获取所有结果 * * @param string $sql * @param array $data * * @return array */ final public function getAll($sql, $data = []) { return $this->baseGet($sql, $data, 'fetchAll'); } /** * 使用生成器进行数据的批量查询,低内存占用 * * @param string $pdoName 数据库连接配置名称 * @param string $sql 欲执行sql * @param array $data 绑定参数 * @param int $limit 限制查询数量 * * @return \Generator * @throws \Exception */ final public function getIterator($pdoName, $sql, $data = [], $limit = 500) { //pdo设置 $pdo = null; if (isset(self::$_pdo[$pdoName])) { $this->ping(self::$_pdo[$pdoName], $pdoName); $pdo = self::$_pdo[$pdoName]; } else { $pdo = $this->getPdoInstance($pdoName); } //迭代查询 $offset = 0; do { //ping 防止超时 if ($this->ping($pdo, $pdoName)) { $pdo = self::$_pdo[$pdoName]; } $s = "{$sql} limit {$offset}, {$limit}"; $ret = $this->baseGet($s, $data, 'fetchAll', $pdo); if (empty($ret)) { break; } foreach ($ret as $v) { yield $v; } $offset += $limit; } while (true); } /** * 预初始化一个pdo的prepare语句,返回准备好的PDOStatement环境,用于批量执行相同查询 * * @param string $pdoName 数据库连接名称(db.php db数组的key名称) * @param string $sql 欲查询的sql * @param string $fetchMode 数据获取模式 [fetch|fetchAll|fetchColumn|fetchObject] 对应statement的方法 * * @return \Closure * @throws \Exception */ final public function getBatchSth($pdoName, $sql, $fetchMode = 'fetch') { $pdo = null; $sth = null; try { if (isset(self::$_pdo[$pdoName])) { //WARN 注意,顺序非常重要 $this->ping(self::$_pdo[$pdoName], $pdoName); $pdo = self::$_pdo[$pdoName]; } else { $pdo = $this->getPdoInstance($pdoName); } $sth = $pdo->prepare($sql); } catch (\PDOException $e) { $this->getApp()->error($e->getMessage()); } $batch = function ($d) use ($sth, $fetchMode, $sql, $pdo, $pdoName) { // WARN 重连之后因为pdo对象变化,需要重新预处理sql if ($this->ping($pdo, $pdoName)) { $pdo = self::$_pdo[$pdoName]; $sth = $pdo->prepare($sql); } try { $this->debug($sql, $d); $sth->execute($d); $ret = $sth->$fetchMode(); return $ret; } catch (\PDOException $e) { $this->getApp()->error($e->getMessage() . PHP_EOL . $this->lastQuery()); } return null; }; return $batch; } /** * 向表里插入一条数据 * * @param string $table * @param array $data * * @return int|string */ final public function add($table, $data, $ignore = false) { $lastId = 0; if (empty($data)) { return $lastId; } $keys = array_keys($data); $cols = implode(',', $keys); $params = ':' . implode(',:', $keys); $sql = ''; if ($ignore) { $sql = <<<SQL insert IGNORE into {$table} ({$cols}) values ($params) SQL; } else { $sql = <<<SQL insert into {$table} ({$cols}) values ($params) SQL; } try { $this->debug($sql, $data); $sth = $this->pdo->prepare($sql); $sth->execute($data); //WARN 当引擎为innodb 则不会自动提交,需要手动提交 //$this->pdo->query('commit'); $lastId = $this->pdo->lastInsertId(); } catch (\PDOException $e) { $this->getApp()->error($e->getMessage() . PHP_EOL . $this->lastQuery()); } return $lastId; } /** * 生成一个prepare的Statement语句,用于批量插入 * * @param string $pdoName pdo连接名称 * @param string $table 表名称 * @param array $bindCols 插入数据字段数组 * * @return \Closure * @throws \Exception */ final public function addBatchSth($pdoName, $table, $bindCols) { $cols = implode(',', $bindCols); $params = ':' . implode(',:', $bindCols); $sql = <<<SQL insert into {$table} ({$cols}) values ($params) SQL; $pdo = null; $sth = null; try { if (isset(self::$_pdo[$pdoName])) { $this->ping(self::$_pdo[$pdoName], $pdoName); $pdo = self::$_pdo[$pdoName]; } else { $pdo = $this->getPdoInstance($pdoName); } $sth = $pdo->prepare($sql); } catch (\PDOException $e) { $this->getApp()->error($e->getMessage()); } //匿名函数用于sql prepare之后的批量操作 $batch = function ($d) use ($sth, $bindCols, $pdo, $sql, $pdoName) { if ($this->ping($pdo, $pdoName)) { $pdo = self::$_pdo[$pdoName]; $sth = $pdo->prepare($sql); } try { $bindParam = []; foreach ($bindCols as $v) { $bindParam[":{$v}"] = $d[$v]; } $this->debug($sql, $bindParam); $sth->execute($bindParam); return $pdo->lastInsertId(); } catch (\PDOException $e) { $this->getApp()->error($e->getMessage() . PHP_EOL . $this->lastQuery()); } }; return $batch; } final public function addUpdate($table, $data) { //TODO } /** * 更新指定表数据 * * @param string $table * @param array $data 绑定参数 * @param string $where * * @return int */ final public function update($table, $data, $where) { $rowsCount = 0; $keys = array_keys($data); $cols = []; foreach ($keys as $v) { $cols[] = "{$v}=:$v"; } $cols = implode(', ', $cols); $sql = <<<SQL update {$table} set {$cols} where {$where} SQL; try { $this->debug($sql, $data); $sth = $this->pdo->prepare($sql); $sth->execute($data); $rowsCount = $sth->rowCount(); } catch (\PDOException $e) { $this->getApp()->error($e->getMessage() . PHP_EOL . $this->lastQuery()); } return $rowsCount; } /** * 删除指定表数据,返回影响行数 * * @param string $table 表名称 * @param string $where where 条件 * * @return int */ final public function del($table, $where) { $rowsCount = 0; $sql = <<<SQL delete from {$table} where $where SQL; try { //优先写入要执行的sql $this->debug($sql); //sth 返回值取决于pdo连接设置的errorMode,如果设置为exception,则抛出异常 $sth = $this->pdo->prepare($sql); $sth->execute(); $rowsCount = $sth->rowCount(); } catch (\PDOException $e) { $this->getApp()->error($e->getMessage() . PHP_EOL . $this->lastQuery()); } return $rowsCount; } }
php
MIT
4f60a6f8185983c956d7c26f16c5819a58b96a71
2026-01-05T05:05:27.542964Z
false
luxixing/swoole-task
https://github.com/luxixing/swoole-task/blob/4f60a6f8185983c956d7c26f16c5819a58b96a71/src/Base/Ctrl.php
src/Base/Ctrl.php
<?php namespace Ping\SwooleTask\Base; /** * Class BaseCtrl */ class Ctrl { const ERRNO_SUCCESS = 0;//成功 const ERRNO_PARAM = 1;//参数错误 const ERROR_SUCCESS = 'OK'; const ERROR_PARAM = 'Params invalid'; /** * dao 单例 * * @var array */ private $_dao = [ ]; /** * 返回请求秃顶模式 * * @var array */ protected $ret = [ //请求协议 'op' => '', //错误代码 'errno' => self::ERRNO_SUCCESS, //错误信息 'error' => self::ERROR_SUCCESS, //任务结束设置的回调函数 'finish' => '', //请求参数 'params' => [], //返回结果 可提供给回调函数使用 'data' => [], ]; /** * 请求唯一标识符 fromId#taskId * * @var string */ public $id = ''; /** * 当前请求 * * @var string */ public $op = ''; /** * 数据抓取日期 * * @var date */ public $date = ''; /** * 请求参数 * * @var array */ public $params = []; public function __construct($params, $op, $id) { $this->id = $id; $this->op = $this->ret['op'] = $op; $this->params = $params; $this->date = isset($params['dt']) ? date('Y-m-d', strtotime("-1 day {$params['dt']}")) : date('Y-m-d', strtotime('-1 day')); $this->ret['params'] = $this->params; } public function __destruct() { //TODO 资源释放 } /** * 在ctrl 里面快速访问config * * @param $key * * @return mixed */ public function getConfig($key) { return App::getConfig($key); } /** * 获取dao * * @param $dao * * @return bool */ public function getDao($dao) { if (isset($this->_dao[$dao])) { return $this->_dao[$dao]; } $class = App::$conf['app']['ns_pre'] . '\\' . App::$conf['app']['ns_dao'] . '\\' . $dao; if (!class_exists($class)) { return false; } $obj = new $class($this->isDebug()); $this->_dao[$class] = $obj; return $obj; } public function getApp() { return App::getApp(); } /** * @return bool true|false true 表示当前请求为debug模式 */ public function isDebug() { return $this->getApp()->getDebug($this->id); } }
php
MIT
4f60a6f8185983c956d7c26f16c5819a58b96a71
2026-01-05T05:05:27.542964Z
false
luxixing/swoole-task
https://github.com/luxixing/swoole-task/blob/4f60a6f8185983c956d7c26f16c5819a58b96a71/bin/function.php
bin/function.php
<?php /** * 首次启动swoole-task 服务时初始化应用 * * @param string swooleTaskAppName swoole-task 业务目录名称 * @param array conf 覆盖默认配置可传递相关参数 * * @throws Exception */ function swTaskInit($appDir) { /** * @var array 默认配置 */ $conf = [ 'app' => [ 'ns_pre' => 'SwTask',//swoole-task 应用默认 namespace 前缀 'ns_ctrl' => 'Ctrl',//Ctrl 代码目录,命名空间 SwTask\Ctrl\FooCtrl 'ns_dao' => 'Dao',//Dao 代码目录,命名空间 SwTask\Dao\FooDao 'ns_helper' => 'Helper',//Helper 代码目录,命名空间 SwTask\Helper\FooHelper ], 'http_server' => [ 'tz' => 'Asia/Shanghai',//时区设定,数据统计时区非常重要 'host' => '127.0.0.1', //默认监听ip 'port' => '9523', //默认监听端口 'app_env' => 'dev', //运行环境 dev|test|prod, 基于运行环境加载不同配置 'ps_name' => 'swTask', //默认swoole 进程名称 'daemonize' => 0, //是否守护进程 1=>守护进程| 0 => 非守护进程 'worker_num' => 2, //worker进程 cpu核数 1-4倍,一般选择和cpu核数一致 'task_worker_num' => 2, //task进程,根据实际情况配置 'task_max_request' => 10000, //当task进程处理请求超过此值则关闭task进程,保障进程无内存泄露 'open_tcp_nodelay' => 1, //关闭Nagle算法,提高HTTP服务器响应速度 ], ]; /** * @var string ctrl 默认模板 */ $ctrlTpl = <<<PHP <?php /** * swoole-task ctrl文件模板,可参考此文件扩充自己的实际功能 */ namespace {$conf['app']['ns_pre']}\\{$conf['app']['ns_ctrl']}; use Ping\SwooleTask\Base\Ctrl as BaseCtrl; class TplCtrl extends BaseCtrl { /** * @var Dao \$testDao 连接数据库操作的dao实例,调用ctrl里面的getDao 方法获取单例实体 */ //private \$testDao; public function init() { //\$this->testDao = \$this->getDao('TestDao'); } public function helloAction() { echo 'hello world' . PHP_EOL; var_dump(\$this->params); } } PHP; /** * @var string dao 默认模板 */ $daoTpl = <<<PHP <?php /** * swoole-task dao文件模板,可参考此文件扩充自己的实际功能 */ namespace {$conf['app']['ns_pre']}\\{$conf['app']['ns_dao']}; use Ping\SwooleTask\Base\Dao as BaseDao; class TplDao extends BaseDao { /** * @see Ping\SwooleTask\Base\Dao */ //使用Ping\SwooleTask\Base\Dao 提供的数据库操作接口进行数据查询处理操作 } PHP; //创建swoole-task 实际业务所需的目录 try { if (!mkdir($appDir)) { throw new Exception("创建swoole-task 应用目录失败,请检查是否权限不足:" . $appDir); } //ctrl目录创建 mkdir($appDir . DS . $conf['app']['ns_ctrl']); //dao 目录创建 mkdir($appDir . DS . $conf['app']['ns_dao']); //helper 目录创建 mkdir($appDir . DS . $conf['app']['ns_helper']); //conf 目录创建 mkdir($appDir . DS . SW_APP_CONF); //根据http_server的app_env配置项的值,根据环境加载配置内容,支持dev,test,prod三个值,如有自定义值,自己创建目录 foreach (['dev', 'test', 'prod'] as $v) { mkdir($appDir . DS . SW_APP_CONF . DS . $v); } //runtime 目录创建 $runtimePath = $appDir . DS . SW_APP_RUNTIME; mkdir($runtimePath, 0777); //runtime-log 目录创建 mkdir($runtimePath . DS . 'log', 0777); //模板文件写入目录 $ctrlFile = $appDir . DS . $conf['app']['ns_ctrl'] . DS . 'TplCtrl.php'; if (!file_put_contents($ctrlFile, $ctrlTpl)) { throw new Exception("创建swoole-task Ctrl 模板文件失败,请检查是否权限不足:" . $ctrlFile); } $daoFile = $appDir . DS . $conf['app']['ns_dao'] . DS . 'TplDao.php'; if (!file_put_contents($daoFile, $daoTpl)) { throw new Exception("创建swoole-task Dao 模板文件失败,请检查是否权限不足:" . $daoFile); } //配置文件初始化写入 $httpServerConf = $appDir . DS . SW_APP_CONF . DS . 'http_server.php'; if (!file_put_contents($httpServerConf, "<?php\nreturn \$http_server = " . var_export($conf['http_server'], 1) . ';') ) { throw new Exception("创建swoole-task 配置文件 http_server 失败,请检查是否权限不足:" . $httpServerConf); } $appConf = $appDir . DS . SW_APP_CONF . DS . 'app.php'; if (!file_put_contents($appConf, "<?php\nreturn \$app = " . var_export($conf['app'], 1) . ';')) { throw new Exception("创建swoole-task 委派文件 app 失败,请检查是否权限不足:" . $appConf); } } catch (Exception $e) { throw $e; } } function swTaskPort($port) { $ret = []; $cmd = "lsof -i :{$port}|awk '$1 != \"COMMAND\" {print $1, $2, $9}'"; exec($cmd, $out); if ($out) { foreach ($out as $v) { $a = explode(' ', $v); list($ip, $p) = explode(':', $a[2]); $ret[$a[1]] = [ 'cmd' => $a[0], 'ip' => $ip, 'port' => $p, ]; } } return $ret; } function swTaskStart($conf) { echo "正在启动 swoole-task 服务" . PHP_EOL; if (!is_writable(dirname($conf['pid_file']))) { exit("swoole-task-pid文件需要目录的写入权限:" . dirname($conf['pid_file']) . PHP_EOL); } if (file_exists($conf['pid_file'])) { $pid = explode("\n", file_get_contents($conf['pid_file'])); $cmd = "ps ax | awk '{ print $1 }' | grep -e \"^{$pid[0]}$\""; exec($cmd, $out); if (!empty($out)) { exit("swoole-task pid文件 " . $conf['pid_file'] . " 存在,swoole-task 服务器已经启动,进程pid为:{$pid[0]}" . PHP_EOL); } else { echo "警告:swoole-task pid文件 " . $conf['pid_file'] . " 存在,可能swoole-task服务上次异常退出(非守护模式ctrl+c终止造成是最大可能)" . PHP_EOL; unlink($conf['pid_file']); } } $bind = swTaskPort($conf['port']); if ($bind) { foreach ($bind as $k => $v) { if ($v['ip'] == '*' || $v['ip'] == $conf['host']) { exit("端口已经被占用 {$conf['host']}:{$conf['port']}, 占用端口进程ID {$k}" . PHP_EOL); } } } date_default_timezone_set($conf['tz']); $server = new Ping\SwooleTask\HttpServer($conf); $server->run(); //确保服务器启动后swoole-task-pid文件必须生成 /*if (!empty(portBind($port)) && !file_exists(SWOOLE_TASK_PID_PATH)) { exit("swoole-task pid文件生成失败( " . SWOOLE_TASK_PID_PATH . ") ,请手动关闭当前启动的swoole-task服务检查原因" . PHP_EOL); }*/ exit("启动 swoole-task 服务成功" . PHP_EOL); } function swTaskStop($conf, $isRestart = false) { echo "正在停止 swoole-task 服务" . PHP_EOL; if (!file_exists($conf['pid_file'])) { exit('swoole-task-pid文件:' . $conf['pid_file'] . '不存在' . PHP_EOL); } $pid = explode("\n", file_get_contents($conf['pid_file'])); $bind = swTaskPort($conf['port']); if (empty($bind) || !isset($bind[$pid[0]])) { exit("指定端口占用进程不存在 port:{$conf['port']}, pid:{$pid[0]}" . PHP_EOL); } $cmd = "kill {$pid[0]}"; exec($cmd); do { $out = []; $c = "ps ax | awk '{ print $1 }' | grep -e \"^{$pid[0]}$\""; exec($c, $out); if (empty($out)) { break; } } while (true); //确保停止服务后swoole-task-pid文件被删除 if (file_exists($conf['pid_file'])) { unlink($conf['pid_file']); } $msg = "执行命令 {$cmd} 成功,端口 {$conf['host']}:{$conf['port']} 进程结束" . PHP_EOL; if ($isRestart) { echo $msg; } else { exit($msg); } } function swTaskStatus($conf) { echo "swoole-task {$conf['host']}:{$conf['port']} 运行状态" . PHP_EOL; $cmd = "curl -s '{$conf['host']}:{$conf['port']}?cmd=status'"; exec($cmd, $out); if (empty($out)) { exit("{$conf['host']}:{$conf['port']} swoole-task服务不存在或者已经停止" . PHP_EOL); } foreach ($out as $v) { $a = json_decode($v); foreach ($a as $k1 => $v1) { echo "$k1:\t$v1" . PHP_EOL; } } exit(); } //WARN macOS 下因为不支持进程修改名称,此方法使用有问题 function swTaskList($conf) { echo "本机运行的swoole-task服务进程" . PHP_EOL; $cmd = "ps aux|grep " . $conf['ps_name'] . "|grep -v grep|awk '{print $1, $2, $6, $8, $9, $11}'"; exec($cmd, $out); if (empty($out)) { exit("没有发现正在运行的swoole-task服务" . PHP_EOL); } echo "USER PID RSS(kb) STAT START COMMAND" . PHP_EOL; foreach ($out as $v) { echo $v . PHP_EOL; } exit(); }
php
MIT
4f60a6f8185983c956d7c26f16c5819a58b96a71
2026-01-05T05:05:27.542964Z
false
luxixing/swoole-task
https://github.com/luxixing/swoole-task/blob/4f60a6f8185983c956d7c26f16c5819a58b96a71/bin/swoole-task.php
bin/swoole-task.php
#!/bin/env php <?php /** * 设置错误报告模式 */ error_reporting(E_ALL); /** * 检查exec 函数是否启用 */ if (!function_exists('exec')) { exit('exec function is disabled' . PHP_EOL); } /** * 检查命令 lsof 命令是否存在 */ exec("whereis lsof", $out); if ($out[0] == 'lsof:') { exit('lsof is not found' . PHP_EOL); } define('DS', DIRECTORY_SEPARATOR); /** * @var string swoole-task源码根目录 */ define('SW_SRC_ROOT', realpath(__DIR__ . DS . '..')); /** * @var string swoole-task 业务应用根目录:即 vendor_path的父目录 */ define("SW_APP_ROOT", realpath(SW_SRC_ROOT . DS . '..' . DS . '..' . DS . '..')); define('SW_APP_CONF', 'Conf');//swoole-task业务配置目录,不允许修改 define('SW_APP_RUNTIME', 'Runtime');//swoole-task业务数据访问目录,不允许修改 //加载http-server include SW_SRC_ROOT . DS . 'src' . DS . 'HttpServer.php'; //加载进程管理函数 include __DIR__ . DS . 'function.php'; /** * @var array swoole-http_server支持的进程管理命令 */ $cmds = [ 'start', 'stop', 'restart', 'status', 'list', ]; /** * @var array 命令行参数,FIXME: getopt 函数的长参数 格式 requried:, optionnal::,novalue 三种格式,可选参数这个有问题 */ $longopt = [ 'help',//显示帮助文档 'nodaemon',//以守护进程模式运行,不指定读取配置文件 'app:',//指定swoole-task业务实际的目录名称(即ctrl,dao,helper的父目录),如果不指定,默认为swoole-task 'host:',//监听主机ip, 0.0.0.0 表示所有ip 'port:',//监听端口 ]; $opts = getopt('', $longopt); if (isset($opts['help']) || $argc < 2) { echo <<<HELP 用法:php swoole-task.php 选项[help|app|daemon|host|port] 命令[start|stop|restart|status|list] 管理swoole-task服务,确保系统 lsof 命令有效 如果不指定监听host或者port,使用配置参数 参数说明 --help 显示本帮助说明 --app swoole-task业务实际处理目录名称,即ctrl,dao,helper的父目录名称,默认为swoole-task,和vendor_path在同一目录下 --nodaemon 指定此参数,以非守护进程模式运行,不指定则读取配置文件值 --host 指定监听ip,例如 php swoole.php -h 127.0.0.1 --port 指定监听端口port, 例如 php swoole.php --host 127.0.0.1 --port 9520 启动swoole-task 如果不指定 host和port,读取http-server中的配置文件 关闭swoole-task 必须指定port,没有指定host,关闭的监听端口是 *:port, 指定了host,关闭 host:port端口 重启swoole-task 必须指定端口 获取swoole-task 状态,必须指定port(不指定host默认127.0.0.1), tasking_num是正在处理的任务数量(0表示没有待处理任务) HELP; exit; } /** * 参数检查 */ foreach ($opts as $k => $v) { if ($k == "app") { if (empty($v)) { exit("参数 --app 必须指定值,例如swoole-task,此参数用于指定初始化时swoole-task处理业务的根目录\n"); } } if ($k == 'host') { if (empty($v)) { exit("参数 --host 必须指定值\n"); } } if ($k == 'port') { if (empty($v)) { exit("参数--port 必须指定值\n"); } } } //命令检查 $cmd = $argv[$argc - 1]; if (!in_array($cmd, $cmds)) { exit("输入命令有误 : {$cmd}, 请查看帮助文档\n"); } $app = 'sw-app'; if (!empty($opts['app'])) { $app = $opts['app']; } $appDir = SW_APP_ROOT . DS . $app; if (!file_exists($appDir)) { swTaskInit($appDir); } //读取swoole-httpSerer配置 $httpConf = include $appDir . DS . SW_APP_CONF . DS . 'http_server.php'; /** * swoole_task业务实际目录 */ $httpConf['app_dir'] = $appDir; /** * @var string 监听主机ip, 0.0.0.0 表示监听所有本机ip, 如果命令行提供 ip 则覆盖配置项 */ if (!empty($opts['host'])) { if (!filter_var($host, FILTER_VALIDATE_IP)) { exit("输入host有误:{$host}"); } $httpConf['host'] = $opts['host']; } /** * @var int 监听端口 */ if (!empty($opts['port'])) { $port = (int)$opts['port']; if ($port <= 0) { exit("输入port有误:{$port}"); } $httpConf['port'] = $port; } //确定port之后则进程文件确定,可在conf中加入 $httpConf['pid_file'] = $httpConf['app_dir'] . DS . SW_APP_RUNTIME . DS . 'sw-' . $httpConf['port'] . '.pid'; /** * @var bool swoole-httpServer运行模式,参数nodaemon 以非守护进程模式运行,否则以配置文件设置值为默认值 */ if (isset($opts['nodaemon'])) { $httpConf['daemonize'] = 0; } //启动 if ($cmd == 'start') { swTaskStart($httpConf); } //停止 if ($cmd == 'stop') { swTaskStop($httpConf); } //重启 if ($cmd == 'restart') { echo "重启swoole-task服务" . PHP_EOL; swTaskStop($httpConf, true); swTaskStart($httpConf); } //状态 if ($cmd == 'status') { swTaskStatus($httpConf); } //列表 WARN macOS 下因为进程名称修改问题,此方法使用有问题 if ($cmd == 'list') { swTaskList($httpConf); }
php
MIT
4f60a6f8185983c956d7c26f16c5819a58b96a71
2026-01-05T05:05:27.542964Z
false
php-enqueue/null
https://github.com/php-enqueue/null/blob/25d9df714fcf607682e58c67bb55791fb60289c1/NullTopic.php
NullTopic.php
<?php namespace Enqueue\Null; use Interop\Queue\Topic; class NullTopic implements Topic { /** * @var string */ private $name; public function __construct(string $name) { $this->name = $name; } public function getTopicName(): string { return $this->name; } }
php
MIT
25d9df714fcf607682e58c67bb55791fb60289c1
2026-01-05T05:05:31.847668Z
false
php-enqueue/null
https://github.com/php-enqueue/null/blob/25d9df714fcf607682e58c67bb55791fb60289c1/NullConsumer.php
NullConsumer.php
<?php declare(strict_types=1); namespace Enqueue\Null; use Interop\Queue\Consumer; use Interop\Queue\Destination; use Interop\Queue\Message; use Interop\Queue\Queue; class NullConsumer implements Consumer { /** * @var Destination */ private $queue; public function __construct(Destination $queue) { $this->queue = $queue; } public function getQueue(): Queue { return $this->queue; } /** * @return NullMessage */ public function receive(int $timeout = 0): ?Message { return null; } /** * @return NullMessage */ public function receiveNoWait(): ?Message { return null; } public function acknowledge(Message $message): void { } public function reject(Message $message, bool $requeue = false): void { } }
php
MIT
25d9df714fcf607682e58c67bb55791fb60289c1
2026-01-05T05:05:31.847668Z
false
php-enqueue/null
https://github.com/php-enqueue/null/blob/25d9df714fcf607682e58c67bb55791fb60289c1/NullSubscriptionConsumer.php
NullSubscriptionConsumer.php
<?php declare(strict_types=1); namespace Enqueue\Null; use Interop\Queue\Consumer; use Interop\Queue\SubscriptionConsumer; class NullSubscriptionConsumer implements SubscriptionConsumer { public function consume(int $timeout = 0): void { } public function subscribe(Consumer $consumer, callable $callback): void { } public function unsubscribe(Consumer $consumer): void { } public function unsubscribeAll(): void { } }
php
MIT
25d9df714fcf607682e58c67bb55791fb60289c1
2026-01-05T05:05:31.847668Z
false