Improve exception types and messages

This commit is contained in:
Giuseppe Criscione 2023-12-26 19:09:19 +01:00
parent 619d3b673e
commit 728de4364c
51 changed files with 167 additions and 95 deletions

View File

@ -1,6 +1,6 @@
<?php
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Http\RedirectResponse;
use Formwork\Http\Request;
use Formwork\Languages\Languages;

View File

@ -5,6 +5,7 @@ namespace Formwork;
use BadMethodCallException;
use Formwork\Cache\AbstractCache;
use Formwork\Cache\FilesCache;
use Formwork\Config\Config;
use Formwork\Fields\Dynamic\DynamicFieldValue;
use Formwork\Files\FileFactory;
use Formwork\Files\FileUriGenerator;

View File

@ -2,6 +2,7 @@
namespace Formwork;
use Formwork\Config\Config;
use Formwork\Exceptions\TranslatedException;
use Formwork\Utils\FileSystem;
use Formwork\Utils\Uri;

View File

@ -155,7 +155,7 @@ class ServeCommand
return "<red>{$status}<red>";
}
throw new UnexpectedValueException();
throw new UnexpectedValueException(sprintf('Unexpected status code %d', $status));
}
protected function formatTime(float $dt): string

View File

@ -1,8 +1,9 @@
<?php
namespace Formwork;
namespace Formwork\Config;
use Exception;
use Formwork\Config\Exceptions\ConfigResolutionException;
use Formwork\Config\Exceptions\UnresolvedConfigException;
use Formwork\Data\Contracts\Arrayable;
use Formwork\Data\Traits\DataArrayable;
use Formwork\Data\Traits\DataGetter;
@ -33,7 +34,7 @@ class Config implements Arrayable
public function get(string $key, mixed $default = null): mixed
{
if (!$this->resolved) {
throw new Exception('Unresolved config');
throw new UnresolvedConfigException('Unresolved config');
}
return $this->baseGet($key, $default);
}
@ -72,13 +73,13 @@ class Config implements Arrayable
$key = $matches[1];
if (!Arr::has($this->data, $key) && !Arr::has($vars, $key)) {
throw new Exception();
throw new ConfigResolutionException(sprintf('Cannot resolve a config value with undefined key or variable "%s"', $key));
}
$value = Arr::get($this->data, $key, Arr::get($vars, $key));
if (!is_string($value)) {
throw new Exception();
throw new ConfigResolutionException(sprintf('Cannot resolve a config value with non-string "%s"', $key));
}
return $value;

View File

@ -0,0 +1,9 @@
<?php
namespace Formwork\Config\Exceptions;
use RuntimeException;
class ConfigResolutionException extends RuntimeException
{
}

View File

@ -0,0 +1,9 @@
<?php
namespace Formwork\Config\Exceptions;
use RuntimeException;
class UnresolvedConfigException extends RuntimeException
{
}

View File

@ -2,7 +2,7 @@
namespace Formwork\Controllers;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Http\FileResponse;
use Formwork\Router\RouteParams;
use Formwork\Utils\Exceptions\FileNotFoundException;
@ -18,6 +18,6 @@ class AssetController
return new FileResponse($path);
}
throw new FileNotFoundException();
throw new FileNotFoundException('Cannot find asset');
}
}

View File

@ -4,7 +4,7 @@ namespace Formwork\Controllers;
use Formwork\App;
use Formwork\Cache\FilesCache;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Http\FileResponse;
use Formwork\Http\RedirectResponse;
use Formwork\Http\Response;

View File

@ -2,7 +2,7 @@
namespace Formwork\Fields;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Services\Container;
use Formwork\Translations\Translations;
use Formwork\Utils\FileSystem;

View File

@ -0,0 +1,9 @@
<?php
namespace Formwork\Files\Exceptions;
use RuntimeException;
class FileUriGenerationException extends RuntimeException
{
}

View File

