Skip to content

Commit d51920a

Browse files
committed
Mutualizing cache code
1 parent daded02 commit d51920a

File tree

1 file changed

+26
-24
lines changed

1 file changed

+26
-24
lines changed

src/SchemaAnalyzer.php

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -175,14 +175,9 @@ private function isJunctionTable(Table $table)
175175
*/
176176
public function getShortestPath($fromTable, $toTable)
177177
{
178-
$cacheKey = $this->cachePrefix.'_shortest_'.$fromTable.'```'.$toTable;
179-
$path = $this->cache->fetch($cacheKey);
180-
if ($path === false) {
181-
$path = $this->getShortestPathWithoutCache($fromTable, $toTable);
182-
$this->cache->save($cacheKey, $path);
183-
}
184-
185-
return $path;
178+
return $this->fromCache($this->cachePrefix.'_shortest_'.$fromTable.'```'.$toTable, function() use ($fromTable, $toTable) {
179+
return $this->getShortestPathWithoutCache($fromTable, $toTable);
180+
});
186181
}
187182

188183
/**
@@ -457,14 +452,9 @@ private function isInheritanceRelationship(ForeignKeyConstraint $fk) {
457452
* @return string|null
458453
*/
459454
public function getParentTable($tableName) {
460-
$cacheKey = $this->cachePrefix.'_parent_'.$tableName;
461-
$parent = $this->cache->fetch($cacheKey);
462-
if ($parent === false) {
463-
$parent = $this->getParentTableWithoutCache($tableName);
464-
$this->cache->save($cacheKey, $parent);
465-
}
466-
467-
return $parent;
455+
return $this->fromCache($this->cachePrefix.'_parent_'.$tableName, function() use ($tableName) {
456+
return $this->getParentTableWithoutCache($tableName);
457+
});
468458
}
469459

470460
/**
@@ -494,14 +484,9 @@ private function getParentTableWithoutCache($tableName) {
494484
* @return string[]
495485
*/
496486
public function getChildrenTables($tableName) {
497-
$cacheKey = $this->cachePrefix.'_children_'.$tableName;
498-
$parent = $this->cache->fetch($cacheKey);
499-
if ($parent === false) {
500-
$parent = $this->getChildrenTablesWithoutCache($tableName);
501-
$this->cache->save($cacheKey, $parent);
502-
}
503-
504-
return $parent;
487+
return $this->fromCache($this->cachePrefix.'_children_'.$tableName, function() use ($tableName) {
488+
return $this->getChildrenTablesWithoutCache($tableName);
489+
});
505490
}
506491

507492
/**
@@ -527,4 +512,21 @@ private function getChildrenTablesWithoutCache($tableName) {
527512
}
528513
return $children;
529514
}
515+
516+
/**
517+
* Returns an item from cache or computes it using $closure and puts it in cache
518+
*
519+
* @param string $key
520+
* @param callable $closure
521+
* @return mixed
522+
*/
523+
private function fromCache($key, callable $closure) {
524+
$item = $this->cache->fetch($key);
525+
if ($item === false) {
526+
$item = $closure();
527+
$this->cache->save($key, $item);
528+
}
529+
530+
return $item;
531+
}
530532
}

0 commit comments

Comments
 (0)