Skip to content

Commit

Permalink
Minor code cleanups (#368)
Browse files Browse the repository at this point in the history
  • Loading branch information
spaze authored Jul 22, 2024
2 parents 1c4492a + b982ed8 commit 7c0986c
Show file tree
Hide file tree
Showing 20 changed files with 104 additions and 99 deletions.
4 changes: 0 additions & 4 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,6 @@ jobs:

check-file-patterns:
runs-on: ubuntu-latest
strategy:
matrix:
php-version:
- "8.3"
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- run: make --directory=site check-file-patterns
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
<tbody id="historie-container" class="hidden">
{formContainer statusHistoryDelete}
<tr n:foreach="$history as $record" class="row">
{var $statusTime = $record->getStatusTime()->format('Y-m-d H:i:s')}
{var $statusTime = $record->getStatusTime()->format(MichalSpacekCz\DateTime\DateTimeFormat::MYSQL)}
<td><code>{$record->getStatus()->value}</code></td>
<td><small>{$statusTime}</small><br></td>
<td class="center">
Expand Down
19 changes: 19 additions & 0 deletions site/app/DateTime/DateTimeFormat.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
declare(strict_types = 1);

namespace MichalSpacekCz\DateTime;

class DateTimeFormat
{

/**
* Same as DATE_RFC3339_EXTENDED except it uses microseconds (`.u`) instead of milliseconds (`.v`).
*/
public const string RFC3339_MICROSECONDS = 'Y-m-d\TH:i:s.uP';

/**
* Same as in \Nette\Database\Drivers\MySqlDriver::formatDateTime() but without the quotes.
*/
public const string MYSQL = 'Y-m-d H:i:s';

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,16 @@

use Exception;
use MichalSpacekCz\ShouldNotHappenException;
use Nette\Utils\DateTime as NetteDateTime;
use Nette\Utils\DateTime;

class DateTime
class DateTimeParser
{

/**
* Same as DATE_RFC3339_EXTENDED except it uses microseconds (`.u`) instead of milliseconds (`.v`).
*/
public const string DATE_RFC3339_MICROSECONDS = 'Y-m-d\TH:i:s.uP';

/**
* Same as in \Nette\Database\Drivers\MySqlDriver::formatDateTime() but without the quotes.
*/
public const string DATE_MYSQL = 'Y-m-d H:i:s';


public function getDaysFromString(string $interval): int
{
$now = new NetteDateTime();
$now = new DateTime();
try {
$then = NetteDateTime::from($interval);
$then = DateTime::from($interval);
} catch (Exception $e) {
throw new ShouldNotHappenException("Cannot create an object from {$interval}", previous: $e);
}
Expand Down
2 changes: 1 addition & 1 deletion site/app/Formatter/TexyFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ private function replace(string $key, Texy $texy, callable $callback): Html

$replacements = [];
foreach ($this->placeholders as $placeholder) {
$replacements[$placeholder::getPlaceholder()] = $placeholder->replace(...);
$replacements[$placeholder::getId()] = $placeholder->replace(...);
}

$result = Strings::replace(
Expand Down
4 changes: 2 additions & 2 deletions site/app/Formatter/TexyFormatterPlaceholder.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
interface TexyFormatterPlaceholder
{

public static function getPlaceholder(): string;
public static function getId(): string;


public function replace(string $placeholder): string;
public function replace(string $value): string;

}
2 changes: 1 addition & 1 deletion site/app/Formatter/TexyPhraseHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ private function getTrainingSuffix(string $training): string
{
$el = Html::el()
->addHtml(Html::el()->setText(' '))
->addHtml(Html::el('small')->setText(sprintf('(**%s:%s**)', TrainingDateTexyFormatterPlaceholder::getPlaceholder(), $training)));
->addHtml(Html::el('small')->setText(sprintf('(**%s:%s**)', TrainingDateTexyFormatterPlaceholder::getId(), $training)));
return $el->render();
}

Expand Down
8 changes: 4 additions & 4 deletions site/app/Formatter/TrainingDateTexyFormatterPlaceholder.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,21 @@ public function __construct(


#[Override]
public static function getPlaceholder(): string
public static function getId(): string
{
return 'TRAINING_DATE';
}


#[Override]
public function replace(string $placeholder): string
public function replace(string $value): string
{
$upcoming = $this->upcomingTrainingDates->getPublicUpcoming();
$dates = [];
if (!isset($upcoming[$placeholder]) || !$upcoming[$placeholder]->getDates()) {
if (!isset($upcoming[$value]) || !$upcoming[$value]->getDates()) {
$dates[] = $this->translator->translate('messages.trainings.nodateyet.short');
} else {
foreach ($upcoming[$placeholder]->getDates() as $date) {
foreach ($upcoming[$value]->getDates() as $date) {
$trainingDate = $date->isTentative()
? $this->dateTimeFormatter->localeIntervalMonth($date->getStart(), $date->getEnd())
: $this->dateTimeFormatter->localeIntervalDay($date->getStart(), $date->getEnd());
Expand Down
12 changes: 6 additions & 6 deletions site/app/Http/Cookies/CookieDescriptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
namespace MichalSpacekCz\Http\Cookies;

use MichalSpacekCz\Application\Theme;
use MichalSpacekCz\DateTime\DateTime;
use MichalSpacekCz\DateTime\DateTimeParser;
use MichalSpacekCz\Formatter\TexyFormatter;
use MichalSpacekCz\ShouldNotHappenException;
use MichalSpacekCz\User\Manager;
Expand All @@ -19,7 +19,7 @@ public function __construct(
private Theme $theme,
private Session $sessionHandler,
private TexyFormatter $texyFormatter,
private DateTime $dateTime,
private DateTimeParser $dateTimeParser,
) {
}

Expand All @@ -40,25 +40,25 @@ public function get(): array
CookieName::PermanentLogin->value,
true,
$this->texyFormatter->translate('messages.cookies.cookie.permanentLogin'),
$this->dateTime->getDaysFromString($this->authenticator->getPermanentLoginCookieLifetime()),
$this->dateTimeParser->getDaysFromString($this->authenticator->getPermanentLoginCookieLifetime()),
),
new CookieDescription(
CookieName::ReturningUser->value,
true,
$this->texyFormatter->translate('messages.cookies.cookie.returningUser'),
$this->dateTime->getDaysFromString($this->authenticator->getReturningUserCookieLifetime()),
$this->dateTimeParser->getDaysFromString($this->authenticator->getReturningUserCookieLifetime()),
),
new CookieDescription(
CookieName::Theme->value,
false,
$this->texyFormatter->translate('messages.cookies.cookie.theme'),
$this->dateTime->getDaysFromString($this->theme->getCookieLifetime()),
$this->dateTimeParser->getDaysFromString($this->theme->getCookieLifetime()),
),
new CookieDescription(
$this->sessionHandler->getName(),
false,
$this->texyFormatter->translate('messages.cookies.cookie.netteSession'),
$this->dateTime->getDaysFromString($cookieLifetime . ' seconds'),
$this->dateTimeParser->getDaysFromString($cookieLifetime . ' seconds'),
),
new CookieDescription(
Helpers::StrictCookieName,
Expand Down
3 changes: 2 additions & 1 deletion site/app/Test/Database/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use DateTime;
use DateTimeInterface;
use MichalSpacekCz\DateTime\DateTimeFormat;
use MichalSpacekCz\Test\WillThrow;
use Nette\Database\Explorer;
use Nette\Database\Row;
Expand Down Expand Up @@ -132,7 +133,7 @@ public function query(string $sql, ...$params): ResultSet
*/
private function formatValue(string|int|bool|DateTimeInterface|null $value): string|int|bool|null
{
return $value instanceof DateTimeInterface ? $value->format('Y-m-d H:i:s') : $value;
return $value instanceof DateTimeInterface ? $value->format(DateTimeFormat::MYSQL) : $value;
}


Expand Down
8 changes: 4 additions & 4 deletions site/app/Tls/Certificate.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

use DateTimeImmutable;
use JsonSerializable;
use MichalSpacekCz\DateTime\DateTime;
use MichalSpacekCz\DateTime\DateTimeFormat;
use MichalSpacekCz\Tls\Exceptions\CertificateException;
use Override;

Expand Down Expand Up @@ -109,13 +109,13 @@ public function jsonSerialize(): array
return [
'commonName' => $this->commonName,
'commonNameExt' => $this->commonNameExt,
'notBefore' => $this->notBefore->format(DateTime::DATE_RFC3339_MICROSECONDS),
'notBefore' => $this->notBefore->format(DateTimeFormat::RFC3339_MICROSECONDS),
'notBeforeTz' => $this->notBefore->getTimezone()->getName(),
'notAfter' => $this->notAfter->format(DateTime::DATE_RFC3339_MICROSECONDS),
'notAfter' => $this->notAfter->format(DateTimeFormat::RFC3339_MICROSECONDS),
'notAfterTz' => $this->notAfter->getTimezone()->getName(),
'expiringThreshold' => $this->expiringThreshold,
'serialNumber' => $this->serialNumber,
'now' => $this->now->format(DateTime::DATE_RFC3339_MICROSECONDS),
'now' => $this->now->format(DateTimeFormat::RFC3339_MICROSECONDS),
'nowTz' => $this->now->getTimezone()->getName(),
];
}
Expand Down
4 changes: 2 additions & 2 deletions site/app/Tls/CertificateFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
namespace MichalSpacekCz\Tls;

use DateTimeImmutable;
use MichalSpacekCz\DateTime\DateTime;
use MichalSpacekCz\DateTime\DateTimeFactory;
use MichalSpacekCz\DateTime\DateTimeFormat;
use MichalSpacekCz\DateTime\DateTimeZoneFactory;
use MichalSpacekCz\DateTime\Exceptions\CannotParseDateTimeException;
use MichalSpacekCz\DateTime\Exceptions\DateTimeException;
Expand Down Expand Up @@ -102,7 +102,7 @@ public function get(
*/
private function createDateTimeImmutable(string $time, string $timeZone): DateTimeImmutable
{
return $this->dateTimeFactory->createFromFormat(DateTime::DATE_RFC3339_MICROSECONDS, $time)->setTimezone($this->dateTimeZoneFactory->get($timeZone));
return $this->dateTimeFactory->createFromFormat(DateTimeFormat::RFC3339_MICROSECONDS, $time)->setTimezone($this->dateTimeZoneFactory->get($timeZone));
}


Expand Down
6 changes: 3 additions & 3 deletions site/app/Tls/Certificates.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
namespace MichalSpacekCz\Tls;

use DateTimeImmutable;
use MichalSpacekCz\DateTime\DateTime;
use MichalSpacekCz\DateTime\DateTimeFormat;
use MichalSpacekCz\DateTime\Exceptions\DateTimeException;
use MichalSpacekCz\Tls\Exceptions\CertificateException;
use MichalSpacekCz\Tls\Exceptions\SomeCertificatesLoggedToFileException;
Expand Down Expand Up @@ -109,8 +109,8 @@ public function log(array $certs, array $failures): array
'OK %s%s from %s to %s',
$cert->getCommonName(),
$cert->getCommonNameExt() ?? '',
$cert->getNotBefore()->format(DateTime::DATE_RFC3339_MICROSECONDS),
$cert->getNotAfter()->format(DateTime::DATE_RFC3339_MICROSECONDS),
$cert->getNotBefore()->format(DateTimeFormat::RFC3339_MICROSECONDS),
$cert->getNotAfter()->format(DateTimeFormat::RFC3339_MICROSECONDS),
), 'cert');
$dbException = $e;
}
Expand Down
2 changes: 1 addition & 1 deletion site/config/services.neon
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ services:
create: MichalSpacekCz\Database\TypedDatabase
autowired: MichalSpacekCz\Database\TypedDatabase
typedDatabase.pulse: MichalSpacekCz\Database\TypedDatabase(@database.pulse.explorer)
- MichalSpacekCz\DateTime\DateTime
- MichalSpacekCz\DateTime\DateTimeFactory
- MichalSpacekCz\DateTime\DateTimeFormatter(@translation.translator::getDefaultLocale())
- MichalSpacekCz\DateTime\DateTimeParser
- MichalSpacekCz\DateTime\DateTimeZoneFactory
- MichalSpacekCz\EasterEgg\CrLfUrlInjections
- MichalSpacekCz\EasterEgg\FourOhFourButFound
Expand Down
30 changes: 15 additions & 15 deletions site/tests/Database/TypedDatabaseTest.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ namespace Database;

use MichalSpacekCz\Database\Exceptions\TypedDatabaseTypeException;
use MichalSpacekCz\Database\TypedDatabase;
use MichalSpacekCz\DateTime\DateTime;
use MichalSpacekCz\DateTime\DateTimeFormat;
use MichalSpacekCz\Test\Database\Database;
use MichalSpacekCz\Test\TestCaseRunner;
use Nette\Utils\DateTime as NetteDateTime;
use Nette\Utils\DateTime;
use Override;
use Tester\Assert;
use Tester\TestCase;
Expand Down Expand Up @@ -108,22 +108,22 @@ class TypedDatabaseTest extends TestCase
public function testFetchPairsListDateTime(): void
{
$this->database->setFetchPairsDefaultResult([
1 => new NetteDateTime('2023-01-01 10:20:30'),
3 => new NetteDateTime('2023-01-03 10:20:30'),
5 => new NetteDateTime('2023-01-05 10:20:30'),
1 => new DateTime('2023-01-01 10:20:30'),
3 => new DateTime('2023-01-03 10:20:30'),
5 => new DateTime('2023-01-05 10:20:30'),
]);
$list = $this->typedDatabase->fetchPairsListDateTime('SELECT foo');
Assert::type('list', $list);
Assert::same('2023-01-01 10:20:30', $list[0]->format(DateTime::DATE_MYSQL));
Assert::same('2023-01-03 10:20:30', $list[1]->format(DateTime::DATE_MYSQL));
Assert::same('2023-01-05 10:20:30', $list[2]->format(DateTime::DATE_MYSQL));
Assert::same('2023-01-01 10:20:30', $list[0]->format(DateTimeFormat::MYSQL));
Assert::same('2023-01-03 10:20:30', $list[1]->format(DateTimeFormat::MYSQL));
Assert::same('2023-01-05 10:20:30', $list[2]->format(DateTimeFormat::MYSQL));
}


public function testFetchPairsListDateTimeInvalidType(): void
{
$this->database->setFetchPairsDefaultResult([
1 => new NetteDateTime('2023-01-01 10:20:30'),
1 => new DateTime('2023-01-01 10:20:30'),
3 => 'foo',
]);
Assert::exception(function (): void {
Expand Down Expand Up @@ -202,15 +202,15 @@ class TypedDatabaseTest extends TestCase

public function testFetchFieldDateTime(): void
{
$this->database->setFetchFieldDefaultResult(new NetteDateTime());
Assert::type(NetteDateTime::class, $this->typedDatabase->fetchFieldDateTime('SELECT 808'));
$this->database->setFetchFieldDefaultResult(new DateTime());
Assert::type(DateTime::class, $this->typedDatabase->fetchFieldDateTime('SELECT 808'));
}


public function testFetchFieldDateTimeNullable(): void
{
$this->database->setFetchFieldDefaultResult(new NetteDateTime());
Assert::type(NetteDateTime::class, $this->typedDatabase->fetchFieldDateTimeNullable('SELECT 808'));
$this->database->setFetchFieldDefaultResult(new DateTime());
Assert::type(DateTime::class, $this->typedDatabase->fetchFieldDateTimeNullable('SELECT 808'));
$this->database->setFetchFieldDefaultResult(null);
Assert::null($this->typedDatabase->fetchFieldIntNullable('SELECT 808'));
}
Expand All @@ -221,7 +221,7 @@ class TypedDatabaseTest extends TestCase
$this->database->setFetchFieldDefaultResult('foo');
Assert::exception(function (): void {
$this->typedDatabase->fetchFieldDateTime('SELECT 808');
}, TypedDatabaseTypeException::class, NetteDateTime::class . ' expected, string given');
}, TypedDatabaseTypeException::class, DateTime::class . ' expected, string given');
}


Expand All @@ -230,7 +230,7 @@ class TypedDatabaseTest extends TestCase
$this->database->setFetchFieldDefaultResult('foo');
Assert::exception(function (): void {
$this->typedDatabase->fetchFieldDateTimeNullable('SELECT 808');
}, TypedDatabaseTypeException::class, NetteDateTime::class . '|null expected, string given');
}, TypedDatabaseTypeException::class, DateTime::class . '|null expected, string given');
}

}
Expand Down
2 changes: 1 addition & 1 deletion site/tests/DateTime/DateTimeFactoryTest.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class DateTimeFactoryTest extends TestCase
$niceDate = '2020-10-10 20:30:40';
$niceDateTime = new DateTimeImmutable("{$niceDate} UTC");
$newDateTime = $this->dateTimeFactory->createFrom($niceDateTime, 'Europe/Prague');
Assert::same($niceDate, $newDateTime->format('Y-m-d H:i:s'));
Assert::same($niceDate, $newDateTime->format(DateTimeFormat::MYSQL));
Assert::same('Europe/Prague', $newDateTime->getTimezone()->getName());
Assert::notSame($niceDateTime->getTimestamp(), $newDateTime->getTimestamp());
}
Expand Down
33 changes: 33 additions & 0 deletions site/tests/DateTime/DateTimeParserTest.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php
declare(strict_types = 1);

namespace MichalSpacekCz\DateTime;

use MichalSpacekCz\Test\TestCaseRunner;
use Tester\Assert;
use Tester\TestCase;

require __DIR__ . '/../bootstrap.php';

/** @testCase */
class DateTimeParserTest extends TestCase
{

public function __construct(
private readonly DateTimeParser $dateTimeParser,
) {
}


public function testGetDaysFromString(): void
{
Assert::same(303, $this->dateTimeParser->getDaysFromString('303 days'));
Assert::same(14, $this->dateTimeParser->getDaysFromString('+14 days'));
Assert::same(0, $this->dateTimeParser->getDaysFromString('now'));
Assert::same(0, $this->dateTimeParser->getDaysFromString('0 days'));
Assert::same(0, $this->dateTimeParser->getDaysFromString('0'));
}

}

TestCaseRunner::run(DateTimeParserTest::class);
Loading

0 comments on commit 7c0986c

Please sign in to comment.