@ -2,11 +2,12 @@
namespace Formwork\Files;
use Exception;
use Formwork\Data\Contracts\Arrayable;
use Formwork\Files\Exceptions\FileUriGenerationException;
use Formwork\Utils\FileSystem;
use Formwork\Utils\MimeType;
use Formwork\Utils\Str;
use RuntimeException;
class File implements Arrayable
{
@ -167,7 +168,7 @@ class File implements Arrayable
if ($hash = hash_file('sha256', $this->path)) {
return $this->hash = $hash;
}
throw new Exception();
throw new RuntimeException('Cannot calculate file hash');
}
@ -179,7 +180,7 @@ class File implements Arrayable
public function uri(): string
{
if (!isset($this->uriGenerator)) {
throw new Exception('Cannot generate file uri: generator not set');
throw new FileUriGenerationException('Cannot generate file uri: generator not set');
}
return $this->uriGenerator->generate($this);
}

View File

@ -3,9 +3,9 @@
namespace Formwork\Files;
use Closure;
use Exception;
use Formwork\Services\Container;
use Formwork\Utils\FileSystem;
use RuntimeException;
class FileFactory
{
@ -37,7 +37,7 @@ class FileFactory
: $class;
if (!$instance instanceof File) {
throw new Exception(sprintf('Invalid object of type %s, only instances of %s are allowed', get_debug_type($instance), File::class));
throw new RuntimeException(sprintf('Invalid object of type %s, only instances of %s are allowed', get_debug_type($instance), File::class));
}
$instance->setUriGenerator($this->container->get(FileUriGenerator::class));

View File

@ -1,16 +1,16 @@
<?php
namespace Formwork;
namespace Formwork\Files;
use Exception;
use Formwork\Files\File;
use Formwork\Config\Config;
use Formwork\Http\Files\UploadedFile;
use Formwork\Utils\Arr;
use Formwork\Utils\FileSystem;
use Formwork\Utils\MimeType;
use Formwork\Utils\Str;
use RuntimeException;
class Uploader
class FileUploader
{
public function __construct(protected Config $config)
{
@ -30,7 +30,7 @@ class Uploader
$mimeType = MimeType::fromFile($file->tempPath());
if (!in_array($mimeType, $this->allowedMimeTypes(), true)) {
throw new Exception('Invalid mime type');
throw new RuntimeException(sprintf('Invalid mime type %s for file uploads', $mimeType));
}
$filename = Str::slug($name ?? pathinfo($file->clientName(), PATHINFO_FILENAME)) . '.' . MimeType::toExtension($mimeType);

View File

@ -2,8 +2,8 @@
namespace Formwork\Files;
use Exception;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Files\Exceptions\FileUriGenerationException;
use Formwork\Pages\Site;
use Formwork\Router\Router;
use Formwork\Utils\FileSystem;
@ -32,6 +32,6 @@ class FileUriGenerator
return $this->site->uri($uriPath, includeLanguage: false);
}
throw new Exception('Cannot generate URI');
throw new FileUriGenerationException(sprintf('Cannot generate uri for "%s": missing file generator', $file->name()));
}
}

View File

