Skip to content

Commit

Permalink
Cache file_get_contents calls.
Browse files Browse the repository at this point in the history
  • Loading branch information
Sebastian Thulin committed Aug 18, 2023
1 parent 0dc9421 commit 4fdd74c
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions source/php/Register.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
class Register
{
private static $cache = [
'configJson' => [],
'fileExists' => []
'configJson' => [],
'fileExists' => [],
'fileGetContents' => [],
];

public $data;
Expand Down Expand Up @@ -281,12 +282,10 @@ public function locateController($controller)
*/
public function getNamespace($classPath)
{
$src = file_get_contents($classPath);

$src = $this->cachedFileGetContents($classPath);
if (preg_match('/namespace\s+(.+?);/', $src, $m)) {
return $m[1];
}

return null;
}

Expand All @@ -311,7 +310,7 @@ public function cleanViewName($viewName): string
* @throws \Exception If no configuration file is found in the specified path.
*/
private function getConfigFilePath($path) {
$configFile = $path . DIRECTORY_SEPARATOR . strtolower(basename($path)) .".json";
$configFile = $path . DIRECTORY_SEPARATOR . lcfirst(basename($path)) .".json";
if($this->cachedFileExists($configFile)) {
return $configFile;
}
Expand All @@ -338,7 +337,7 @@ private function readConfigFile(string $path) {
}

//Read config
if (!$json = file_get_contents($path)) {
if (!$json = $this->cachedFileGetContents($path)) {
throw new \Exception("Configuration file unreadable at " . $path);
}

Expand Down Expand Up @@ -400,4 +399,28 @@ private function cachedFileExists($path) {
return false;
}


/**
* Check if a file exists using cached results.
*
* This function checks for the existence of a file using cached results to improve performance.
* It first looks in the cache for a previous check result and returns true if the file is found.
* If not found in the cache, it checks the file system, updates the cache if found, and returns the result.
*
* @param string $path The path to the file to check.
* @return bool Returns true if the file exists, false otherwise.
*/
private function cachedFileGetContents($path) {
$id = md5($path);
if(isset(self::$cache['fileGetContents'][$id])) {
return self::$cache['fileGetContents'][$id];
}

if($content = file_get_contents($path)) {
return self::$cache['fileGetContents'][$id] = $content;
}

return false;
}

}

0 comments on commit 4fdd74c

Please sign in to comment.