Skip to content

Commit

Permalink
Merge pull request #613 from getformwork/refactor/remove-app-instance
Browse files Browse the repository at this point in the history
Remove the use of `App::instance()` to avoid global state
  • Loading branch information
giuscris authored Nov 29, 2024
2 parents 8496f84 + f36e01e commit c942d97
Show file tree
Hide file tree
Showing 47 changed files with 373 additions and 308 deletions.
32 changes: 22 additions & 10 deletions formwork/fields/date.php
Original file line number Diff line number Diff line change
@@ -1,31 +1,38 @@
<?php

use Formwork\App;
use Formwork\Fields\Exceptions\ValidationException;
use Formwork\Fields\Field;
use Formwork\Languages\Languages;
use Formwork\Utils\Constraint;
use Formwork\Utils\Date;
use Formwork\Utils\Str;

return function (Languages $languages) {
return function (App $app): array {
return [
'format' => function (Field $field, ?string $format = null, string $type = 'pattern'): string {
'format' => function (Field $field, ?string $format = null, string $type = 'pattern') use ($app): string {
$format ??= $app->config()->get('system.date.dateFormat');
$translation = $app->translations()->getCurrent();

if ($format !== null) {
$format = match (strtolower($type)) {
'pattern' => Date::patternToFormat($format),
'date' => $format,
default => throw new InvalidArgumentException('Invalid date format type')
};
}
return $field->isEmpty() ? '' : Date::formatTimestamp($field->toTimestamp(), $format);
return $field->isEmpty() ? '' : Date::formatTimestamp($field->toTimestamp(), $format, $translation);
},

'toTimestamp' => function (Field $field): ?int {
return $field->isEmpty() ? null : Date::toTimestamp($field->value());
'toTimestamp' => function (Field $field) use ($app): ?int {
$formats = [
$app->config()->get('system.date.dateFormat'),
$app->config()->get('system.date.datetimeFormat'),
];
return $field->isEmpty() ? null : Date::toTimestamp($field->value(), $formats);
},

'toDuration' => function (Field $field) use ($languages): string {
return $field->isEmpty() ? '' : Date::formatTimestampAsDistance($field->toTimestamp(), $languages->current());
'toDuration' => function (Field $field) use ($app): string {
return $field->isEmpty() ? '' : Date::formatTimestampAsDistance($field->toTimestamp(), $app->translations()->getCurrent());
},

'toString' => function (Field $field): string {
Expand All @@ -36,13 +43,18 @@
return $field;
},

'validate' => function (Field $field, $value): ?string {
'validate' => function (Field $field, $value) use ($app): ?string {
if (Constraint::isEmpty($value)) {
return null;
}

$formats = [
$app->config()->get('system.date.dateFormat'),
$app->config()->get('system.date.datetimeFormat'),
];

try {
return date('Y-m-d H:i:s', Date::toTimestamp($value));
return date('Y-m-d H:i:s', Date::toTimestamp($value, $formats));
} catch (InvalidArgumentException $e) {
throw new ValidationException(sprintf('Invalid value for field "%s" of type "%s":%s', $field->name(), $field->type(), Str::after($e->getMessage(), ':')));
}
Expand Down
14 changes: 11 additions & 3 deletions formwork/fields/markdown.php
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
<?php

use Formwork\App;
use Formwork\Fields\Exceptions\ValidationException;
use Formwork\Fields\Field;
use Formwork\Parsers\Markdown;
use Formwork\Site;
use Formwork\Utils\Constraint;
use Formwork\Utils\Str;

return function (Site $site) {
return function (App $app, Site $site) {
return [
'toHTML' => function (Field $field) use ($site): string {
'toHTML' => function (Field $field) use ($app, $site): string {
$currentPage = $site->currentPage();
return Markdown::parse((string) $field->value(), ['baseRoute' => $currentPage !== null ? $currentPage->route() : '/']);
return Markdown::parse(
(string) $field->value(),
[
'site' => $site,
'safeMode' => $app->config()->get('system.pages.content.safeMode'),
'baseRoute' => $currentPage !== null ? $currentPage->route() : '/',
]
);
},

'toString' => function (Field $field): string {
Expand Down
15 changes: 10 additions & 5 deletions formwork/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,28 @@
$currentPage = $app->site()->currentPage();
return Markdown::parse(
$markdown,
['baseRoute' => $currentPage !== null ? $currentPage->route() : '/']
[
'site' => $app->site(),
'safeMode' => $app->config()->get('system.pages.content.safeMode'),
'baseRoute' => $currentPage !== null ? $currentPage->route() : '/',
]
);
},

'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()->get('system.date.dateFormat'),
$app->translations()->getCurrent()
);
},

'datetime' => static function (int $timestamp) use ($app): string {
return Date::formatTimestamp($timestamp, $app->config()->get('system.date.datetimeFormat'));
return Date::formatTimestamp($timestamp, $app->config()->get('system.date.datetimeFormat'), $app->translations()->getCurrent());
},

'timedistance' => static function (int $timestamp): string {
return Date::formatTimestampAsDistance($timestamp);
'timedistance' => static function (int $timestamp) use ($app): string {
return Date::formatTimestampAsDistance($timestamp, $app->translations()->getCurrent());
},

'translate' => fn (string $key, ...$arguments) => $app->translations()->getCurrent()->translate($key, ...$arguments),
Expand Down
10 changes: 10 additions & 0 deletions formwork/src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
use Formwork\Http\Response;
use Formwork\Images\ImageFactory;
use Formwork\Languages\Languages;
use Formwork\Pages\PageCollectionFactory;
use Formwork\Pages\PageFactory;
use Formwork\Pages\PaginationFactory;
use Formwork\Panel\Panel;
use Formwork\Router\Router;
use Formwork\Schemes\Schemes;
Expand Down Expand Up @@ -189,6 +192,12 @@ protected function loadServices(Container $container): void
->loader(SchemesServiceLoader::class)
->alias('schemes');

$container->define(PageFactory::class);

$container->define(PaginationFactory::class);

$container->define(PageCollectionFactory::class);

$container->define(Site::class)
->loader(SiteServiceLoader::class)
->alias('site');
Expand All @@ -201,6 +210,7 @@ protected function loadServices(Container $container): void

$container->define(Statistics::class)
->parameter('path', fn (Config $config) => $config->get('system.statistics.path'))
->parameter('translation', fn (Translations $translations) => $translations->getCurrent())
->alias('statistics');

$container->define(FilesCache::class)
Expand Down
19 changes: 6 additions & 13 deletions formwork/src/Backupper.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@

namespace Formwork;

use Formwork\Config\Config;
use Formwork\Exceptions\TranslatedException;
use Formwork\Utils\FileSystem;
use Formwork\Utils\Uri;
use Formwork\Utils\ZipErrors;
use ZipArchive;

Expand All @@ -16,19 +14,14 @@ class Backupper
*/
protected const string DATE_FORMAT = 'YmdHis';

/**
* Backupper options
*
* @var array<string, mixed>
*/
protected array $options = [];

/**
* Return a new Backupper instance
*
* @param array<mixed> $options
*/
public function __construct(Config $config)
{
$this->options = $config->get('system.backup');
public function __construct(
protected array $options
) {
}

/**
Expand All @@ -47,7 +40,7 @@ public function backup(): string
FileSystem::createDirectory($this->options['path'], recursive: true);
}

$name = sprintf('%s-%s-%s.zip', str_replace([' ', '.'], '-', Uri::host() ?? ''), $this->options['name'], date(self::DATE_FORMAT));
$name = sprintf('%s-%s-%s.zip', str_replace([' ', '.'], '-', $this->options['hostname'] ?? 'unknown-host'), $this->options['name'], date(self::DATE_FORMAT));

$destination = FileSystem::joinPaths($path, $name);

Expand Down
2 changes: 1 addition & 1 deletion formwork/src/Controllers/AbstractController.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ protected function redirectToReferer(
string $base = '/'
): RedirectResponse {
if (
!in_array($this->request->referer(), [null, Uri::current()], true)
!in_array($this->request->referer(), [null, $this->request->absoluteUri()], true)
&& $this->request->validateReferer(Path::join([$this->app->request()->root(), $base]))
) {
return new RedirectResponse($this->request->referer(), $responseStatus, $headers);
Expand Down
9 changes: 0 additions & 9 deletions formwork/src/Exceptions/TranslatedException.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Formwork\Exceptions;

use Exception;
use Formwork\App;

class TranslatedException extends Exception
{
Expand All @@ -27,12 +26,4 @@ public function getLanguageString(): string
{
return $this->languageString;
}

/**
* Get localized message
*/
public function getTranslatedMessage(): string
{
return App::instance()->translations()->getCurrent()->translate($this->languageString);
}
}
6 changes: 4 additions & 2 deletions formwork/src/Fields/Layout/Layout.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Formwork\Fields\Layout;

use Formwork\Translations\Translation;

class Layout
{
/**
Expand All @@ -17,10 +19,10 @@ class Layout
/**
* @param array<string, mixed> $data
*/
public function __construct(array $data)
public function __construct(array $data, Translation $translation)
{
$this->type = $data['type'];
$this->sections = new SectionCollection($data['sections'] ?? []);
$this->sections = new SectionCollection($data['sections'] ?? [], $translation);
}

/** Get layout type
Expand Down
7 changes: 3 additions & 4 deletions formwork/src/Fields/Layout/Section.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

namespace Formwork\Fields\Layout;

use Formwork\App;
use Formwork\Data\Traits\DataGetter;
use Formwork\Translations\Translation;
use Formwork\Utils\Str;

class Section
Expand All @@ -13,7 +13,7 @@ class Section
/**
* @param array<string, mixed> $data
*/
public function __construct(array $data)
public function __construct(array $data, protected Translation $translation)
{
$this->data = $data;
}
Expand All @@ -31,7 +31,6 @@ public function is(string $key, bool $default = false): bool
*/
public function label(): string
{
$translation = App::instance()->translations()->getCurrent();
return Str::interpolate($this->get('label', ''), fn ($key) => $translation->translate($key));
return Str::interpolate($this->get('label', ''), fn ($key) => $this->translation->translate($key));
}
}
5 changes: 3 additions & 2 deletions formwork/src/Fields/Layout/SectionCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Formwork\Fields\Layout;

use Formwork\Data\AbstractCollection;
use Formwork\Translations\Translation;
use Formwork\Utils\Arr;

class SectionCollection extends AbstractCollection
Expand All @@ -14,8 +15,8 @@ class SectionCollection extends AbstractCollection
/**
* @param array<string, array<string, mixed>> $sections
*/
public function __construct(array $sections)
public function __construct(array $sections, Translation $translation)
{
parent::__construct(Arr::map($sections, fn ($section) => new Section($section)));
parent::__construct(Arr::map($sections, fn ($section) => new Section($section, $translation)));
}
}
30 changes: 14 additions & 16 deletions formwork/src/Files/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

namespace Formwork\Files;

use Formwork\App;
use Formwork\Data\Contracts\Arrayable;
use Formwork\Files\Exceptions\FileUriGenerationException;
use Formwork\Model\Attributes\ReadonlyModelProperty;
use Formwork\Model\Model;
use Formwork\Parsers\Yaml;
use Formwork\Schemes\Scheme;
use Formwork\Utils\FileSystem;
use Formwork\Utils\MimeType;
use Formwork\Utils\Str;
Expand All @@ -16,9 +15,9 @@

class File extends Model implements Arrayable, Stringable
{
protected const string MODEL_IDENTIFIER = 'file';
public const string SCHEME_IDENTIFIER = 'files.file';

protected const string SCHEME_IDENTIFIER = 'files.file';
protected const string MODEL_IDENTIFIER = 'file';

/**
* File name
Expand Down Expand Up @@ -79,7 +78,6 @@ public function __construct(protected string $path)
{
$this->name = basename($path);
$this->extension = FileSystem::extension($path);
$this->loadData();
}

public function __toString(): string
Expand Down Expand Up @@ -208,6 +206,14 @@ public function uri(): string
return $this->uriGenerator->generate($this);
}

public function absoluteUri(): string
{
if (!isset($this->uriGenerator)) {
throw new FileUriGenerationException('Cannot generate file absolute uri: generator not set');
}
return $this->uriGenerator->generateAbsolute($this);
}

public function toArray(): array
{
return [
Expand All @@ -220,18 +226,10 @@ public function toArray(): array
];
}

private function loadData(): void
public function setScheme(Scheme $scheme): void
{
$app = App::instance();

$this->scheme = $app->schemes()->get(static::SCHEME_IDENTIFIER);
$this->fields = $this->scheme->fields();

$metadataFile = $this->path . $app->config()->get('system.files.metadataExtension');

$this->data = FileSystem::exists($metadataFile) ? Yaml::parseFile($metadataFile) : [];

$this->fields->setValues($this->data);
$this->scheme = $scheme;
$this->fields = $scheme->fields();
}

/**
Expand Down
Loading

0 comments on commit c942d97

Please sign in to comment.