diff --git a/formwork/config/routes/routes.php b/formwork/config/routes/routes.php index 0de374e64..22a28feaa 100644 --- a/formwork/config/routes/routes.php +++ b/formwork/config/routes/routes.php @@ -67,7 +67,7 @@ 'filters' => [ 'request.validateSize' => [ 'action' => static function (Config $config, Request $request, Router $router, ErrorsControllerInterface $errorsController) { - if ($config->get('system.panel.enabled') && $router->requestHasPrefix($config->get('system.panel.root'))) { + if ($config->getBool('system.panel.enabled') && $router->requestHasPrefix($config->getString('system.panel.root'))) { return; } @@ -86,7 +86,7 @@ 'request.validateCsrf' => [ 'action' => static function (Config $config, Request $request, Router $router, CsrfToken $csrfToken, ErrorsControllerInterface $errorsController) { - if ($config->get('system.panel.enabled') && $router->requestHasPrefix($config->get('system.panel.root'))) { + if ($config->getBool('system.panel.enabled') && $router->requestHasPrefix($config->getString('system.panel.root'))) { // CSRF validation is handled by a separate filter in the panel routes return; } @@ -113,7 +113,7 @@ $router->setRequest(Str::removeStart($router->request(), '/' . $requested)); } elseif (($preferred = $site->languages()->preferred()) !== null) { // Don't redirect if we are in Panel - if ($config->get('system.panel.enabled') && $router->requestHasPrefix($config->get('system.panel.root'))) { + if ($config->getBool('system.panel.enabled') && $router->requestHasPrefix($config->getString('system.panel.root'))) { return; } return new RedirectResponse($request->root() . $preferred . $router->request()); diff --git a/formwork/config/views/methods.php b/formwork/config/views/methods.php index 093eea26d..c8113b403 100644 --- a/formwork/config/views/methods.php +++ b/formwork/config/views/methods.php @@ -57,9 +57,9 @@ [ 'site' => $app->site(), 'baseRoute' => $currentPage !== null ? $currentPage->route() : '/', - 'allowHtml' => $app->config()->get('system.pages.content.allowHtml'), - 'addHeadingIds' => $app->config()->get('system.pages.content.addHeadingIds'), - 'commonmarkExtensions' => $app->config()->get('system.pages.content.commonmarkExtensions', []), + 'allowHtml' => $app->config()->getBool('system.pages.content.allowHtml'), + 'addHeadingIds' => $app->config()->getBool('system.pages.content.addHeadingIds'), + 'commonmarkExtensions' => $app->config()->getArray('system.pages.content.commonmarkExtensions', []), ] ); }, @@ -70,7 +70,7 @@ 'date' => static function (int $timestamp, ?string $format = null) use ($app): string { return Date::formatTimestamp( $timestamp, - $format ?? $app->config()->get('system.date.dateFormat'), + $format ?? $app->config()->getString('system.date.dateFormat'), $app->translations()->getCurrent() ); }, @@ -79,7 +79,7 @@ * Formats a timestamp as a datetime string */ 'datetime' => static function (int $timestamp) use ($app): string { - return Date::formatTimestamp($timestamp, $app->config()->get('system.date.datetimeFormat'), $app->translations()->getCurrent()); + return Date::formatTimestamp($timestamp, $app->config()->getString('system.date.datetimeFormat'), $app->translations()->getCurrent()); }, /** diff --git a/formwork/fields/date.php b/formwork/fields/date.php index c39bcfe42..1c407c1ae 100644 --- a/formwork/fields/date.php +++ b/formwork/fields/date.php @@ -35,7 +35,10 @@ * Return the field value as a timestamp */ 'toTimestamp' => function (Field $field) use ($app): ?int { - $formats = $app->config()->getMultiple(['system.date.dateFormat', 'system.date.datetimeFormat']); + $formats = [ + $app->config()->getString('system.date.dateFormat'), + $app->config()->getString('system.date.datetimeFormat'), + ]; return $field->isEmpty() ? null : Date::toTimestamp($field->value(), $formats); }, @@ -100,8 +103,8 @@ } $inputFormats = [ - $app->config()->get('system.date.dateFormat'), - $app->config()->get('system.date.datetimeFormat'), + $app->config()->getString('system.date.dateFormat'), + $app->config()->getString('system.date.datetimeFormat'), ]; $format = $field->hasTime() diff --git a/formwork/fields/markdown.php b/formwork/fields/markdown.php index 8c25ff040..4ad15e162 100644 --- a/formwork/fields/markdown.php +++ b/formwork/fields/markdown.php @@ -29,9 +29,9 @@ [ 'site' => $site, 'baseRoute' => $currentPage !== null ? $currentPage->route() : '/', - 'allowHtml' => $app->config()->get('system.pages.content.allowHtml'), - 'addHeadingIds' => $app->config()->get('system.pages.content.addHeadingIds'), - 'commonmarkExtensions' => $app->config()->get('system.pages.content.commonmarkExtensions', []), + 'allowHtml' => $app->config()->getBool('system.pages.content.allowHtml'), + 'addHeadingIds' => $app->config()->getBool('system.pages.content.addHeadingIds'), + 'commonmarkExtensions' => $app->config()->getArray('system.pages.content.commonmarkExtensions', []), ] ); }, diff --git a/formwork/fields/upload.php b/formwork/fields/upload.php index 2102682fd..4f05c9eb5 100644 --- a/formwork/fields/upload.php +++ b/formwork/fields/upload.php @@ -16,7 +16,7 @@ * Return the accepted MIME types for the field */ 'acceptMimeTypes' => function (Field $field) use ($app) { - $allowedExtensions = $app->config()->get('system.files.allowedExtensions', ''); + $allowedExtensions = $app->config()->getArray('system.files.allowedExtensions', []); $accept = is_string($field->get('accept')) ? preg_split('/\s*,\s*/', $field->get('accept'), flags: PREG_SPLIT_NO_EMPTY) @@ -89,7 +89,7 @@ return null; } - $allowedExtensions = $app->config()->get('system.files.allowedExtensions', ''); + $allowedExtensions = $app->config()->getArray('system.files.allowedExtensions', []); $allowedMimeTypes = Arr::map($allowedExtensions, MimeType::fromExtension(...)); $acceptMimeTypes = $field->acceptMimeTypes(); diff --git a/formwork/src/Cms/App.php b/formwork/src/Cms/App.php index fa3211e2e..8a5971d20 100644 --- a/formwork/src/Cms/App.php +++ b/formwork/src/Cms/App.php @@ -284,8 +284,8 @@ private function loadServices(Container $container): void ->alias('config'); $container->define(ViewFactory::class) - ->parameter('resolutionPaths', fn(Config $config) => ['system' => $config->get('system.views.paths.system')]) - ->parameter('methods', fn(Container $container, Config $config) => $container->call(require $config->get('system.views.methods.system'))); + ->parameter('resolutionPaths', fn(Config $config) => ['system' => $config->getString('system.views.paths.system')]) + ->parameter('methods', fn(Container $container, Config $config) => $container->call(require $config->getString('system.views.methods.system'))); $container->define(ErrorsController::class) ->alias(ErrorsControllerInterface::class); @@ -323,13 +323,13 @@ private function loadServices(Container $container): void ->alias('templates'); $container->define(Statistics::class) - ->parameter('options', fn(Config $config) => $config->get('site.statistics')) + ->parameter('options', fn(Config $config) => $config->getArray('site.statistics')) ->parameter('translation', fn(Translations $translations) => $translations->getCurrent()) ->alias('statistics'); $container->define(FilesCache::class) - ->parameter('path', fn(Config $config) => $config->get('system.cache.path')) - ->parameter('defaultTtl', fn(Config $config) => $config->get('system.cache.time')) + ->parameter('path', fn(Config $config) => $config->getString('system.cache.path')) + ->parameter('defaultTtl', fn(Config $config) => $config->getInt('system.cache.time')) ->alias(AbstractCache::class) ->alias('cache'); @@ -376,14 +376,14 @@ private function loadRoutes(): void { $this->events()->dispatch(new RoutesBeforeLoadEvent($this->router())); - if ($this->config()->get('system.panel.enabled')) { + if ($this->config()->getBool('system.panel.enabled')) { $this->router()->loadFromFile( - $this->config()->get('system.routes.files.panel'), - Str::wrap($this->config()->get('system.panel.root'), '/') + $this->config()->getString('system.routes.files.panel'), + Str::wrap($this->config()->getString('system.panel.root'), '/') ); } - $this->router()->loadFromFile($this->config()->get('system.routes.files.system')); + $this->router()->loadFromFile($this->config()->getString('system.routes.files.system')); $this->events()->dispatch(new RoutesAfterLoadEvent($this->router())); } diff --git a/formwork/src/Cms/Site.php b/formwork/src/Cms/Site.php index 79eed257d..ba320708c 100644 --- a/formwork/src/Cms/Site.php +++ b/formwork/src/Cms/Site.php @@ -270,8 +270,8 @@ public function metadata(): MetadataCollection } $defaults = [ - 'charset' => $this->config->get('system.charset'), - 'generator' => $this->config->get('system.metadata.setGenerator') ? 'Formwork' : null, + 'charset' => $this->config->getString('system.charset'), + 'generator' => $this->config->getBool('system.metadata.setGenerator') ? 'Formwork' : null, ]; $data = array_filter([...$defaults, ...$this->data['metadata']]); @@ -436,7 +436,7 @@ public function findPage(string $route): ?Page */ public function indexPage(): Page { - return $this->findPage($this->config->get('system.pages.index')) + return $this->findPage($this->config->getString('system.pages.index')) ?? throw new PageNotFoundException('Site index page not found'); } @@ -447,7 +447,7 @@ public function indexPage(): Page */ public function errorPage(): Page { - return $this->findPage($this->config->get('system.pages.error')) + return $this->findPage($this->config->getString('system.pages.error')) ?? throw new PageNotFoundException('Site error page not found'); } @@ -478,15 +478,15 @@ public function files(): FileCollection $files = []; - $path = $this->config->get('system.files.paths.site'); + $path = $this->config->getString('system.files.paths.site'); if (FileSystem::isDirectory($path, assertExists: false)) { foreach (FileSystem::listFiles($path) as $file) { $extension = '.' . FileSystem::extension($file); - if (Str::endsWith($file, $this->config->get('system.files.metadataExtension'))) { + if (Str::endsWith($file, $this->config->getString('system.files.metadataExtension'))) { continue; } - if (in_array($extension, $this->config->get('system.files.allowedExtensions'), true)) { + if (in_array($extension, $this->config->getArray('system.files.allowedExtensions', []), true)) { $files[] = $this->app()->getService(FileFactory::class)->make(FileSystem::joinPaths($path, $file)); } } diff --git a/formwork/src/Commands/BackupCommand.php b/formwork/src/Commands/BackupCommand.php index f678e2e75..b8a1edaa4 100644 --- a/formwork/src/Commands/BackupCommand.php +++ b/formwork/src/Commands/BackupCommand.php @@ -136,7 +136,7 @@ public function list(array $argv = []): void */ private function getBackupper(?string $hostname = null): Backupper { - return new Backupper([...$this->app->config()->get('system.backup'), 'hostname' => $hostname ?? (gethostname() ?: 'local-cli')]); + return new Backupper([...$this->app->config()->getArray('system.backup'), 'hostname' => $hostname ?? (gethostname() ?: 'local-cli')]); } /** diff --git a/formwork/src/Commands/CacheCommand.php b/formwork/src/Commands/CacheCommand.php index e131ebed5..7a14d4772 100644 --- a/formwork/src/Commands/CacheCommand.php +++ b/formwork/src/Commands/CacheCommand.php @@ -219,7 +219,7 @@ private function configCacheStats(): void */ private function imagesCacheStats(): void { - $path = $this->app->config()->get('system.images.processPath'); + $path = $this->app->config()->getString('system.images.processPath'); $items = iterator_to_array(FileSystem::listContents($path)); $size = FileSystem::directorySize($path); @@ -233,7 +233,7 @@ private function imagesCacheStats(): void */ private function pagesCacheStats(): void { - $path = $this->app->config()->get('system.cache.path'); + $path = $this->app->config()->getString('system.cache.path'); $items = iterator_to_array(FileSystem::listContents($path)); $size = FileSystem::directorySize($path); @@ -273,7 +273,7 @@ private function clearCaches(array $types): void */ private function clearImagesCache(): void { - $path = $this->app->config()->get('system.images.processPath'); + $path = $this->app->config()->getString('system.images.processPath'); FileSystem::delete($path, recursive: true); FileSystem::createDirectory($path, recursive: true); } diff --git a/formwork/src/Commands/UpdatesCommand.php b/formwork/src/Commands/UpdatesCommand.php index c7eac5134..95e16794f 100644 --- a/formwork/src/Commands/UpdatesCommand.php +++ b/formwork/src/Commands/UpdatesCommand.php @@ -203,7 +203,7 @@ public function update(array $argv = []): void } $this->climate->br(); - if ($this->app->config()->get('system.cache.enabled')) { + if ($this->app->config()->getBool('system.cache.enabled')) { $this->climate->out('Clearing cache...'); $this->app->getService(AbstractCache::class)->clear(); $this->climate->br(); @@ -219,7 +219,7 @@ public function update(array $argv = []): void */ private function getUpdater(array $config): Updater { - return new Updater([...$this->app->config()->get('system.updates'), ...$config], App::instance()); + return new Updater([...$this->app->config()->getArray('system.updates'), ...$config], App::instance()); } /** @@ -227,7 +227,7 @@ private function getUpdater(array $config): Updater */ private function getBackupper(): Backupper { - return new Backupper([...$this->app->config()->get('system.backup'), 'hostname' => gethostname() ?: 'local-cli']); + return new Backupper([...$this->app->config()->getArray('system.backup'), 'hostname' => gethostname() ?: 'local-cli']); } /** diff --git a/formwork/src/Config/Config.php b/formwork/src/Config/Config.php index 702b9b0bd..270e7675f 100644 --- a/formwork/src/Config/Config.php +++ b/formwork/src/Config/Config.php @@ -10,6 +10,7 @@ use Formwork\Utils\Arr; use Formwork\Utils\FileSystem; use Formwork\Utils\Str; +use UnexpectedValueException; class Config implements ArraySerializable { @@ -64,6 +65,80 @@ public function get(string $key, mixed $default = null): mixed return Arr::get($this->config, $key, $default); } + /** + * Get a string value from the config + * + * @throws UnexpectedValueException If the config value is not a string + */ + public function getString(string $key, ?string $default = null): string + { + $value = $this->get($key, $default); + if (!is_string($value)) { + throw new UnexpectedValueException(sprintf('Config value for key "%s" is not a string, got %s', $key, get_debug_type($value))); + } + return $value; + } + + /** + * Get a boolean value from the config + * + * @throws UnexpectedValueException If the config value is not a boolean + */ + public function getBool(string $key, ?bool $default = null): bool + { + $value = $this->get($key, $default); + if (!is_bool($value)) { + throw new UnexpectedValueException(sprintf('Config value for key "%s" is not a boolean, got %s', $key, get_debug_type($value))); + } + return $value; + } + + /** + * Get an integer value from the config + * + * @throws UnexpectedValueException If the config value is not an integer + */ + public function getInt(string $key, ?int $default = null): int + { + $value = $this->get($key, $default); + if (!is_int($value)) { + throw new UnexpectedValueException(sprintf('Config value for key "%s" is not an integer, got %s', $key, get_debug_type($value))); + } + return $value; + } + + /** + * Get a float value from the config + * + * @throws UnexpectedValueException If the config value is not a float + */ + public function getFloat(string $key, ?float $default = null): float + { + $value = $this->get($key, $default); + if (!is_float($value)) { + throw new UnexpectedValueException(sprintf('Config value for key "%s" is not a float, got %s', $key, get_debug_type($value))); + } + return $value; + } + + /** + * Get an array value from the config + * + * @param ?array $default + * + * @throws UnexpectedValueException If the config value is not an array + * + * @return array + */ + public function getArray(string $key, ?array $default = null): array + { + $value = $this->get($key, $default); + if (!is_array($value)) { + throw new UnexpectedValueException(sprintf('Config value for key "%s" is not an array, got %s', $key, get_debug_type($value))); + } + return $value; + } + /** * Get multiple values from the config * diff --git a/formwork/src/Controllers/AssetsController.php b/formwork/src/Controllers/AssetsController.php index b66dc0842..c68c58c21 100644 --- a/formwork/src/Controllers/AssetsController.php +++ b/formwork/src/Controllers/AssetsController.php @@ -21,7 +21,7 @@ public function asset(RouteParams $routeParams): Response return $this->redirect($this->router->rewrite(['type' => 'images']), ResponseStatus::MovedPermanently); } - $path = FileSystem::joinPaths($this->config->get('system.images.processPath'), $routeParams->get('id'), $routeParams->get('name')); + $path = FileSystem::joinPaths($this->config->getString('system.images.processPath'), $routeParams->get('id'), $routeParams->get('name')); if (FileSystem::isFile($path, assertExists: false)) { return new FileResponse($path, headers: ['Cache-Control' => 'private, max-age=31536000, immutable'], autoEtag: true, autoLastModified: true); @@ -35,7 +35,7 @@ public function asset(RouteParams $routeParams): Response */ public function template(RouteParams $routeParams): Response { - $path = FileSystem::joinPaths($this->config->get('system.templates.path'), 'assets', Path::resolve($routeParams->get('file'), '/', DIRECTORY_SEPARATOR)); + $path = FileSystem::joinPaths($this->config->getString('system.templates.path'), 'assets', Path::resolve($routeParams->get('file'), '/', DIRECTORY_SEPARATOR)); if (FileSystem::isFile($path, assertExists: false)) { $headers = $this->request->query()->has('v') diff --git a/formwork/src/Controllers/ErrorsController.php b/formwork/src/Controllers/ErrorsController.php index bd68ebf8f..3fba8fe21 100644 --- a/formwork/src/Controllers/ErrorsController.php +++ b/formwork/src/Controllers/ErrorsController.php @@ -22,7 +22,7 @@ public function error(ResponseStatus $responseStatus = ResponseStatus::InternalS { Response::cleanOutputBuffers(); - if ($this->config->get('system.debug.enabled') || $this->request->isLocalhost()) { + if ($this->config->getBool('system.debug.enabled') || $this->request->isLocalhost()) { $data['throwable'] = $throwable; $data['stackTrace'] = $throwable !== null ? $this->getTrace($throwable) : []; } diff --git a/formwork/src/Controllers/FilesController.php b/formwork/src/Controllers/FilesController.php index a8eb8f112..9fa4a8f35 100644 --- a/formwork/src/Controllers/FilesController.php +++ b/formwork/src/Controllers/FilesController.php @@ -14,7 +14,7 @@ final class FilesController extends AbstractController */ public function file(RouteParams $routeParams): Response { - $path = FileSystem::joinPaths($this->config->get('system.files.paths.site'), $routeParams->get('name')); + $path = FileSystem::joinPaths($this->config->getString('system.files.paths.site'), $routeParams->get('name')); if (FileSystem::isFile($path, assertExists: false)) { return new FileResponse($path); diff --git a/formwork/src/Controllers/PageController.php b/formwork/src/Controllers/PageController.php index ffca2c3c2..f8c1aeba4 100644 --- a/formwork/src/Controllers/PageController.php +++ b/formwork/src/Controllers/PageController.php @@ -30,7 +30,7 @@ public function __construct( */ public function load(RouteParams $routeParams, Statistics $statistics): Response { - $trackable = $this->config->get('site.statistics.enabled'); + $trackable = $this->config->getBool('site.statistics.enabled'); if ($this->site->get('maintenance.enabled') && !$this->app->panel()->isLoggedIn()) { $trackable = false; @@ -44,7 +44,7 @@ public function load(RouteParams $routeParams, Statistics $statistics): Response } if (!isset($route)) { - $route = $routeParams->get('page', $this->config->get('system.pages.index')); + $route = $routeParams->get('page', $this->config->getString('system.pages.index')); if ($resolvedAlias = $this->site->resolveRouteAlias($route)) { $route = $resolvedAlias; @@ -69,7 +69,7 @@ public function load(RouteParams $routeParams, Statistics $statistics): Response return $this->getPageResponse($this->site->errorPage()); } - if ($this->config->get('system.cache.enabled') && ($page->fields()->has('publishDate') || $page->fields()->has('unpublishDate')) && ( + if ($this->config->getBool('system.cache.enabled') && ($page->fields()->has('publishDate') || $page->fields()->has('unpublishDate')) && ( ($page->isPublished() && !$page->publishDate()->isEmpty() && !$this->site->modifiedSince($page->publishDate()->toTimestamp())) || (!$page->isPublished() && !$page->unpublishDate()->isEmpty() && !$this->site->modifiedSince($page->unpublishDate()->toTimestamp())) )) { @@ -91,7 +91,7 @@ public function load(RouteParams $routeParams, Statistics $statistics): Response $upperLevel = dirname((string) $route); if ($upperLevel === '.') { - $upperLevel = $this->config->get('system.pages.index'); + $upperLevel = $this->config->getString('system.pages.index'); } if ( @@ -130,7 +130,7 @@ private function getPageResponse(Page $page): Response // Use requested route as cache key to include parameters like pagination and tags $cacheKey = $this->router->request(); - $cacheable = $this->config->get('system.cache.enabled') + $cacheable = $this->config->getBool('system.cache.enabled') && $this->isRequestCacheable() && $page->cacheable() && !$page->isErrorPage(); diff --git a/formwork/src/Fields/FieldFactory.php b/formwork/src/Fields/FieldFactory.php index 8b775b56c..58369d716 100644 --- a/formwork/src/Fields/FieldFactory.php +++ b/formwork/src/Fields/FieldFactory.php @@ -63,7 +63,7 @@ public function make(string $name, array $data = [], ?FieldCollection $parentFie */ private function getFieldConfig(string $type, ?array $default = null): array { - $configPath = FileSystem::joinPaths($this->config->get('system.fields.path'), $type . '.php'); + $configPath = FileSystem::joinPaths($this->config->getString('system.fields.path'), $type . '.php'); if (!FileSystem::exists($configPath)) { if ($default !== null) { diff --git a/formwork/src/Files/FileFactory.php b/formwork/src/Files/FileFactory.php index 59fecacd2..b998ffe07 100644 --- a/formwork/src/Files/FileFactory.php +++ b/formwork/src/Files/FileFactory.php @@ -47,7 +47,7 @@ public function make(string $path): File $instance->setScheme($this->schemes->get($instance::SCHEME_IDENTIFIER)); - $metadataFile = $path . $this->config->get('system.files.metadataExtension'); + $metadataFile = $path . $this->config->getString('system.files.metadataExtension'); $metadata = FileSystem::exists($metadataFile) ? Yaml::parseFile($metadataFile) : []; diff --git a/formwork/src/Files/FileUriGenerator.php b/formwork/src/Files/FileUriGenerator.php index 8d265e6e3..a272a6295 100644 --- a/formwork/src/Files/FileUriGenerator.php +++ b/formwork/src/Files/FileUriGenerator.php @@ -29,32 +29,32 @@ public function generate(File $file): string { $path = $file->path(); - if (Str::startsWith($path, FileSystem::normalizePath($this->config->get('system.files.paths.site')))) { + if (Str::startsWith($path, FileSystem::normalizePath($this->config->getString('system.files.paths.site')))) { $name = basename($path); $uriPath = $this->router->generate('files', compact('name')); return $this->site->uri($uriPath, includeLanguage: false); } - if (Str::startsWith($path, FileSystem::normalizePath($this->config->get('system.images.processPath')))) { + if (Str::startsWith($path, FileSystem::normalizePath($this->config->getString('system.images.processPath')))) { $id = basename(dirname($path)); $name = basename($path); $uriPath = $this->router->generate('assets', ['type' => 'images', 'id' => $id, 'name' => $name]); return $this->site->uri($uriPath, includeLanguage: false); } - if (Str::startsWith($path, $contentPath = FileSystem::normalizePath($this->config->get('system.pages.path')))) { + if (Str::startsWith($path, $contentPath = FileSystem::normalizePath($this->config->getString('system.pages.path')))) { $uriPath = preg_replace('~[/\\\](\d+-)~', '/', Str::after(dirname($path), $contentPath)) ?? throw new RuntimeException(sprintf('Replacement failed with error: %s', preg_last_error_msg())); return $this->site->uri(Path::join([$uriPath, basename($path)]), includeLanguage: false); } - if (Str::startsWith($path, FileSystem::normalizePath($this->config->get('system.users.paths.images')))) { + if (Str::startsWith($path, FileSystem::normalizePath($this->config->getString('system.users.paths.images')))) { $image = basename($path); $uriPath = $this->router->generate('panel.users.images', compact('image')); return $this->site->uri($uriPath, includeLanguage: false); } - if (Str::startsWith($path, $panelAssetsPath = FileSystem::normalizePath($this->config->get('system.panel.paths.assets')))) { + if (Str::startsWith($path, $panelAssetsPath = FileSystem::normalizePath($this->config->getString('system.panel.paths.assets')))) { $uriPath = Str::after($path, $panelAssetsPath); return $this->site->uri(Path::join(['panel/assets/', $uriPath]), includeLanguage: false); } diff --git a/formwork/src/Files/Services/FileUploader.php b/formwork/src/Files/Services/FileUploader.php index 2c7d65ba5..37e2679bb 100644 --- a/formwork/src/Files/Services/FileUploader.php +++ b/formwork/src/Files/Services/FileUploader.php @@ -31,8 +31,8 @@ public function __construct( protected Config $config, protected FileFactory $fileFactory, ) { - $this->allowedMimeTypes = Arr::map($this->config->get('system.files.allowedExtensions'), fn(string $ext) => MimeType::fromExtension($ext)); - $this->baseDestinations = $this->config->get('system.files.uploads.baseDestinations'); + $this->allowedMimeTypes = Arr::map($this->config->getArray('system.files.allowedExtensions', []), fn(string $ext) => MimeType::fromExtension($ext)); + $this->baseDestinations = $this->config->getArray('system.files.uploads.baseDestinations', []); } /** @@ -89,7 +89,7 @@ public function upload(UploadedFile $uploadedFile, string $destinationPath, ?str case 'image/webp': case 'image/avif': // Process JPEG, PNG, WebP and AVIF images according to system options (e.g. quality) - if ($this->config->get('system.uploads.processImages') && !$file->info()->isAnimation()) { + if ($this->config->getBool('system.uploads.processImages') && !$file->info()->isAnimation()) { $file->save(); } break; diff --git a/formwork/src/Images/ImageFactory.php b/formwork/src/Images/ImageFactory.php index 7640d682c..63cf2c36e 100644 --- a/formwork/src/Images/ImageFactory.php +++ b/formwork/src/Images/ImageFactory.php @@ -20,7 +20,7 @@ public function make(string $path, array $options = []): Image /** * @var array */ - $defaults = $this->config->get('system.images', []); + $defaults = $this->config->getArray('system.images', []); return new Image($path, [...$defaults, ...$options]); } diff --git a/formwork/src/Pages/Page.php b/formwork/src/Pages/Page.php index a8d11c3c9..eef5ba57d 100644 --- a/formwork/src/Pages/Page.php +++ b/formwork/src/Pages/Page.php @@ -770,7 +770,7 @@ protected function load(): void $extension = '.' . FileSystem::extension($file); - if ($extension === $config->get('system.pages.content.extension')) { + if ($extension === $config->getString('system.pages.content.extension')) { $language = ''; if (preg_match('/([a-z0-9]+)\.([a-z]+)/', $name, $matches)) { @@ -789,10 +789,10 @@ protected function load(): void } } } else { - if (Str::endsWith($file, $config->get('system.files.metadataExtension'))) { + if (Str::endsWith($file, $config->getString('system.files.metadataExtension'))) { continue; } - if (in_array($extension, $config->get('system.files.allowedExtensions'), true)) { + if (in_array($extension, $config->getArray('system.files.allowedExtensions', []), true)) { $files[] = $this->app()->getService(FileFactory::class)->make(FileSystem::joinPaths($this->path, $file)); } } @@ -927,7 +927,7 @@ protected function write(?string $language = null, bool $copy = false): void $filename .= ".{$language}"; } - $filename .= $config->get('system.pages.content.extension'); + $filename .= $config->getString('system.pages.content.extension'); $fileContent = Str::wrap(Yaml::encode($frontmatter), '---' . PHP_EOL) . $content; @@ -1052,7 +1052,7 @@ protected function setNum(?int $num = null): void if ($mode === 'date') { $timestamp = isset($this->data['publishDate']) - ? Date::toTimestamp($this->data['publishDate'], [$this->app()->config()->get('system.date.dateFormat'), $this->app()->config()->get('system.date.datetimeFormat')]) + ? Date::toTimestamp($this->data['publishDate'], [$this->app()->config()->getString('system.date.dateFormat'), $this->app()->config()->getString('system.date.datetimeFormat')]) : ($this->contentFile()?->lastModifiedTime() ?? time()); $num = (int) date(self::DATE_NUM_FORMAT, $timestamp); } elseif ($this->parent() === null) { diff --git a/formwork/src/Pages/Traits/PageStatus.php b/formwork/src/Pages/Traits/PageStatus.php index 7e282c89a..790b6f489 100644 --- a/formwork/src/Pages/Traits/PageStatus.php +++ b/formwork/src/Pages/Traits/PageStatus.php @@ -32,7 +32,10 @@ public function status(): string $now = time(); - $formats = $this->app()->config()->getMultiple(['system.date.dateFormat', 'system.date.datetimeFormat']); + $formats = [ + $this->app()->config()->getString('system.date.dateFormat'), + $this->app()->config()->getString('system.date.datetimeFormat'), + ]; if ($publishDate = ($this->data['publishDate'] ?? null)) { if (!is_string($publishDate)) { diff --git a/formwork/src/Panel/Controllers/AssetsController.php b/formwork/src/Panel/Controllers/AssetsController.php index 27947f391..d1ad8b4bc 100644 --- a/formwork/src/Panel/Controllers/AssetsController.php +++ b/formwork/src/Panel/Controllers/AssetsController.php @@ -16,7 +16,7 @@ final class AssetsController extends AbstractController */ public function asset(RouteParams $routeParams): Response { - $path = FileSystem::joinPaths($this->config->get('system.panel.paths.assets'), $routeParams->get('type'), Path::resolve($routeParams->get('file'), '/', DIRECTORY_SEPARATOR)); + $path = FileSystem::joinPaths($this->config->getString('system.panel.paths.assets'), $routeParams->get('type'), Path::resolve($routeParams->get('file'), '/', DIRECTORY_SEPARATOR)); if (FileSystem::isFile($path, assertExists: false)) { $headers = ( diff --git a/formwork/src/Panel/Controllers/AuthenticationController.php b/formwork/src/Panel/Controllers/AuthenticationController.php index f4b022137..ed62bd012 100644 --- a/formwork/src/Panel/Controllers/AuthenticationController.php +++ b/formwork/src/Panel/Controllers/AuthenticationController.php @@ -93,7 +93,7 @@ public function logout(): RedirectResponse $this->events->dispatch(new PanelLoggedOutEvent($user)); - if ($this->config->get('system.panel.logoutRedirect') === 'home') { + if ($this->config->getString('system.panel.logoutRedirect') === 'home') { return $this->redirect('/'); } diff --git a/formwork/src/Panel/Controllers/BackupController.php b/formwork/src/Panel/Controllers/BackupController.php index f5b3fcbac..dac4de538 100644 --- a/formwork/src/Panel/Controllers/BackupController.php +++ b/formwork/src/Panel/Controllers/BackupController.php @@ -24,7 +24,7 @@ public function make(): JsonResponse|Response return $this->forward(ErrorsController::class, 'forbidden'); } - $backupper = new Backupper([...$this->config->get('system.backup'), 'hostname' => $this->request->host()]); + $backupper = new Backupper([...$this->config->getArray('system.backup'), 'hostname' => $this->request->host()]); try { $file = $backupper->backup(); } catch (TranslatedException $e) { @@ -35,10 +35,10 @@ public function make(): JsonResponse|Response return JsonResponse::success($this->translate('panel.backup.ready'), data: [ 'filename' => $filename, 'uri' => $this->panel->uri("/backup/download/{$uriName}/"), - 'date' => Date::formatTimestamp(FileSystem::lastModifiedTime($file), $this->config->get('system.date.datetimeFormat'), $this->translations->getCurrent()), + 'date' => Date::formatTimestamp(FileSystem::lastModifiedTime($file), $this->config->getString('system.date.datetimeFormat'), $this->translations->getCurrent()), 'size' => FileSystem::formatSize(FileSystem::size($file)), 'deleteUri' => $this->panel->uri("/backup/delete/{$uriName}/"), - 'maxFiles' => $this->config->get('system.backup.maxFiles'), + 'maxFiles' => $this->config->getInt('system.backup.maxFiles'), ]); } @@ -51,7 +51,7 @@ public function download(RouteParams $routeParams): Response return $this->forward(ErrorsController::class, 'forbidden'); } - $file = FileSystem::joinPaths($this->config->get('system.backup.path'), basename(base64_decode((string) $routeParams->get('backup')))); + $file = FileSystem::joinPaths($this->config->getString('system.backup.path'), basename(base64_decode((string) $routeParams->get('backup')))); try { if (FileSystem::isFile($file, assertExists: false)) { return new FileResponse($file, download: true); @@ -72,7 +72,7 @@ public function delete(RouteParams $routeParams): Response return $this->forward(ErrorsController::class, 'forbidden'); } - $file = FileSystem::joinPaths($this->config->get('system.backup.path'), basename(base64_decode((string) $routeParams->get('backup')))); + $file = FileSystem::joinPaths($this->config->getString('system.backup.path'), basename(base64_decode((string) $routeParams->get('backup')))); try { if (FileSystem::isFile($file, assertExists: false)) { FileSystem::delete($file); diff --git a/formwork/src/Panel/Controllers/CacheController.php b/formwork/src/Panel/Controllers/CacheController.php index a742de580..4351a14bd 100644 --- a/formwork/src/Panel/Controllers/CacheController.php +++ b/formwork/src/Panel/Controllers/CacheController.php @@ -35,7 +35,7 @@ public function clear(RouteParams $routeParams): JsonResponse|Response case 'default': $this->clearCaches([ 'pages' => true, - 'images' => $this->config->get('system.images.clearCacheByDefault'), + 'images' => $this->config->getBool('system.images.clearCacheByDefault'), ]); return JsonResponse::success($this->translate('panel.cache.cleared'), data: compact('type')); case 'all': @@ -97,7 +97,7 @@ private function clearPagesCache(): void */ private function clearImagesCache(): void { - $path = $this->config->get('system.images.processPath'); + $path = $this->config->getString('system.images.processPath'); FileSystem::delete($path, recursive: true); FileSystem::createDirectory($path, recursive: true); } diff --git a/formwork/src/Panel/Controllers/ErrorsController.php b/formwork/src/Panel/Controllers/ErrorsController.php index 906600ef2..6861b2f9b 100644 --- a/formwork/src/Panel/Controllers/ErrorsController.php +++ b/formwork/src/Panel/Controllers/ErrorsController.php @@ -68,7 +68,7 @@ private function makeErrorResponse(ResponseStatus $responseStatus, string $name, { Response::cleanOutputBuffers(); - if ($this->config->get('system.debug.enabled') || $this->request->isLocalhost()) { + if ($this->config->getBool('system.debug.enabled') || $this->request->isLocalhost()) { $data['throwable'] = $throwable; $data['stackTrace'] = $throwable !== null ? $this->getTrace($throwable) : []; } diff --git a/formwork/src/Panel/Controllers/FilesController.php b/formwork/src/Panel/Controllers/FilesController.php index add02ca52..f442f6c3c 100644 --- a/formwork/src/Panel/Controllers/FilesController.php +++ b/formwork/src/Panel/Controllers/FilesController.php @@ -65,7 +65,7 @@ public function list(RouteParams $routeParams): JsonResponse|Response 'size' => $file->size(), 'lastModifiedTime' => Date::formatTimestamp( $file->lastModifiedTime(), - $this->config->get('system.date.datetimeFormat'), + $this->config->getString('system.date.datetimeFormat'), $this->translations->getCurrent() ), 'type' => $file->type(), @@ -107,7 +107,7 @@ public function upload(): Response } $destination = $parent instanceof Site - ? $this->config->get('system.files.paths.site') + ? $this->config->getString('system.files.paths.site') : $parent->contentPath(); try { @@ -275,7 +275,7 @@ public function rename(RouteParams $routeParams, FileFactory $fileFactory): Json 'size' => $file->size(), 'lastModifiedTime' => Date::formatTimestamp( $file->lastModifiedTime(), - $this->config->get('system.date.datetimeFormat'), + $this->config->getString('system.date.datetimeFormat'), $this->translations->getCurrent() ), 'type' => $file->type(), @@ -344,7 +344,7 @@ public function replace(RouteParams $routeParams): JsonResponse|Response 'size' => $file->size(), 'lastModifiedTime' => Date::formatTimestamp( $file->lastModifiedTime(), - $this->config->get('system.date.datetimeFormat'), + $this->config->getString('system.date.datetimeFormat'), $this->translations->getCurrent() ), 'type' => $file->type(), @@ -395,7 +395,7 @@ private function updateFileMetadata(File $file, FormData $formData): void Arr::undot($file->fields()->extract('default')) ); - $metaFile = $file->path() . $this->config->get('system.files.metadataExtension'); + $metaFile = $file->path() . $this->config->getString('system.files.metadataExtension'); if ($data === [] && FileSystem::exists($metaFile)) { FileSystem::delete($metaFile); diff --git a/formwork/src/Panel/Controllers/OptionsController.php b/formwork/src/Panel/Controllers/OptionsController.php index 451e93487..9333db78c 100644 --- a/formwork/src/Panel/Controllers/OptionsController.php +++ b/formwork/src/Panel/Controllers/OptionsController.php @@ -36,7 +36,7 @@ public function systemOptions(Schemes $schemes): Response $scheme = $schemes->get('config.system'); $fields = $scheme->fields(); - $fields->setValues($this->config->get('system')); + $fields->setValues($this->config->getArray('system')); $form = $this->form('system-options', $fields) ->processRequest($this->request); @@ -45,8 +45,8 @@ public function systemOptions(Schemes $schemes): Response if (!$form->isValid()) { $this->panel->notify($this->translate('panel.options.cannotUpdate.invalidFields'), 'error'); } else { - $options = $this->getConfigOverrides()->get('system', []); - $defaults = $this->getConfigDefaults()->get('system'); + $options = $this->getConfigOverrides()->getArray('system', []); + $defaults = $this->getConfigDefaults()->getArray('system'); $differ = $this->updateOptions('system', $form->data()->toArray(), $options, $defaults); @@ -90,8 +90,8 @@ public function siteOptions(Schemes $schemes): Response if (!$form->isValid()) { $this->panel->notify($this->translate('panel.options.cannotUpdate.invalidFields'), 'error'); } else { - $options = $this->getConfigOverrides()->get('site', []); - $defaults = $this->getConfigDefaults()->get('site'); + $options = $this->getConfigOverrides()->getArray('site', []); + $defaults = $this->getConfigDefaults()->getArray('site'); $differ = $this->updateOptions('site', $form->data()->toArray(), $options, $defaults); // Touch content folder to invalidate cache diff --git a/formwork/src/Panel/Controllers/PagesController.php b/formwork/src/Panel/Controllers/PagesController.php index ddb89a5e5..506aabc88 100644 --- a/formwork/src/Panel/Controllers/PagesController.php +++ b/formwork/src/Panel/Controllers/PagesController.php @@ -463,7 +463,7 @@ public function upload(RouteParams $routeParams): Response|JsonResponse 'size' => $file->size(), 'lastModifiedTime' => Date::formatTimestamp( $file->lastModifiedTime(), - $this->config->get('system.date.datetimeFormat'), + $this->config->getString('system.date.datetimeFormat'), $this->translations->getCurrent() ), 'type' => $file->type(), diff --git a/formwork/src/Panel/Controllers/PluginsController.php b/formwork/src/Panel/Controllers/PluginsController.php index d4f6f3c75..9eb7bfe3e 100644 --- a/formwork/src/Panel/Controllers/PluginsController.php +++ b/formwork/src/Panel/Controllers/PluginsController.php @@ -69,7 +69,7 @@ public function plugin(RouteParams $routeParams, Plugins $plugins): Response $fields = $scheme->fields(); - $fields->setValues($this->config->get("plugins.{$name}", [])); + $fields->setValues($this->config->getArray("plugins.{$name}", [])); $form = $this->form('plugin-options', $fields) ->processRequest($this->request); @@ -146,7 +146,7 @@ private function togglePluginStatus(Plugin $plugin, bool $enabled): void */ private function updatePluginsOptions(Plugin $plugin, array $options): void { - $options = Arr::override($this->config->get("plugins.{$plugin->name()}", []), Arr::undot($options)); + $options = Arr::override($this->config->getArray("plugins.{$plugin->name()}", []), Arr::undot($options)); if (!FileSystem::isDirectory(ROOT_PATH . '/site/config/plugins/', assertExists: false)) { FileSystem::createDirectory(ROOT_PATH . '/site/config/plugins/'); diff --git a/formwork/src/Panel/Controllers/ToolsController.php b/formwork/src/Panel/Controllers/ToolsController.php index 8ce2284ce..9d7d7cc03 100644 --- a/formwork/src/Panel/Controllers/ToolsController.php +++ b/formwork/src/Panel/Controllers/ToolsController.php @@ -40,7 +40,7 @@ public function backups(): Response return $this->forward(ErrorsController::class, 'forbidden'); } - $backupper = new Backupper([...$this->config->get('system.backup'), 'hostname' => $this->request->host()]); + $backupper = new Backupper([...$this->config->getArray('system.backup'), 'hostname' => $this->request->host()]); $backups = Arr::map($backupper->getBackups(), fn(string $path, int $timestamp): array => [ 'name' => basename($path), @@ -100,7 +100,7 @@ public function info(): Response $warnings = []; - if ($this->config->get('system.debug.enabled')) { + if ($this->config->getBool('system.debug.enabled')) { $warnings[] = 'Debug mode enabled, remember to turn it off in production'; } diff --git a/formwork/src/Panel/Controllers/UpdatesController.php b/formwork/src/Panel/Controllers/UpdatesController.php index 096b2e8ba..4b775fce0 100644 --- a/formwork/src/Panel/Controllers/UpdatesController.php +++ b/formwork/src/Panel/Controllers/UpdatesController.php @@ -49,8 +49,8 @@ public function update(Updater $updater, AbstractCache $cache): JsonResponse|Res return $this->forward(ErrorsController::class, 'forbidden'); } - if ($this->config->get('system.updates.backupBefore')) { - $backupper = new Backupper([...$this->config->get('system.backup'), 'hostname' => $this->request->host()]); + if ($this->config->getBool('system.updates.backupBefore')) { + $backupper = new Backupper([...$this->config->getArray('system.backup'), 'hostname' => $this->request->host()]); try { $backupper->backup(); } catch (TranslatedException) { @@ -66,7 +66,7 @@ public function update(Updater $updater, AbstractCache $cache): JsonResponse|Res 'status' => $this->translate('panel.updates.status.cannotInstall'), ]); } - if ($this->config->get('system.cache.enabled')) { + if ($this->config->getBool('system.cache.enabled')) { $cache->clear(); } return JsonResponse::success($this->translate('panel.updates.installed'), data: [ diff --git a/formwork/src/Panel/Controllers/UsersController.php b/formwork/src/Panel/Controllers/UsersController.php index 9a104a9a6..9d84ed412 100644 --- a/formwork/src/Panel/Controllers/UsersController.php +++ b/formwork/src/Panel/Controllers/UsersController.php @@ -219,7 +219,7 @@ public function profile(RouteParams $routeParams): Response */ public function images(RouteParams $routeParams): Response { - $path = FileSystem::joinPaths($this->config->get('system.users.paths.images'), $routeParams->get('image')); + $path = FileSystem::joinPaths($this->config->getString('system.users.paths.images'), $routeParams->get('image')); if (FileSystem::isFile($path, assertExists: false)) { return new FileResponse($path, headers: ['Cache-Control' => 'private, max-age=31536000, immutable'], autoEtag: true, autoLastModified: true); @@ -233,7 +233,7 @@ public function images(RouteParams $routeParams): Response */ private function uploadUserImage(Field $field): ?Image { - $imagesPath = FileSystem::joinPaths($this->config->get('system.users.paths.images')); + $imagesPath = FileSystem::joinPaths($this->config->getString('system.users.paths.images')); $files = $field->isMultiple() ? $field->value() : [$field->value()]; @@ -252,7 +252,7 @@ private function uploadUserImage(Field $field): ?Image return null; } - $userImageSize = $this->config->get('system.panel.userImageSize'); + $userImageSize = $this->config->getInt('system.panel.userImageSize'); // Square off uploaded image $file->square($userImageSize)->save(); diff --git a/formwork/src/Panel/Modals/ModalFactory.php b/formwork/src/Panel/Modals/ModalFactory.php index 1546cfd1d..3b8a30ff4 100644 --- a/formwork/src/Panel/Modals/ModalFactory.php +++ b/formwork/src/Panel/Modals/ModalFactory.php @@ -21,7 +21,7 @@ public function __construct( */ public function make(string $id): Modal { - $path = FileSystem::joinPaths($this->config->get('system.panel.paths.modals'), $id . '.yaml'); + $path = FileSystem::joinPaths($this->config->getString('system.panel.paths.modals'), $id . '.yaml'); $data = FileSystem::exists($path) ? Yaml::parseFile($path) : []; diff --git a/formwork/src/Panel/Panel.php b/formwork/src/Panel/Panel.php index a2ebcad4f..1b5be24bf 100644 --- a/formwork/src/Panel/Panel.php +++ b/formwork/src/Panel/Panel.php @@ -69,7 +69,7 @@ public function user(): User */ public function path(): string { - return $this->config->get('system.panel.path'); + return $this->config->getString('system.panel.path'); } /** @@ -85,7 +85,7 @@ public function uri(string $route = ''): string */ public function panelRoot(): string { - return Uri::normalize(Str::append($this->config->get('system.panel.root'), '/')); + return Uri::normalize(Str::append($this->config->getString('system.panel.root'), '/')); } /** @@ -122,7 +122,7 @@ public function navigation(): NavigationItemCollection $translation = $this->translations->getCurrent(); $this->navigation = NavigationItemCollection::fromArray( - $this->container->call(require $this->config->get('system.panel.config.navigation'), [ + $this->container->call(require $this->config->getString('system.panel.config.navigation'), [ 'translation' => $translation, ]) ); @@ -233,7 +233,7 @@ public function availableTranslations(): array return $translations; } - $path = $this->config->get('system.translations.paths.panel'); + $path = $this->config->getString('system.translations.paths.panel'); foreach (FileSystem::listFiles($path) as $file) { if (FileSystem::extension($file) === 'yaml') { @@ -262,7 +262,7 @@ public function getCsrfTokenName(): string */ public function getAppConfig(): array { - return $this->container->call(require $this->config->get('system.panel.config.app'), [ + return $this->container->call(require $this->config->getString('system.panel.config.app'), [ 'translation' => $this->translations->getCurrent(), ]); } @@ -274,6 +274,6 @@ private function colorSchemeOption(): ColorScheme { return $this->isLoggedIn() ? $this->user()->colorScheme() - : ColorScheme::from($this->config->get('system.panel.colorScheme')); + : ColorScheme::from($this->config->getString('system.panel.colorScheme')); } } diff --git a/formwork/src/Parsers/Extensions/CommonMark/ImageAltProcessor.php b/formwork/src/Parsers/Extensions/CommonMark/ImageAltProcessor.php index ee32202a7..390566f34 100644 --- a/formwork/src/Parsers/Extensions/CommonMark/ImageAltProcessor.php +++ b/formwork/src/Parsers/Extensions/CommonMark/ImageAltProcessor.php @@ -2,6 +2,7 @@ namespace Formwork\Parsers\Extensions\CommonMark; +use Formwork\Cms\Site; use League\CommonMark\Event\DocumentParsedEvent; use League\CommonMark\Extension\CommonMark\Node\Inline\Image; use League\Config\ConfigurationInterface; @@ -19,12 +20,15 @@ public function __invoke(DocumentParsedEvent $documentParsedEvent): void continue; } + /** @var string $baseRoute */ $baseRoute = $this->configuration->get('formwork/baseRoute'); + /** @var Site $site */ $site = $this->configuration->get('formwork/site'); $uri = $node->getUrl(); + /** @var string $key */ $key = $this->configuration->get('formwork/imageAltProperty'); $alt = $site->findPage($baseRoute)?->files()->get($uri)?->get($key); diff --git a/formwork/src/Plugins/Controllers/AssetsController.php b/formwork/src/Plugins/Controllers/AssetsController.php index 8c968db55..76cf168c5 100644 --- a/formwork/src/Plugins/Controllers/AssetsController.php +++ b/formwork/src/Plugins/Controllers/AssetsController.php @@ -29,7 +29,7 @@ public function __construct( */ public function asset(RouteParams $routeParams): Response { - $path = FileSystem::joinPaths($this->config->get('system.plugins.path'), $this->plugin->id(), 'assets', $routeParams->get('type'), Path::resolve($routeParams->get('file'), '/', DIRECTORY_SEPARATOR)); + $path = FileSystem::joinPaths($this->config->getString('system.plugins.path'), $this->plugin->id(), 'assets', $routeParams->get('type'), Path::resolve($routeParams->get('file'), '/', DIRECTORY_SEPARATOR)); if (FileSystem::isFile($path, assertExists: false)) { $headers = ($this->request->query()->has('v')) diff --git a/formwork/src/Plugins/Plugin.php b/formwork/src/Plugins/Plugin.php index 6f7cf5b59..c8e949d9d 100644 --- a/formwork/src/Plugins/Plugin.php +++ b/formwork/src/Plugins/Plugin.php @@ -114,7 +114,7 @@ final public function initialize(): void */ final public function isEnabled(): bool { - return $this->app->config()->get("plugins.{$this->name()}.enabled", false); + return $this->app->config()->getBool("plugins.{$this->name()}.enabled", false); } /** @@ -177,6 +177,7 @@ protected function loadManifest(): void { $manifestPath = FileSystem::joinPaths($this->path, 'plugin.yaml'); + /** @var array $data */ $data = FileSystem::isFile($manifestPath, assertExists: false) ? Yaml::parseFile($manifestPath) : []; diff --git a/formwork/src/Plugins/Plugins.php b/formwork/src/Plugins/Plugins.php index ab7988842..f1c1ef6b4 100644 --- a/formwork/src/Plugins/Plugins.php +++ b/formwork/src/Plugins/Plugins.php @@ -71,7 +71,7 @@ public function initializeEnabled(): void throw new UnexpectedValueException('Unexpected non-string plugin name'); } - if (!$this->config->get("plugins.{$name}.enabled")) { + if (!$this->config->getBool("plugins.{$name}.enabled", false)) { continue; } diff --git a/formwork/src/Services/Loaders/AssetsServiceLoader.php b/formwork/src/Services/Loaders/AssetsServiceLoader.php index 2af9c8c68..4590e0b61 100644 --- a/formwork/src/Services/Loaders/AssetsServiceLoader.php +++ b/formwork/src/Services/Loaders/AssetsServiceLoader.php @@ -31,7 +31,7 @@ public function onResolved(object $service, Container $container): void // Configure template assets namespace $service->setResolutionPaths([ 'template' => [ - 'path' => $this->config->get('system.templates.path') . '/assets', + 'path' => $this->config->getString('system.templates.path') . '/assets', 'uri' => $this->site->uri('/site/templates/assets/', includeLanguage: false), ], ]); diff --git a/formwork/src/Services/Loaders/AuthenticationServiceLoader.php b/formwork/src/Services/Loaders/AuthenticationServiceLoader.php index 849328d11..d657d8073 100644 --- a/formwork/src/Services/Loaders/AuthenticationServiceLoader.php +++ b/formwork/src/Services/Loaders/AuthenticationServiceLoader.php @@ -22,9 +22,9 @@ public function __construct( public function load(Container $container): Authenticator { $container->define(RateLimiter::class) - ->parameter('registry', new Registry(FileSystem::joinPaths($this->config->get('system.authentication.registryPath'), 'accessAttempts.json'))) - ->parameter('limit', $this->config->get('system.authentication.limits.maxAttempts')) - ->parameter('resetTime', $this->config->get('system.authentication.limits.resetTime')); + ->parameter('registry', new Registry(FileSystem::joinPaths($this->config->getString('system.authentication.registryPath'), 'accessAttempts.json'))) + ->parameter('limit', $this->config->getInt('system.authentication.limits.maxAttempts')) + ->parameter('resetTime', $this->config->getInt('system.authentication.limits.resetTime')); return $container->build(Authenticator::class); } diff --git a/formwork/src/Services/Loaders/ConfigServiceLoader.php b/formwork/src/Services/Loaders/ConfigServiceLoader.php index 780d9ce27..cce68d45d 100644 --- a/formwork/src/Services/Loaders/ConfigServiceLoader.php +++ b/formwork/src/Services/Loaders/ConfigServiceLoader.php @@ -47,10 +47,10 @@ public function load(Container $container): Config } } - date_default_timezone_set($config->get('system.date.timezone')); + date_default_timezone_set($config->getString('system.date.timezone')); - $this->request->session()->setPath($config->get('system.session.path')); - $this->request->session()->setDuration($config->get('system.session.duration')); + $this->request->session()->setPath($config->getString('system.session.path')); + $this->request->session()->setDuration($config->getInt('system.session.duration')); return $config; } diff --git a/formwork/src/Services/Loaders/LoggerServiceLoader.php b/formwork/src/Services/Loaders/LoggerServiceLoader.php index 4d7440b18..934225dd8 100644 --- a/formwork/src/Services/Loaders/LoggerServiceLoader.php +++ b/formwork/src/Services/Loaders/LoggerServiceLoader.php @@ -27,7 +27,7 @@ public function __construct( public function load(Container $container): Logger { $logger = $container->build(Logger::class); - foreach ($this->config->get('system.logs.handlers', []) as $handlerConfig) { + foreach ($this->config->getArray('system.logs.handlers', []) as $handlerConfig) { $logger->addHandler($this->buildHandler($handlerConfig)); } diff --git a/formwork/src/Services/Loaders/PanelServiceLoader.php b/formwork/src/Services/Loaders/PanelServiceLoader.php index 6b5f577da..0c649b5a9 100644 --- a/formwork/src/Services/Loaders/PanelServiceLoader.php +++ b/formwork/src/Services/Loaders/PanelServiceLoader.php @@ -49,19 +49,19 @@ public function load(Container $container): Panel } $container->define(RateLimiter::class) - ->parameter('registry', new Registry(FileSystem::joinPaths($this->config->get('system.authentication.registryPath'), 'accessAttempts.json'))) - ->parameter('limit', $this->config->get('system.panel.loginAttempts', $this->config->get('system.authentication.limits.maxAttempts'))) - ->parameter('resetTime', $this->config->get('system.panel.loginResetTime', $this->config->get('system.authentication.limits.resetTime'))); + ->parameter('registry', new Registry(FileSystem::joinPaths($this->config->getString('system.authentication.registryPath'), 'accessAttempts.json'))) + ->parameter('limit', $this->config->getInt('system.panel.loginAttempts', $this->config->getInt('system.authentication.limits.maxAttempts'))) + ->parameter('resetTime', $this->config->getInt('system.panel.loginResetTime', $this->config->getInt('system.authentication.limits.resetTime'))); $container->resolve(RateLimiter::class); } $container->define(Updater::class) - ->parameter('options', $this->config->get('system.updates')); + ->parameter('options', $this->config->getArray('system.updates')); if ($this->config->has('system.panel.sessionTimeout')) { trigger_error('The "system.panel.sessionTimeout" configuration option (in minutes) is deprecated since Formwork 2.3.0. Use "system.session.duration" (in seconds) instead.', E_USER_DEPRECATED); - $this->request->session()->setDuration($this->config->get('system.panel.sessionTimeout') * 60); + $this->request->session()->setDuration($this->config->getInt('system.panel.sessionTimeout') * 60); } $container->define(ModalFactory::class); @@ -77,17 +77,17 @@ public function load(Container $container): Panel */ public function onResolved(object $service, Container $container): void { - $this->viewFactory->setResolutionPaths(['panel' => $this->config->get('system.views.paths.panel')]); - $this->viewFactory->setMethods($container->call(require $this->config->get('system.views.methods.panel'))); + $this->viewFactory->setResolutionPaths(['panel' => $this->config->getString('system.views.paths.panel')]); + $this->viewFactory->setMethods($container->call(require $this->config->getString('system.views.methods.panel'))); $this->assets->setResolutionPaths(['panel' => [ - 'path' => $this->config->get('system.panel.paths.assets'), + 'path' => $this->config->getString('system.panel.paths.assets'), 'uri' => $service->uri('/assets/'), ]]); - $this->schemes->loadFromPath($this->config->get('system.schemes.paths.panel')); + $this->schemes->loadFromPath($this->config->getString('system.schemes.paths.panel')); - $this->translations->loadFromPath($this->config->get('system.translations.paths.panel')); + $this->translations->loadFromPath($this->config->getString('system.translations.paths.panel')); // Resolve site to avoid panel language to be changed after $container->get(Site::class); @@ -95,7 +95,7 @@ public function onResolved(object $service, Container $container): void if ($service->isLoggedIn()) { $this->translations->setCurrent($service->user()->language()); } else { - $this->translations->setCurrent($this->config->get('system.panel.translation')); + $this->translations->setCurrent($this->config->getString('system.panel.translation')); } if ($service->isLoggedIn()) { diff --git a/formwork/src/Services/Loaders/PluginsServiceLoader.php b/formwork/src/Services/Loaders/PluginsServiceLoader.php index 5e4a1a70e..3eacb8f64 100644 --- a/formwork/src/Services/Loaders/PluginsServiceLoader.php +++ b/formwork/src/Services/Loaders/PluginsServiceLoader.php @@ -31,11 +31,11 @@ public function load(Container $container): Plugins */ public function onResolved(object $service, Container $container): void { - if (!$this->config->get('system.plugins.enabled')) { + if (!$this->config->getBool('system.plugins.enabled')) { return; } - $pluginsPath = $this->config->get('system.plugins.path'); + $pluginsPath = $this->config->getString('system.plugins.path'); if (!FileSystem::isDirectory($pluginsPath, assertExists: false)) { return; diff --git a/formwork/src/Services/Loaders/SchemesServiceLoader.php b/formwork/src/Services/Loaders/SchemesServiceLoader.php index ce8e6a198..c726b437d 100644 --- a/formwork/src/Services/Loaders/SchemesServiceLoader.php +++ b/formwork/src/Services/Loaders/SchemesServiceLoader.php @@ -22,7 +22,7 @@ public function load(Container $container): object $container->define(FieldFactory::class); - DynamicFieldValue::$varsLoader = fn() => $container->call(require $this->config->get('system.fields.dynamic.vars.file')); + DynamicFieldValue::$varsLoader = fn() => $container->call(require $this->config->getString('system.fields.dynamic.vars.file')); return $container->build(Schemes::class); } @@ -32,7 +32,7 @@ public function load(Container $container): object */ public function onResolved(object $service, Container $container): void { - $service->loadFromPath($this->config->get('system.schemes.paths.system')); - $service->loadFromPath($this->config->get('system.schemes.paths.site')); + $service->loadFromPath($this->config->getString('system.schemes.paths.system')); + $service->loadFromPath($this->config->getString('system.schemes.paths.site')); } } diff --git a/formwork/src/Services/Loaders/SiteServiceLoader.php b/formwork/src/Services/Loaders/SiteServiceLoader.php index 02d572061..ea5d4e7b3 100644 --- a/formwork/src/Services/Loaders/SiteServiceLoader.php +++ b/formwork/src/Services/Loaders/SiteServiceLoader.php @@ -15,11 +15,11 @@ public function __construct( public function load(Container $container): Site { - $config = $this->config->get('site'); + $config = $this->config->getArray('site'); return $container->build(Site::class, ['data' => [ ...$config, - 'contentPath' => $this->config->get('system.pages.path'), + 'contentPath' => $this->config->getString('system.pages.path'), ]]); } diff --git a/formwork/src/Services/Loaders/TemplatesServiceLoader.php b/formwork/src/Services/Loaders/TemplatesServiceLoader.php index a085f8525..8d5b2ffdd 100644 --- a/formwork/src/Services/Loaders/TemplatesServiceLoader.php +++ b/formwork/src/Services/Loaders/TemplatesServiceLoader.php @@ -18,7 +18,7 @@ public function __construct( public function load(Container $container): Templates { - $path = $this->config->get('system.templates.path'); + $path = $this->config->getString('system.templates.path'); $templates = []; diff --git a/formwork/src/Services/Loaders/TranslationsServiceLoader.php b/formwork/src/Services/Loaders/TranslationsServiceLoader.php index 575b3fe81..042ad866f 100644 --- a/formwork/src/Services/Loaders/TranslationsServiceLoader.php +++ b/formwork/src/Services/Loaders/TranslationsServiceLoader.php @@ -24,10 +24,10 @@ public function load(Container $container): object */ public function onResolved(object $service, Container $container): void { - $service->loadFromPath($this->config->get('system.translations.paths.system')); + $service->loadFromPath($this->config->getString('system.translations.paths.system')); - if (FileSystem::isDirectory($this->config->get('system.translations.paths.site'), assertExists: false)) { - $service->loadFromPath($this->config->get('system.translations.paths.site')); + if (FileSystem::isDirectory($this->config->getString('system.translations.paths.site'), assertExists: false)) { + $service->loadFromPath($this->config->getString('system.translations.paths.site')); } } } diff --git a/formwork/src/Services/Loaders/UsersServiceLoader.php b/formwork/src/Services/Loaders/UsersServiceLoader.php index 038780180..7882b6d51 100644 --- a/formwork/src/Services/Loaders/UsersServiceLoader.php +++ b/formwork/src/Services/Loaders/UsersServiceLoader.php @@ -42,7 +42,7 @@ public function onResolved(object $service, Container $container): void private function loadRoles(): void { - foreach (FileSystem::listFiles($path = $this->config->get('system.users.paths.roles')) as $file) { + foreach (FileSystem::listFiles($path = $this->config->getString('system.users.paths.roles')) as $file) { /** * @var array{title: string, permissions?: array} */ @@ -55,7 +55,7 @@ private function loadRoles(): void private function loadUsers(): void { - foreach (FileSystem::listFiles($path = $this->config->get('system.users.paths.accounts')) as $file) { + foreach (FileSystem::listFiles($path = $this->config->getString('system.users.paths.accounts')) as $file) { /** * @var array{username: string, fullname: string, hash: string, email: string, language: string, role?: string, image?: string, colorScheme?: string} */ diff --git a/formwork/src/Templates/TemplateFactory.php b/formwork/src/Templates/TemplateFactory.php index fda3e3365..926e1747e 100644 --- a/formwork/src/Templates/TemplateFactory.php +++ b/formwork/src/Templates/TemplateFactory.php @@ -22,7 +22,7 @@ public function __construct( */ public function make(string $name): Template { - $path = $this->config->get('system.templates.path'); + $path = $this->config->getString('system.templates.path'); return $this->container->build(Template::class, [ 'name' => $name, diff --git a/formwork/src/Translations/Translations.php b/formwork/src/Translations/Translations.php index 01a5bb866..d38bb14aa 100644 --- a/formwork/src/Translations/Translations.php +++ b/formwork/src/Translations/Translations.php @@ -89,7 +89,7 @@ public function get(string $code, bool $fallbackIfInvalid = false): Translation $translation = new Translation($code, $data); - if (($this->config->get('system.translations.fallback')) !== $code) { + if (($this->config->getString('system.translations.fallback')) !== $code) { $translation->setFallback($this->getFallback()); } @@ -153,7 +153,7 @@ public function getCurrent(): Translation */ public function getFallback(): Translation { - $fallbackCode = $this->config->get('system.translations.fallback'); + $fallbackCode = $this->config->getString('system.translations.fallback'); return $this->get($fallbackCode); } } diff --git a/formwork/src/Users/User.php b/formwork/src/Users/User.php index da86f083d..2f7a95105 100644 --- a/formwork/src/Users/User.php +++ b/formwork/src/Users/User.php @@ -86,7 +86,7 @@ public function image(): ?Image return $this->image; } - $path = FileSystem::joinPaths($this->config->get('system.users.paths.images'), (string) ($this->data['image'] ?? null)); + $path = FileSystem::joinPaths($this->config->getString('system.users.paths.images'), (string) ($this->data['image'] ?? null)); if (!FileSystem::isFile($path, assertExists: false)) { return $this->image = null; @@ -281,7 +281,7 @@ public function save(): void throw new LogicException('Cannot save a user with no username assigned'); } - Yaml::encodeToFile($this->data, FileSystem::joinPaths($this->config->get('system.users.paths.accounts'), $this->username() . '.yaml')); + Yaml::encodeToFile($this->data, FileSystem::joinPaths($this->config->getString('system.users.paths.accounts'), $this->username() . '.yaml')); } /** @@ -294,7 +294,7 @@ public function delete(): void } // Delete user file - FileSystem::delete(FileSystem::joinPaths($this->config->get('system.users.paths.accounts'), $this->username() . '.yaml')); + FileSystem::delete(FileSystem::joinPaths($this->config->getString('system.users.paths.accounts'), $this->username() . '.yaml')); // Delete user image if exists if ($this->image() !== null) { @@ -334,7 +334,7 @@ protected function load(): void protected function setImage(string|Image|null $image): void { if ($image instanceof Image) { - $imagesPath = FileSystem::joinPaths($this->config->get('system.users.paths.images')); + $imagesPath = FileSystem::joinPaths($this->config->getString('system.users.paths.images')); if (!Str::startsWith($image->path(), $imagesPath)) { throw new LogicException('User image must be located in the user images directory'); diff --git a/formwork/views/errors/partials/debug.php b/formwork/views/errors/partials/debug.php index b30280d67..f1c252c70 100644 --- a/formwork/views/errors/partials/debug.php +++ b/formwork/views/errors/partials/debug.php @@ -4,8 +4,8 @@ $frame) : ?>
attr(['open' => $i === 0]) ?>> - $1', $frame['file']) ?>: - config()->get('system.debug.contextLines', 5)) ?> + $1', $frame['file']) ?>: + config()->getInt('system.debug.contextLines', 5)) ?>
- \ No newline at end of file + diff --git a/panel/config/app.php b/panel/config/app.php index 2fe594a49..2e4afac08 100644 --- a/panel/config/app.php +++ b/panel/config/app.php @@ -13,9 +13,9 @@ 'csrfToken' => $csrfToken->get($panel->getCsrfTokenName()), 'colorScheme' => $panel->compatibleColorSchemes(), 'DateInput' => [ - 'weekStarts' => $config->get('system.date.weekStarts'), - 'dateFormat' => Date::formatToPattern($config->get('system.date.dateFormat')), - 'dateTimeFormat' => Date::formatToPattern($config->get('system.date.datetimeFormat')), + 'weekStarts' => $config->getInt('system.date.weekStarts'), + 'dateFormat' => Date::formatToPattern($config->getString('system.date.dateFormat')), + 'dateTimeFormat' => Date::formatToPattern($config->getString('system.date.datetimeFormat')), 'time' => true, 'labels' => [ 'today' => $translation->translate('date.today'), diff --git a/panel/config/routes/routes.php b/panel/config/routes/routes.php index 1b502cc72..782f9ee17 100644 --- a/panel/config/routes/routes.php +++ b/panel/config/routes/routes.php @@ -359,7 +359,7 @@ 'panel.checkAssets' => [ 'action' => static function (Config $config, ViewFactory $viewFactory) { - $path = $config->get('system.panel.paths.assets'); + $path = $config->getString('system.panel.paths.assets'); $assets = ['css/panel.min.css', 'js/app.min.js']; foreach ($assets as $asset) { diff --git a/panel/views/errors/error.php b/panel/views/errors/error.php index c9c8936dc..1407056ce 100644 --- a/panel/views/errors/error.php +++ b/panel/views/errors/error.php @@ -32,8 +32,8 @@ $frame) : ?>
attr(['open' => $i === 0]) ?>> - $1', $frame['file']) ?>: - config()->get('system.debug.contextLines', 5)) ?> + $1', $frame['file']) ?>: + config()->getInt('system.debug.contextLines', 5)) ?>
diff --git a/panel/views/fields/upload.php b/panel/views/fields/upload.php index 4761768f6..bc7686de1 100644 --- a/panel/views/fields/upload.php +++ b/panel/views/fields/upload.php @@ -11,7 +11,7 @@ 'class' => $this->classes(['form-input', 'form-input-upload', 'is-invalid' => ($field->isValidated() && !$field->isValid()), $field->get('class')]), 'id' => $field->name(), 'name' => $field->formName() . ($field->get('multiple') ? '[]' : ''), - 'accept' => $field->get('accept', implode(', ', $app->config()->get('system.files.allowedExtensions'))), + 'accept' => $field->get('accept', implode(', ', $app->config()->getArray('system.files.allowedExtensions', []))), 'multiple' => $field->get('multiple'), 'required' => false, 'disabled' => $field->isDisabled(),