. */ declare(strict_types=1); namespace FireflyIII\Support; use Cache; use Exception; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Configuration; use Illuminate\Database\QueryException; /** * Class FireflyConfig. * * @codeCoverageIgnore */ class FireflyConfig { /** * @param string $name */ public function delete(string $name): void { $fullName = 'ff-config-' . $name; if (Cache::has($fullName)) { Cache::forget($fullName); } try { Configuration::where('name', $name)->forceDelete(); } catch (Exception $e) { // @phpstan-ignore-line // @ignoreException } } /** * @param string $name * @param bool|string|int|null $default * * @return Configuration|null * @throws FireflyException */ public function get(string $name, $default = null): ?Configuration { $fullName = 'ff-config-' . $name; if (Cache::has($fullName)) { return Cache::get($fullName); } try { /** @var Configuration|null $config */ $config = Configuration::where('name', $name)->first(['id', 'name', 'data']); } catch (QueryException|Exception $e) { // @phpstan-ignore-line throw new FireflyException(sprintf('Could not poll the database: %s', $e->getMessage())); } if (null !== $config) { Cache::forever($fullName, $config); return $config; } // no preference found and default is null: if (null === $default) { return null; } return $this->set($name, $default); } /** * @param string $name * @param mixed $value * * @return Configuration */ public function set(string $name, $value): Configuration { try { $config = Configuration::whereName($name)->whereNull('deleted_at')->first(); } catch (QueryException|Exception $e) { // @phpstan-ignore-line $item = new Configuration; $item->name = $name; $item->data = $value; return $item; } if (null === $config) { $item = new Configuration; $item->name = $name; $item->data = $value; $item->save(); Cache::forget('ff-config-' . $name); return $item; } $config->data = $value; $config->save(); Cache::forget('ff-config-' . $name); return $config; } /** * @param string $name * @param mixed $default * * @return Configuration|null */ public function getFresh(string $name, $default = null): ?Configuration { $config = Configuration::where('name', $name)->first(['id', 'name', 'data']); if ($config) { return $config; } // no preference found and default is null: if (null === $default) { return null; } return $this->set($name, $default); } /** * @param string $name * * @return bool */ public function has(string $name): bool { return Configuration::where('name', $name)->count() === 1; } /** * @param string $name * @param mixed $value * * @return Configuration */ public function put(string $name, $value): Configuration { return $this->set($name, $value); } }