public function StateItemTest::testField in State Machine 8
@dataProvider providerTestField
File
- tests/
src/ Kernel/ StateItemTest.php, line 50
Class
- StateItemTest
- @coversDefaultClass \Drupal\state_machine\Plugin\Field\FieldType\StateItem @group state_machine
Namespace
Drupal\Tests\state_machine\KernelCode
public function testField($initial_state, $allowed_transitions, $invalid_new_state, $valid_transition, $expected_new_state) {
$entity = EntityTestWithBundle::create([
'type' => 'second',
'field_state' => $initial_state,
]);
$this
->assertEquals($initial_state, $entity
->get('field_state')->value);
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $entity
->get('field_state')
->first();
// Confirm that the transitions are correct.
$transitions = $state_item
->getTransitions();
$this
->assertCount(count($allowed_transitions), $transitions);
$this
->assertEquals($allowed_transitions, array_keys($transitions));
if (count($allowed_transitions) > 0) {
foreach ($allowed_transitions as $transition_id) {
$this
->assertTrue($state_item
->isTransitionAllowed($transition_id));
}
}
$this
->assertFalse($state_item
->isTransitionAllowed('foo'));
// Confirm that invalid states are recognized.
if ($invalid_new_state) {
$state_item->value = $invalid_new_state;
$this
->assertEquals($initial_state, $state_item
->getOriginalId());
$this
->assertEquals($invalid_new_state, $state_item
->getId());
$this
->assertFalse($state_item
->isValid());
}
// Revert to the initial state because the valid transaction could be
// invalid from the invalid_new_state.
$state_item->value = $initial_state;
// Retrieve all workflow transitions.
$workflow = $state_item
->getWorkflow();
$all_transitions = $workflow
->getTransitions();
// Pick a random invalid transition and assert it throws an Exception.
$invalid_transitions = array_diff_key($all_transitions, $allowed_transitions);
if ($invalid_transitions) {
$random_key = array_rand($invalid_transitions);
$this
->expectException(\InvalidArgumentException::class);
$state_item
->applyTransition($invalid_transitions[$random_key]);
// Also try applying by ID.
$this
->expectException(\InvalidArgumentException::class);
$state_item
->applyTransitionById($random_key);
}
$state_item
->applyTransitionById($valid_transition);
$this
->assertEquals($initial_state, $state_item
->getOriginalId());
$this
->assertEquals($expected_new_state, $state_item
->getId());
$this
->assertTrue($state_item
->isValid());
}