/** * Move to trash. Validation will be performed * before trashing with `trash` (TrashInterface::ScenarioTrash) scenario. * * * @see TrashInterface::ScenarioTrash * @param boolean $runValidation whether to perform validation before saving the record. * If the validation fails, the record will not be saved to database. * * @return boolean * @Ignored */ public function trash($runValidation = true) { ScenarioManager::setScenario($this, TrashInterface::ScenarioTrash); $validator = new Validator($this); if (!$runValidation || $validator->validate()) { $eventBefore = new TrashEvent($this); if (Event::hasHandler($this, TrashInterface::EventBeforeTrash)) { if (!Event::valid($this, TrashInterface::EventBeforeTrash, $eventBefore)) { return false; } } $meta = ManganMeta::create($this); $trash = $eventBefore->getTrash(); if (empty($trash)) { $trash = new Trash(); } $trash->name = (string) $this; $trash->data = $this; $trash->type = isset($meta->type()->label) ? $meta->type()->label : get_class($this); if (!$trash->save()) { return false; } $eventAfter = new TrashEvent($this); $eventAfter->setTrash($trash); if (!Event::valid($this, TrashInterface::EventAfterTrash, $eventAfter)) { return false; } // Use deleteOne, to avoid beforeDelete event, // which should be raised only when really removing document: // when emtying trash $em = new EntityManager($this); return $em->deleteOne(PkManager::prepareFromModel($this)); } return false; }
public function testIfWillDeleteIndexOfTrashableDocumentAfterTrashingAndRestoreItOnRestore() { $model = new TrashableModel(); $model->_id = new MongoId(); $model->title = 'Connecticut is a state'; // Mock signal receive save (new Receiver())->onSave(new AfterSave($model)); $mnl = Manganel::fly(); $client = $mnl->getClient(); $get = ['index' => $mnl->index, 'type' => CollectionNamer::nameCollection($model), 'id' => (string) $model->_id]; $found = $client->get($get)['_source']; $this->assertSame($model->title, $found['title']); // Should be handle by event handler from Receiver $model->trash(); try { $client->get($get); $this->assertFalse(true, 'That missing exception was not thrown'); } catch (Missing404Exception $e) { $this->assertTrue(true, 'That missing exception was thrown'); } $trash = new Trash(); $trashed = $trash->find(); $this->assertNotNull($trashed, 'That item was found in trash'); $restored = $trashed->restore(); $this->assertTrue($restored, 'That item was successfully restored'); $restoredIndex = $client->get($get)['_source']; $this->assertSame($model->title, $restoredIndex['title'], 'That restored item is back in index'); }