Skip to content

Commit

Permalink
Add static functions to DatabaseData to find information in rows.
Browse files Browse the repository at this point in the history
  • Loading branch information
kloor committed Oct 3, 2022
1 parent bf81463 commit db7ac72
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/Lits/Data/DatabaseData.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

use Lits\Data;
use Lits\Database;
use Lits\Exception\InvalidDataException;
use Lits\Settings;
use Safe\DateTimeImmutable;

abstract class DatabaseData extends Data
{
Expand All @@ -18,4 +20,67 @@ public function __construct(Settings $settings, Database $database)

$this->database = $database;
}

/**
* @param array<string, string|null> $row
* @throws InvalidDataException
*/
protected static function findRowDatetime(
array $row,
string $key
): ?DateTimeImmutable {
if (isset($row[$key])) {
try {
return new DateTimeImmutable($row[$key]);
} catch (\Throwable $exception) {
throw new InvalidDataException(
'The string could not be parsed into a datetime',
0,
$exception
);
}
}

return null;
}

/** @param array<string, string|null> $row */
protected static function findRowBool(array $row, string $key): ?bool
{
if (isset($row[$key])) {
return (bool) $row[$key];
}

return null;
}

/** @param array<string, string|null> $row */
protected static function findRowFloat(array $row, string $key): ?float
{
if (isset($row[$key])) {
return (float) $row[$key];
}

return null;
}

/** @param array<string, string|null> $row */
protected static function findRowInt(array $row, string $key): ?int
{
if (isset($row[$key])) {
return (int) $row[$key];
}

return null;
}

/** @param array<string, string|null> $row */
protected static function findRowString(array $row, string $key): ?string
{
if (isset($row[$key])) {
return \trim($row[$key]);
}

return null;
}
}

0 comments on commit db7ac72

Please sign in to comment.