AfterSaveBehaviorTest.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace Tools\Test\TestCase\Model\Behavior;
  3. use Shim\TestSuite\TestCase;
  4. class AfterSaveBehaviorTest extends TestCase {
  5. /**
  6. * @var array
  7. */
  8. protected array $fixtures = [
  9. 'plugin.Tools.Articles',
  10. ];
  11. /**
  12. * @var \Tools\Model\Table\Table|\Tools\Model\Behavior\AfterSaveBehavior
  13. */
  14. protected $table;
  15. /**
  16. * @return void
  17. */
  18. public function setUp(): void {
  19. parent::setUp();
  20. $this->table = $this->getTableLocator()->get('Articles');
  21. $this->table->addBehavior('Tools.AfterSave');
  22. }
  23. /**
  24. * @return void
  25. */
  26. public function testSaveBasic() {
  27. $data = [
  28. 'body' => 'test save',
  29. ];
  30. $entity = $this->table->newEntity($data);
  31. $entityAfter = $this->table->save($entity);
  32. $this->assertTrue((bool)$entityAfter);
  33. // The saved entity is resetted
  34. $this->assertFalse($entityAfter->isDirty('body'));
  35. $this->assertFalse($entityAfter->isNew());
  36. $this->assertSame(['id' => 4, 'body' => 'test save'], $entityAfter->extractOriginal(['id', 'body']));
  37. $entityBefore = $this->table->getEntityBeforeSave();
  38. // The stored one from before the save contains the info we want
  39. $this->assertTrue($entityBefore->isDirty('body'));
  40. $this->assertTrue($entityBefore->isNew());
  41. $this->assertSame(['body' => 'test save'], $entityBefore->extractOriginal(['id', 'body']));
  42. }
  43. /**
  44. * @return void
  45. */
  46. public function testSaveExisting() {
  47. $data = [
  48. 'body' => 'test save',
  49. ];
  50. $entity = $this->table->newEntity($data);
  51. $this->table->saveOrFail($entity);
  52. $entity = $this->table->get($entity->id);
  53. $entity = $this->table->patchEntity($entity, ['body' => 'modified']);
  54. $this->assertEmpty($entity->getErrors());
  55. $entityAfter = $this->table->save($entity);
  56. $this->assertTrue((bool)$entityAfter);
  57. // The saved entity is resetted
  58. $this->assertFalse($entityAfter->isDirty('body'));
  59. $this->assertSame(['body' => 'modified'], $entityAfter->extractOriginal(['body']));
  60. $entityBefore = $this->table->getEntityBeforeSave();
  61. // The stored one from before the save contains the info we want
  62. $this->assertTrue($entityBefore->isDirty('body'));
  63. $this->assertSame(['body' => 'test save'], $entityBefore->extractOriginal(['body']));
  64. }
  65. }