@ -2,8 +2,8 @@
namespace Formwork\Http;
use Exception;
use Formwork\Traits\StaticClass;
use RuntimeException;
use UnexpectedValueException;
class Header
@ -20,7 +20,7 @@ class Header
$pattern = '/"[^"]*"(*SKIP)(*F)|' . preg_quote($separators[0], '/') . '/';
if (($tokens = preg_split($pattern, $header)) === false) {
throw new Exception();
throw new RuntimeException(sprintf('Header splitting failed with error: %s', preg_last_error_msg()));
}
return array_reduce($tokens, function ($result, $token) use ($separators) {

View File

@ -2,12 +2,12 @@
namespace Formwork\Http;
use Exception;
use Formwork\Http\Files\UploadedFile;
use Formwork\Http\Session\Session;
use Formwork\Utils\Path;
use Formwork\Utils\Str;
use Formwork\Utils\Uri;
use InvalidArgumentException;
class Request
{
@ -370,7 +370,7 @@ class Request
$name = strtolower($name);
if (!in_array($name, self::FORWARDED_DIRECTIVES, true)) {
throw new Exception('Invalid forwarded directive');
throw new InvalidArgumentException('Invalid forwarded directive');
}
$result = [];

View File

@ -2,7 +2,8 @@
namespace Formwork\Http;
use Exception;
use InvalidArgumentException;
use UnexpectedValueException;
/**
* @see https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
@ -98,7 +99,7 @@ enum ResponseStatus: string
}
}
throw new Exception('HTTP status code not found');
throw new InvalidArgumentException('HTTP status code not found');
}
public function type(): ResponseStatusType
@ -125,6 +126,6 @@ enum ResponseStatus: string
return ResponseStatusType::ServerError;
}
throw new Exception(sprintf('Invalid response status code: %d', $code));
throw new UnexpectedValueException(sprintf('Invalid response status code: %d', $code));
}
}

View File

@ -2,7 +2,6 @@
namespace Formwork\Http\Session;
use Exception;
use Formwork\Data\Contracts\Arrayable;
use Formwork\Data\Traits\DataArrayable;
use Formwork\Data\Traits\DataMultipleGetter;
@ -10,6 +9,8 @@ use Formwork\Data\Traits\DataMultipleSetter;
use Formwork\Http\Request;
use Formwork\Http\Utils\Cookie;
use Formwork\Utils\Str;
use InvalidArgumentException;
use RuntimeException;
class Session implements Arrayable
{
@ -42,11 +43,11 @@ class Session implements Arrayable
public function __construct(Request $request)
{
if (!extension_loaded('session')) {
throw new Exception('Session not available');
throw new RuntimeException('Sessions extension not available');
}
if (session_status() === PHP_SESSION_DISABLED) {
throw new Exception('Session disabled');
throw new RuntimeException('Sessions disabled by PHP configuration');
}
$this->request = $request;
@ -70,7 +71,7 @@ class Session implements Arrayable
public function start(): void
{
if (session_status() === PHP_SESSION_ACTIVE) {
throw new Exception('Already started');
throw new RuntimeException('Session already started');
}
session_name($this->name);
@ -90,7 +91,7 @@ class Session implements Arrayable
]);
if (($id = session_id()) === false) {
throw new Exception('Cannot get session id');
throw new RuntimeException('Cannot get session id');
}
Cookie::send($this->name, $id, $this->getCookieOptions());
@ -126,7 +127,7 @@ class Session implements Arrayable
}
$newId = session_create_id();
if ($newId === false) {
throw new Exception('Cannot create new session id');
throw new RuntimeException('Cannot create new session id');
}
session_id($newId);
$this->start();
@ -149,7 +150,7 @@ class Session implements Arrayable
public function setName(string $name): void
{
if ($this->started) {
throw new Exception('Session already started');
throw new RuntimeException('Cannot set session name: session already started');
}
$this->name = $name;
@ -161,7 +162,7 @@ class Session implements Arrayable
if ($this->started) {
if (($id = session_id()) === false) {
throw new Exception('Cannot get session id');
throw new RuntimeException('Cannot get session id');
}
Cookie::send($this->name, $id, $this->getCookieOptions());
}
@ -189,7 +190,7 @@ class Session implements Arrayable
}
if (Str::startsWith($key, self::SESSION_MESSAGES_KEY)) {
throw new Exception(sprintf('The key "%s" is reserved', self::SESSION_MESSAGES_KEY));
throw new InvalidArgumentException(sprintf('The key "%s" is reserved', self::SESSION_MESSAGES_KEY));
}
return $this->baseHas($key);
@ -202,7 +203,7 @@ class Session implements Arrayable
}
if (Str::startsWith($key, self::SESSION_MESSAGES_KEY)) {
throw new Exception(sprintf('The key "%s" is reserved', self::SESSION_MESSAGES_KEY));
throw new InvalidArgumentException(sprintf('The key "%s" is reserved', self::SESSION_MESSAGES_KEY));
}
return $this->baseGet($key, $default);
@ -215,7 +216,7 @@ class Session implements Arrayable
}
if (Str::startsWith($key, self::SESSION_MESSAGES_KEY)) {
throw new Exception(sprintf('The key "%s" is reserved', self::SESSION_MESSAGES_KEY));
throw new InvalidArgumentException(sprintf('The key "%s" is reserved', self::SESSION_MESSAGES_KEY));
}
$this->baseRemove($key);
@ -228,7 +229,7 @@ class Session implements Arrayable
}
if (Str::startsWith($key, self::SESSION_MESSAGES_KEY)) {
throw new Exception(sprintf('The key "%s" is reserved', self::SESSION_MESSAGES_KEY));
throw new InvalidArgumentException(sprintf('The key "%s" is reserved', self::SESSION_MESSAGES_KEY));
}
$this->baseSet($key, $value);

View File

@ -70,7 +70,7 @@ class Header
public static function redirect(string $uri, ResponseStatus $status = ResponseStatus::Found): void
{
if ($status->type() !== ResponseStatusType::Redirection) {
throw new InvalidArgumentException();
throw new InvalidArgumentException(sprintf('Invalid response status "%s" for redirection, only 3XX statuses are allowed', $status->value));
}
static::status($status);
static::send('Location', $uri);

View File

@ -2,7 +2,6 @@
namespace Formwork\Http\Utils;
use Exception;
use Formwork\Traits\StaticClass;
use InvalidArgumentException;
@ -53,11 +52,11 @@ class IpAnonymizer
private static function packIPAddress(string $ip): string
{
return inet_pton($ip) ?: throw new Exception('Cannot pack IP address');
return inet_pton($ip) ?: throw new InvalidArgumentException('Cannot pack IP address');
}
private static function unpackIPAddress(string $ip): string
{
return inet_ntop($ip) ?: throw new Exception('Cannot unpack IP address');
return inet_ntop($ip) ?: throw new InvalidArgumentException('Cannot unpack IP address');
}
}

View File

@ -2,9 +2,9 @@
namespace Formwork\Images\Decoder;
use Exception;
use Generator;
use InvalidArgumentException;
use UnexpectedValueException;
class JpegDecoder implements DecoderInterface
{
@ -55,6 +55,6 @@ class JpegDecoder implements DecoderInterface
}
$position += 2;
}
throw new Exception('Segment end not found');
throw new UnexpectedValueException('Segment end not found');
}
}

View File

@ -2,7 +2,7 @@
namespace Formwork\Images;
use Formwork\Config;
use Formwork\Config\Config;
class ImageFactory
{

View File

@ -35,7 +35,7 @@ class ImageInfo implements Arrayable
{
foreach ($info as $key => $value) {
if (!property_exists($this, $key)) {
throw new UnexpectedValueException();
throw new UnexpectedValueException(sprintf('Invalid property "%s"', $key));
}
$this->{$key} = $value;

View File

@ -0,0 +1,9 @@
<?php
namespace Formwork\Pages\Exceptions;
use RuntimeException;
class PageNotFoundException extends RuntimeException
{
}

View File

@ -2,13 +2,13 @@
namespace Formwork\Pages;
use Exception;
use Formwork\App;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Data\Contracts\Arrayable;
use Formwork\Fields\FieldCollection;
use Formwork\Languages\Languages;
use Formwork\Metadata\MetadataCollection;
use Formwork\Pages\Exceptions\PageNotFoundException;
use Formwork\Pages\Templates\TemplateCollection;
use Formwork\Pages\Templates\TemplateFactory;
use Formwork\Pages\Traits\PageData;
@ -391,7 +391,8 @@ class Site implements Arrayable
*/
public function indexPage(): Page
{
return $this->findPage($this->config->get('system.pages.index')) ?? throw new Exception();
return $this->findPage($this->config->get('system.pages.index'))
?? throw new PageNotFoundException('Site index page not found');
}
/**
@ -399,7 +400,8 @@ class Site implements Arrayable
*/
public function errorPage(): Page
{
return $this->findPage($this->config->get('system.pages.error')) ?? throw new Exception();
return $this->findPage($this->config->get('system.pages.error'))
?? throw new PageNotFoundException('Site error page not found');
}
/**

View File

@ -3,7 +3,7 @@
namespace Formwork\Panel\Controllers;
use Formwork\App;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Controllers\AbstractController as BaseAbstractController;
use Formwork\Http\RedirectResponse;
use Formwork\Http\Request;

View File

@ -2,9 +2,9 @@
namespace Formwork\Panel\Controllers;
use Exception;
use Formwork\Exceptions\TranslatedException;
use Formwork\Fields\FieldCollection;
use Formwork\Files\FileUploader;
use Formwork\Http\Files\UploadedFile;
use Formwork\Http\JsonResponse;
use Formwork\Http\RedirectResponse;
@ -17,7 +17,6 @@ use Formwork\Pages\Page;
use Formwork\Pages\Site;
use Formwork\Parsers\Yaml;
use Formwork\Router\RouteParams;
use Formwork\Uploader;
use Formwork\Utils\Arr;
use Formwork\Utils\Date;
use Formwork\Utils\FileSystem;
@ -379,6 +378,23 @@ class PagesController extends AbstractController
return $this->redirect($this->generateRoute('panel.pages.edit', ['page' => $params->get('page')]));
}
public function getFileInfo(RouteParams $params): JsonResponse
{
$this->ensurePermission('pages.getFileInfo');
$page = $this->site()->findPage($params->get('page'));
if ($page === null) {
return JsonResponse::error($this->translate('panel.pages.page.cannotRenameFile.pageNotFound'));
}
if (!$page->files()->has($params->get('filename'))) {
return JsonResponse::error($this->translate('panel.pages.page.cannotRenameFile.fileNotFound'));
}
return JsonResponse::success('Yes!', data: $page->files()->get($params->get('filename'))->toArray());
}
/**
* Create a new page
*/
@ -560,11 +576,11 @@ class PagesController extends AbstractController
*/
protected function processPageUploads(array $files, Page $page): void
{
$uploader = new Uploader($this->config);
$uploader = new FileUploader($this->config);
foreach ($files as $file) {
if (!$file->isUploaded()) {
throw new Exception(sprintf('Cannot upload file "%s"', $file->fieldName()));
throw new RuntimeException(sprintf('Cannot upload file "%s"', $file->fieldName()));
}
$uploadedFile = $uploader->upload($file, $page->path());
// Process JPEG and PNG images according to system options (e.g. quality)

View File

@ -3,6 +3,7 @@
namespace Formwork\Panel\Controllers;
use Formwork\Exceptions\TranslatedException;
use Formwork\Files\FileUploader;
use Formwork\Http\Files\UploadedFile;
use Formwork\Http\RedirectResponse;
use Formwork\Http\RequestMethod;
@ -13,7 +14,6 @@ use Formwork\Panel\Security\Password;
use Formwork\Panel\Users\User;
use Formwork\Parsers\Yaml;
use Formwork\Router\RouteParams;
use Formwork\Uploader;
use Formwork\Utils\FileSystem;
class UsersController extends AbstractController
@ -205,7 +205,7 @@ class UsersController extends AbstractController
{
$imagesPath = FileSystem::joinPaths($this->config->get('system.panel.paths.assets'), '/images/users/');
$uploader = new Uploader($this->config);
$uploader = new FileUploader($this->config);
$uploadedFile = $uploader->upload($file, $imagesPath, FileSystem::randomName());

View File

@ -4,7 +4,7 @@ namespace Formwork\Panel;
use Formwork\App;
use Formwork\Assets;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Http\Request;
use Formwork\Http\Session\MessageType;
use Formwork\Languages\LanguageCodes;

View File

@ -3,7 +3,7 @@
namespace Formwork\Panel\Users;
use Formwork\App;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Data\Contracts\Arrayable;
use Formwork\Http\Request;
use Formwork\Log\Registry;

View File

@ -2,7 +2,6 @@
namespace Formwork\Schemes;
use Exception;
use Formwork\Data\Contracts\Arrayable;
use Formwork\Data\Traits\DataArrayable;
use Formwork\Fields\FieldCollection;
@ -10,6 +9,7 @@ use Formwork\Fields\FieldFactory;
use Formwork\Fields\Layout\Layout;
use Formwork\Translations\Translations;
use Formwork\Utils\Arr;
use InvalidArgumentException;
class Scheme implements Arrayable
{
@ -84,7 +84,7 @@ class Scheme implements Arrayable
protected function extend(Scheme $scheme): void
{
if ($scheme->id === $this->id) {
throw new Exception(sprintf('Scheme "%s" cannot be extended by itself', $this->id));
throw new InvalidArgumentException(sprintf('Scheme "%s" cannot be extended by itself', $this->id));
}
$this->data = array_replace_recursive($scheme->data, $this->data);

View File

@ -3,7 +3,7 @@
namespace Formwork\Services;
use Closure;
use Exception;
use Formwork\Services\Exceptions\ServiceResolutionException;
use LogicException;
use ReflectionClass;
use ReflectionFunction;
@ -128,13 +128,13 @@ class Container
*/
if (in_array($name, $this->resolveStack, true)) {
throw new Exception(sprintf('Already resolving "%s". Resolution stack: "%s"', $name, implode('", "', $this->resolveStack)));
throw new ServiceResolutionException(sprintf('Already resolving "%s". Resolution stack: "%s"', $name, implode('", "', $this->resolveStack)));
}
$this->resolveStack[] = $name;
if (!$this->has($name)) {
throw new Exception();
throw new ServiceResolutionException(sprintf('Trying to resolve undefined service "%s"', $name));
}
$definition = $this->defined[$name];
@ -153,11 +153,11 @@ class Container
if ($loader !== null) {
if ($object !== null) {
throw new Exception('Instantiated object cannot have loaders');
throw new ServiceResolutionException('Instantiated object cannot have loaders');
}
if (!is_subclass_of($loader, ServiceLoaderInterface::class)) {
throw new Exception('Invalid loader');
throw new ServiceResolutionException('Invalid loader');
}
/**

View File

@ -0,0 +1,9 @@
<?php
namespace Formwork\Services\Exceptions;
use RuntimeException;
class ServiceResolutionException extends RuntimeException
{
}

View File

@ -2,7 +2,7 @@
namespace Formwork\Services\Loaders;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Services\Container;
use Formwork\Services\ServiceLoaderInterface;

View File

@ -2,7 +2,7 @@
namespace Formwork\Services\Loaders;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Http\Request;
use Formwork\Languages\Languages;
use Formwork\Services\Container;

View File

@ -2,7 +2,7 @@
namespace Formwork\Services\Loaders;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Http\Request;
use Formwork\Log\Registry;
use Formwork\Panel\Panel;

View File

@ -2,7 +2,7 @@
namespace Formwork\Services\Loaders;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Fields\FieldFactory;
use Formwork\Languages\Languages;
use Formwork\Schemes\Schemes;

View File

@ -2,7 +2,7 @@
namespace Formwork\Services\Loaders;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Languages\Languages;
use Formwork\Pages\Site;
use Formwork\Pages\Templates\TemplateFactory;

View File

@ -2,7 +2,7 @@
namespace Formwork\Services\Loaders;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Languages\Languages;
use Formwork\Services\Container;
use Formwork\Services\ResolutionAwareServiceLoaderInterface;

View File

@ -2,8 +2,8 @@
namespace Formwork\Services;
use Exception;
use Formwork\Utils\Arr;
use LogicException;
class ServiceDefinition
{
@ -56,7 +56,7 @@ class ServiceDefinition
public function loader(string $className): self
{
if (isset($this->object)) {
throw new Exception('Instantiated object cannot have loaders');
throw new LogicException('Instantiated object cannot have loaders');
}
$this->loader = $className;
return $this;

View File

@ -2,7 +2,7 @@
namespace Formwork\Translations;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Parsers\Yaml;
use Formwork\Utils\FileSystem;
use InvalidArgumentException;

View File

@ -4,7 +4,7 @@ namespace Formwork\Updater;
use DateTimeImmutable;
use Formwork\App;
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Http\Client;
use Formwork\Log\Registry;
use Formwork\Parsers\Json;

View File

@ -7,6 +7,7 @@ use Exception;
use Formwork\App;
use Formwork\Traits\StaticClass;
use InvalidArgumentException;
use RuntimeException;
class Date
{
@ -88,7 +89,7 @@ class Date
default => $map[$matches[0]] ?? ''
},
$format
);
) ?? throw new RuntimeException(sprintf('Format conversion failed with error: %s', preg_last_error_msg()));
}
/**
@ -106,7 +107,7 @@ class Date
default => self::PATTERN_TO_DATE_FORMAT[$matches[0]] ?? ''
},
$pattern
);
) ?? throw new RuntimeException(sprintf('Format conversion failed with error: %s', preg_last_error_msg()));
}
/**

View File

@ -248,6 +248,6 @@ class Debug
return sprintf('<span class="__type-name">resource</span>(<span class="__type-name">%s</span> <span class="__note">#%d</span>)', get_resource_type($data), get_resource_id($data));
}
throw new UnexpectedValueException();
throw new UnexpectedValueException('Unexpected value for debug');
}
}

View File

@ -4,6 +4,7 @@ namespace Formwork\Utils;
use Closure;
use Formwork\Traits\StaticClass;
use RuntimeException;
use UnexpectedValueException;
class Str
@ -123,7 +124,8 @@ class Str
*/
public static function slug(string $string): string
{
return preg_replace(['/^-|-$|[^a-z0-9-]/', '/-+/'], ['', '-'], strtr(strtolower($string), self::SLUG_TRANSLATE_MAP));
return preg_replace(['/^-|-$|[^a-z0-9-]/', '/-+/'], ['', '-'], strtr(strtolower($string), self::SLUG_TRANSLATE_MAP))
?? throw new RuntimeException(sprintf('Replacement failed with error: %s', preg_last_error_msg()));
}
/**
@ -189,7 +191,7 @@ class Str
return is_array($data) ? $data[$key] : $data($key);
},
$string
);
) ?? throw new RuntimeException(sprintf('Interpolation sequences matching failed with error: %s', preg_last_error_msg()));
}
/**

View File

@ -34,7 +34,8 @@ class Text
*/
public static function normalizeWhitespace(string $text): string
{
return preg_replace(self::WHITESPACE_REGEX, self::WHITESPACE_SEQUENCE, $text);
return preg_replace(self::WHITESPACE_REGEX, self::WHITESPACE_SEQUENCE, $text)
?? throw new RuntimeException(sprintf('Whitespace replacement failed with error: %s', preg_last_error_msg()));
}
/**

View File

@ -138,7 +138,7 @@ class Uri
public static function queryToArray(?string $uri = null): array
{
$uri ??= static::current();
parse_str(static::query($uri), $array);
parse_str(static::query($uri) ?? '', $array);
return $array;
}
@ -183,7 +183,7 @@ class Uri
}
// Normalize path slashes (leading and trailing separators are trimmed after so that the path
// is always considered relative and we can then add a trailing slash conditionally)
$normalizedPath = '/' . trim(Path::normalize($parts['path']), '/');
$normalizedPath = '/' . trim(Path::normalize($parts['path'] ?? ''), '/');
// Add trailing slash only if the trailing component is not empty or a filename
if ($normalizedPath !== '/' && !Str::contains(basename($normalizedPath), '.')) {
$normalizedPath .= '/';

View File

@ -76,7 +76,7 @@ class View
* @param array<string, mixed> $vars
* @param array<string, Closure> $methods
*/
public function __construct(string $name, array $vars = [], ?string $path = null, array $methods = [])
public function __construct(string $name, array $vars, string $path, array $methods = [])
{
$this->name = $name;
$this->vars = $vars;
@ -162,7 +162,7 @@ class View
$contents = ob_get_clean();
if ($contents === false) {
throw new RenderingException();
throw new RenderingException('Cannot get output buffer contents');
}
return $contents;
@ -200,7 +200,7 @@ class View
$contents = ob_get_clean();
if ($contents === false) {
throw new RenderingException();
throw new RenderingException('Cannot get output buffer contents');
}
$this->blocks[$block] = $contents;
@ -265,7 +265,7 @@ class View
$contents = ob_get_contents();
if ($contents === false) {
throw new RenderingException();
throw new RenderingException('Cannot get output buffer contents');
}
$this->layout->blocks['content'] = $contents;

View File

@ -4,7 +4,7 @@ namespace Formwork\View;
use Closure;
use Formwork\App;
use Formwork\Config;
use Formwork\Config\Config;
class ViewFactory
{

View File

@ -1,6 +1,6 @@
<?php
use Formwork\Config;
use Formwork\Config\Config;
use Formwork\Panel\Panel;
use Formwork\Utils\FileSystem;