Skip to content

Commit

Permalink
Database types cleanup (#388)
Browse files Browse the repository at this point in the history
Some checks in code were irrelevant as some column types are always set,
not nullable. Some type hints were wrong in the code. And some
situations can be prevented.
  • Loading branch information
spaze committed Aug 31, 2024
2 parents a1d1919 + 9326bc6 commit be9eefb
Show file tree
Hide file tree
Showing 15 changed files with 208 additions and 115 deletions.
7 changes: 2 additions & 5 deletions site/app/DateTime/DateTimeFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
use Exception;
use MichalSpacekCz\DateTime\Exceptions\CannotCreateDateTimeObjectException;
use MichalSpacekCz\DateTime\Exceptions\CannotParseDateTimeException;
use MichalSpacekCz\DateTime\Exceptions\InvalidTimezoneException;

readonly class DateTimeFactory
{
Expand All @@ -36,14 +35,12 @@ public function createFromFormat(string $format, string $datetime, ?DateTimeZone


/**
* @throws InvalidTimezoneException
* @throws CannotCreateDateTimeObjectException
*/
public function createFrom(DateTimeInterface $dateTime, ?string $timezoneId = null): DateTimeImmutable
public function createFrom(DateTimeInterface $dateTime, string $timezoneId): DateTimeImmutable
{
$timezone = $timezoneId !== null ? $this->dateTimeZoneFactory->get($timezoneId) : null;
try {
return new DateTimeImmutable($dateTime->format('Y-m-d H:i:s.u'), $timezone);
return new DateTimeImmutable($dateTime->format('Y-m-d H:i:s.u'), $this->dateTimeZoneFactory->get($timezoneId));
} catch (Exception $e) {
throw new CannotCreateDateTimeObjectException($e);
}
Expand Down
12 changes: 6 additions & 6 deletions site/app/Test/Database/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class Database extends Explorer
/** @var array<string, array<int, array<string, string|int|bool|null>>> */
private array $queriesArrayParams = [];

/** @var array<string, int|string|bool|DateTime|null> */
/** @var array<string, int|string|DateTime|null> */
private array $fetchResult = [];

private mixed $fetchFieldDefaultResult = null;
Expand Down Expand Up @@ -156,7 +156,7 @@ public function getParamsArrayForQuery(string $query): array


/**
* @param array<string, int|string|bool|DateTime|null> $fetchResult
* @param array<string, int|string|DateTime|null> $fetchResult
*/
public function setFetchResult(array $fetchResult): void
{
Expand Down Expand Up @@ -230,7 +230,7 @@ public function fetchPairs(string $sql, ...$params): array


/**
* @param list<array<string, int|string|bool|DateTime|null>> $fetchAllDefaultResult
* @param list<array<string, int|string|DateTime|null>> $fetchAllDefaultResult
* @return void
*/
public function setFetchAllDefaultResult(array $fetchAllDefaultResult): void
Expand All @@ -240,7 +240,7 @@ public function setFetchAllDefaultResult(array $fetchAllDefaultResult): void


/**
* @param list<array<string, int|string|bool|DateTime|null>> $fetchAllResult
* @param list<array<string, int|string|DateTime|null>> $fetchAllResult
* @return void
*/
public function addFetchAllResult(array $fetchAllResult): void
Expand All @@ -250,7 +250,7 @@ public function addFetchAllResult(array $fetchAllResult): void


/**
* @param list<array<string, int|string|bool|DateTime|null>> $fetchAllResult
* @param list<array<string, int|string|DateTime|null>> $fetchAllResult
* @return list<Row>
*/
private function getRows(array $fetchAllResult): array
Expand Down Expand Up @@ -278,7 +278,7 @@ public function fetchAll(string $sql, ...$params): array
/**
* Almost the same as Row::from() but with better/simpler types.
*
* @param array<string, int|string|bool|DateTime|null> $array
* @param array<string, int|string|DateTime|null> $array
*/
private function createRow(array $array): Row
{
Expand Down
4 changes: 2 additions & 2 deletions site/app/Training/Applications/TrainingApplication.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public function __construct(
private readonly ?float $priceVat,
private readonly string $priceWithCurrency,
private readonly string $priceVatWithCurrency,
private readonly ?float $discount,
private readonly ?int $discount,
private ?int $invoiceId,
private readonly ?DateTime $paid,
private readonly string $accessToken,
Expand Down Expand Up @@ -323,7 +323,7 @@ public function getPriceVatWithCurrency(): string
}


public function getDiscount(): ?float
public function getDiscount(): ?int
{
return $this->discount;
}
Expand Down
10 changes: 5 additions & 5 deletions site/app/Training/Company/CompanyTraining.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,20 @@ public function __construct(
private int $id,
private string $action,
private Html $name,
private ?Html $description,
private Html $description,
private Html $content,
private ?Html $upsell,
private Html $upsell,
private ?Html $prerequisites,
private ?Html $audience,
private ?int $capacity,
private ?int $price,
private ?int $alternativeDurationPrice,
private int $price,
private int $alternativeDurationPrice,
private ?int $studentDiscount,
private ?Html $materials,
private bool $custom,
private Html $duration,
private Html $alternativeDuration,
private ?Html $alternativeDurationPriceText,
private Html $alternativeDurationPriceText,
private ?int $successorId,
private ?int $discontinuedId,
) {
Expand Down
18 changes: 8 additions & 10 deletions site/app/Training/Company/CompanyTrainings.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,20 +109,18 @@ public function getWithoutPublicUpcoming(): array

private function createFromDatabaseRow(Row $row): CompanyTraining
{
if (isset($row->alternativeDurationPriceText)) {
$price = $this->prices->resolvePriceVat($row->alternativeDurationPrice);
$alternativeDurationPriceText = $this->texyFormatter->translate($row->alternativeDurationPriceText, [
$price->getPriceWithCurrency(),
$price->getPriceVatWithCurrency(),
]);
}
$price = $this->prices->resolvePriceVat($row->alternativeDurationPrice);
$alternativeDurationPriceText = $this->texyFormatter->translate($row->alternativeDurationPriceText, [
$price->getPriceWithCurrency(),
$price->getPriceVatWithCurrency(),
]);
return new CompanyTraining(
$row->id,
$row->action,
$this->texyFormatter->translate($row->name),
$row->description ? $this->texyFormatter->translate($row->description) : null,
$this->texyFormatter->translate($row->description),
$this->texyFormatter->translate($row->content),
$row->upsell ? $this->texyFormatter->translate($row->upsell) : null,
$this->texyFormatter->translate($row->upsell),
$row->prerequisites ? $this->texyFormatter->translate($row->prerequisites) : null,
$row->audience ? $this->texyFormatter->translate($row->audience) : null,
$row->capacity,
Expand All @@ -133,7 +131,7 @@ private function createFromDatabaseRow(Row $row): CompanyTraining
(bool)$row->custom,
$this->texyFormatter->translate($row->duration),
$this->texyFormatter->translate($row->alternativeDuration),
$alternativeDurationPriceText ?? null,
$alternativeDurationPriceText,
$row->successorId,
$row->discontinuedId,
);
Expand Down
15 changes: 14 additions & 1 deletion site/app/Training/Dates/TrainingDateFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function get(Row $row): TrainingDate
$this->lastFreeSeats($row->start, $status),
$row->start,
$row->end,
$row->labelJson ? Json::decode($row->labelJson)->{$this->translator->getDefaultLocale()} : null,
$this->getLabelFromJson($row->labelJson),
$row->labelJson,
(bool)$row->public,
$status,
Expand Down Expand Up @@ -70,4 +70,17 @@ private function lastFreeSeats(DateTime $start, TrainingDateStatus $status): boo
return ($start->diff($now)->days <= self::LAST_FREE_SEATS_THRESHOLD_DAYS && $start > $now && $status !== TrainingDateStatus::Tentative);
}


private function getLabelFromJson(?string $json): ?string
{
if ($json !== null) {
$labels = Json::decode($json);
$label = $labels->{$this->translator->getDefaultLocale()} ?? null;
if (!is_string($label)) {
return null;
}
}
return $label ?? null;
}

}
6 changes: 1 addition & 5 deletions site/psalm-baseline.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<files psalm-version="5.23.1@8471a896ccea3526b26d082f4461eeea467f10a4">
<files psalm-version="5.25.0@01a8eb06b9e9cc6cfb6a320bf9fb14331919d505">
<file src="app/Articles/Articles.php">
<MixedArgument>
<code><![CDATA[$result->slugTags]]></code>
Expand Down Expand Up @@ -666,11 +666,9 @@
</file>
<file src="app/Training/Company/CompanyTrainings.php">
<MixedArgument>
<code><![CDATA[$alternativeDurationPriceText ?? null]]></code>
<code><![CDATA[$row->action]]></code>
<code><![CDATA[$row->alternativeDuration]]></code>
<code><![CDATA[$row->alternativeDurationPrice]]></code>
<code><![CDATA[$row->alternativeDurationPrice]]></code>
<code><![CDATA[$row->alternativeDurationPriceText]]></code>
<code><![CDATA[$row->audience]]></code>
<code><![CDATA[$row->capacity]]></code>
Expand Down Expand Up @@ -698,8 +696,6 @@
<code><![CDATA[$row->end]]></code>
<code><![CDATA[$row->feedbackHref]]></code>
<code><![CDATA[$row->labelJson]]></code>
<code><![CDATA[$row->labelJson]]></code>
<code><![CDATA[$row->labelJson ? Json::decode($row->labelJson)->{$this->translator->getDefaultLocale()} : null]]></code>
<code><![CDATA[$row->note]]></code>
<code><![CDATA[$row->price]]></code>
<code><![CDATA[$row->remoteNotes]]></code>
Expand Down
23 changes: 19 additions & 4 deletions site/tests/DateTime/DateTimeFactoryTest.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ declare(strict_types = 1);
namespace MichalSpacekCz\DateTime;

use DateTimeImmutable;
use MichalSpacekCz\DateTime\Exceptions\CannotCreateDateTimeObjectException;
use MichalSpacekCz\DateTime\Exceptions\CannotParseDateTimeException;
use MichalSpacekCz\DateTime\Exceptions\InvalidTimezoneException;
use MichalSpacekCz\Test\TestCaseRunner;
Expand Down Expand Up @@ -38,10 +39,6 @@ class DateTimeFactoryTest extends TestCase

public function testCreateFrom(): void
{
Assert::exception(function (): void {
$this->dateTimeFactory->createFrom(new DateTimeImmutable(), 'Europe/Brno');
}, InvalidTimezoneException::class, "Invalid timezone 'Europe/Brno'");

$niceDate = '2020-10-10 20:30:40';
$niceDateTime = new DateTimeImmutable("{$niceDate} UTC");
$newDateTime = $this->dateTimeFactory->createFrom($niceDateTime, 'Europe/Prague');
Expand All @@ -50,6 +47,24 @@ class DateTimeFactoryTest extends TestCase
Assert::notSame($niceDateTime->getTimestamp(), $newDateTime->getTimestamp());
}


public function testCreateFromInvalidTimezone(): void
{
$e = Assert::exception(function (): void {
$this->dateTimeFactory->createFrom(new DateTimeImmutable(), 'Europe/Brno');
}, CannotCreateDateTimeObjectException::class, 'Cannot create a DateTime or DateTimeImmutable object');
if (!$e instanceof CannotCreateDateTimeObjectException) {
Assert::fail('Exception is of a wrong type ' . get_debug_type($e));
} else {
$previous = $e->getPrevious();
if (!$previous instanceof InvalidTimeZoneException) {
Assert::fail('Previous exception is of a wrong type ' . get_debug_type($previous));
} else {
Assert::same("Invalid timezone 'Europe/Brno'", $previous->getMessage());
}
}
}

}

TestCaseRunner::run(DateTimeFactoryTest::class);
16 changes: 8 additions & 8 deletions site/tests/Formatter/TexyFormatterTest.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@ class TexyFormatterTest extends TestCase
'name' => 'Bezpečnost PHP aplikací',
'price' => 3490,
'studentDiscount' => null,
'hasCustomPrice' => false,
'hasCustomStudentDiscount' => false,
'hasCustomPrice' => 0,
'hasCustomStudentDiscount' => 0,
'start' => new DateTime('2020-01-05 04:03:02'),
'end' => new DateTime('2020-01-07 04:03:02'),
'labelJson' => '{"cs_CZ": "lej-bl", "en_US": "la-bel"}',
'status' => 'CONFIRMED',
'public' => false,
'remote' => true,
'public' => 0,
'remote' => 1,
'remoteUrl' => null,
'remoteNotes' => null,
'venueId' => 1,
Expand All @@ -80,14 +80,14 @@ class TexyFormatterTest extends TestCase
'name' => 'Bezpečnost PHP aplikací',
'price' => 4490,
'studentDiscount' => null,
'hasCustomPrice' => false,
'hasCustomStudentDiscount' => false,
'hasCustomPrice' => 0,
'hasCustomStudentDiscount' => 0,
'start' => new DateTime('2020-02-05 04:03:02'),
'end' => new DateTime('2020-02-07 04:03:02'),
'labelJson' => '{"cs_CZ": "lej-bl", "en_US": "la-bel"}',
'status' => 'CONFIRMED',
'public' => true,
'remote' => false,
'public' => 1,
'remote' => 0,
'remoteUrl' => null,
'remoteNotes' => null,
'venueId' => 2,
Expand Down
Loading

0 comments on commit be9eefb

Please sign in to comment.