Skip to content

Commit

Permalink
Database::getLanguage caching results, handling non existing database…
Browse files Browse the repository at this point in the history
… table (#242)

* Database::getLanguage caching results, handling non existing database table

* change cache to class member from static variable

* Apply fixes from StyleCI

[ci skip] [skip ci]

* StyleCI fixes

* rename cache variable to languages_cache

* variable name

Co-authored-by: StyleCI Bot <[email protected]>
  • Loading branch information
levu42 and StyleCIBot authored Aug 30, 2022
1 parent bfdaa82 commit 943068a
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/Drivers/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@
use JoeDixon\Translation\Exceptions\LanguageExistsException;
use JoeDixon\Translation\Language;
use JoeDixon\Translation\Translation as TranslationModel;
use Throwable;

class Database extends Translation implements DriverInterface
{
protected $sourceLanguage;

protected $scanner;

protected array $languageCache = [];

public function __construct($sourceLanguage, $scanner)
{
$this->sourceLanguage = $sourceLanguage;
Expand Down Expand Up @@ -225,7 +228,22 @@ public function getGroupsFor($language)
*/
private function getLanguage($language)
{
return Language::where('language', $language)->first();
if (isset($this->languageCache[$language])) {
return $this->languageCache[$language];
}

// Some constallation of composer packages can lead to our code being executed
// as a dependency of running migrations. That's why we need to be able to
// handle the case where the database is empty / our tables don't exist:
try {
$result = Language::where('language', $language)->first();
} catch (Throwable) {
$result = null;
}

$this->languageCache[$language] = $result;

return $result;
}

/**
Expand Down

0 comments on commit 943068a

Please sign in to comment.