save([...$this->all(), ...[$element]]); } /** * Clears the existing file, if any, and re-creates it. */ public function boot(): void { @unlink(self::FOLDER.'/'.$this->filename.'.json'); // @phpstan-ignore-line $this->save([]); } /** * Checks if the given element exists. */ public function exists(string $element): bool { return in_array($element, $this->all(), true); } /** * Gets all elements. * * @return array */ private function all(): array { $contents = file_get_contents(self::FOLDER.'/'.$this->filename.'.json'); assert(is_string($contents)); $all = json_decode($contents, true, 512, JSON_THROW_ON_ERROR); return is_array($all) ? $all : []; } /** * Save the given elements. * * @param array $elements */ private function save(array $elements): void { $contents = json_encode($elements, JSON_THROW_ON_ERROR); file_put_contents(self::FOLDER.'/'.$this->filename.'.json', $contents); } }