Skip to content

Commit

Permalink
Some hooks in BaseEntity
Browse files Browse the repository at this point in the history
  • Loading branch information
Zrnik committed Nov 9, 2021
1 parent 80049df commit f13d1f5
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/Repository/BaseEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -1118,4 +1118,29 @@ public function indicateSave(bool $saved = true): void
$this->originalData = $saved ? $this->getRawData() : [];
}


//region Hooks

// TODO: Write tests for the hooks!

/**
* This hook is ran before 'toArray' method
* converts everything to actual database data...
*/
public function beforeSave() : void {}

/**
* This hook is ran after query being committed to
* the database. Raw data and save indication already happened.
*/
public function afterSave() : void {}

/**
* This method is called after it's retrieved from the database
* by Dispenser class... All foreign keys/fetch arrays
* are already handled.
*/
public function afterRetrieve() : void {}
//endregion

}
4 changes: 4 additions & 0 deletions src/Repository/Fetch/ResultService.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ public function getEntities(string $baseEntityClassString, ?string $propertyName
}
}

foreach ($result as $entity) {
$entity->afterRetrieve();
}


return $result;
}
Expand Down
9 changes: 9 additions & 0 deletions src/Repository/Saver/Saver.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ private function update(BaseEntity $entity): void
return;
}

$entity->beforeSave();
$data = $entity->toArray();
$primaryKeyName = $entity::getPrimaryKeyName();
$primaryKeyValue = $data[$primaryKeyName];
Expand Down Expand Up @@ -195,6 +196,7 @@ static function ($key) {

$entity->updateRawData();
$entity->indicateSave();
$entity->afterSave();
}


Expand Down Expand Up @@ -235,6 +237,7 @@ function insert(array $entities): void

$values = [];
foreach ($entities as $entity) {
$entity->beforeSave();
$data = $entity->toArray();
foreach ($dataKeys as $dataKey) {
$values[] = $data[$dataKey];
Expand Down Expand Up @@ -274,11 +277,17 @@ function insert(array $entities): void
$entity->setPrimaryKeyValue($firstPk);
$entity->updateRawData();
$entity->indicateSave();
$entity->afterSave();
$firstPk++;
}
//endregion

$this->pdo->commit();

foreach ($entities as $entity) {
$entity->afterSave();
}

}

/**
Expand Down

0 comments on commit f13d1f5

Please sign in to comment.