apply more cs rules for php-cs

This commit is contained in:
2023-10-17 13:27:03 +02:00
parent 0b0cbed9db
commit bc2041cbdd
1485 changed files with 8169 additions and 9620 deletions

View File

@@ -19,7 +19,7 @@ final readonly class CollateAddressWithReferenceOrPostalCode implements CollateA
private const LOG_PREFIX = '[collate addresses] ';
/**
* For the address having an "invented" postal code, find the postal code "reference" with the same code,
* and the most similar name. When two reference code match, we add
* and the most similar name. When two reference code match, we add.
*
* This query intentionally includes also address with reference, as the reference may be wrong.
*/
@@ -77,7 +77,7 @@ final readonly class CollateAddressWithReferenceOrPostalCode implements CollateA
SQL;
/**
* Update the point's address with the:
* Update the point's address with the:.
*
* - address reference point, if the address match the reference with sufficient similarity
* - or the postcal code center
@@ -97,7 +97,6 @@ final readonly class CollateAddressWithReferenceOrPostalCode implements CollateA
SELECT MAX(id) AS max_id FROM chill_main_address;
SQL;
public function __construct(
private Connection $connection,
private LoggerInterface $logger,
@@ -128,15 +127,15 @@ final readonly class CollateAddressWithReferenceOrPostalCode implements CollateA
];
});
} catch (\Throwable $e) {
$this->logger->error(self::LOG_PREFIX . "error while re-collating addresses", [
$this->logger->error(self::LOG_PREFIX.'error while re-collating addresses', [
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString()
'trace' => $e->getTraceAsString(),
]);
throw $e;
}
$this->logger->info(self::LOG_PREFIX . "Collate the addresses with reference", [
$this->logger->info(self::LOG_PREFIX.'Collate the addresses with reference', [
'set_postcode_from_most_similar' => $postCodeSetReferenceFromMostSimilar,
'address_reference_match' => $addressReferenceMatch,
'point_update' => $pointUpdates,

View File

@@ -13,11 +13,8 @@ namespace Chill\MainBundle\Service\AddressGeographicalUnit;
use Chill\MainBundle\Cron\CronJobInterface;
use Chill\MainBundle\Entity\CronJobExecution;
use DateInterval;
use DateTimeImmutable;
use Doctrine\DBAL\Connection;
use Symfony\Component\Clock\ClockInterface;
use UnexpectedValueException;
final readonly class RefreshAddressToGeographicalUnitMaterializedViewCronJob implements CronJobInterface
{
@@ -33,14 +30,14 @@ final readonly class RefreshAddressToGeographicalUnitMaterializedViewCronJob imp
}
if ($cronJobExecution->getKey() !== $this->getKey()) {
throw new UnexpectedValueException();
throw new \UnexpectedValueException();
}
$now = $this->clock->now();
return $cronJobExecution->getLastStart() < $now->sub(new DateInterval('P1D'))
return $cronJobExecution->getLastStart() < $now->sub(new \DateInterval('P1D'))
// introduce a random component to ensure a roll when multiple instances are hosted on same machines
&& random_int(0, 10) === 0;
&& 0 === random_int(0, 10);
}
public function getKey(): string

View File

@@ -30,7 +30,7 @@ class ViewEntityInfoManager
$this->connection->transactional(function (Connection $conn): void {
foreach ($this->vienEntityInfoProviders as $viewProvider) {
foreach ($this->createOrReplaceViewSQL($viewProvider, $viewProvider->getViewName()) as $sql) {
$this->logger->debug("Will execute create view sql", ['sql' => $sql]);
$this->logger->debug('Will execute create view sql', ['sql' => $sql]);
$this->logger->debug($sql);
$conn->executeQuery($sql);
}
@@ -45,7 +45,7 @@ class ViewEntityInfoManager
{
return [
"DROP VIEW IF EXISTS {$viewName}",
sprintf("CREATE OR REPLACE VIEW {$viewName} AS %s", $viewProvider->getViewQuery())
sprintf("CREATE OR REPLACE VIEW {$viewName} AS %s", $viewProvider->getViewQuery()),
];
}
}

View File

@@ -11,10 +11,8 @@ declare(strict_types=1);
namespace Chill\MainBundle\Service\Import;
use Exception;
use League\Csv\Reader;
use League\Csv\Statement;
use RuntimeException;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
@@ -37,10 +35,10 @@ class AddressReferenceBEFromBestAddress
$release = $this->client->request('GET', self::RELEASE)
->toArray();
} catch (TransportExceptionInterface $e) {
throw new RuntimeException('could not get the release definition', 0, $e);
throw new \RuntimeException('could not get the release definition', 0, $e);
}
$asset = array_filter($release['assets'], static fn (array $item) => 'addresses-' . $list . '.' . $lang . '.csv.gz' === $item['name']);
$asset = array_filter($release['assets'], static fn (array $item) => 'addresses-'.$list.'.'.$lang.'.csv.gz' === $item['name']);
return array_values($asset)[0]['browser_download_url'];
}
@@ -52,10 +50,10 @@ class AddressReferenceBEFromBestAddress
$response = $this->client->request('GET', $downloadUrl);
if (200 !== $response->getStatusCode()) {
throw new Exception('Could not download CSV: ' . $response->getStatusCode());
throw new \Exception('Could not download CSV: '.$response->getStatusCode());
}
$tmpname = tempnam(sys_get_temp_dir(), 'php-add-' . $list . $lang);
$tmpname = tempnam(sys_get_temp_dir(), 'php-add-'.$list.$lang);
$file = fopen($tmpname, 'r+b');
foreach ($this->client->stream($response) as $chunk) {
@@ -79,8 +77,8 @@ class AddressReferenceBEFromBestAddress
$record['municipality_objectid'],
$record['postal_info_objectid'],
$record['streetname'],
$record['housenumber'] .($record['boxnumber'] !== '' ? ' bte '. $record['boxnumber'] : ''),
'bestaddress.' . $list,
$record['housenumber'].('' !== $record['boxnumber'] ? ' bte '.$record['boxnumber'] : ''),
'bestaddress.'.$list,
(float) $record['Y'],
(float) $record['X'],
3812

View File

@@ -13,12 +13,7 @@ namespace Chill\MainBundle\Service\Import;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Statement;
use Exception;
use LogicException;
use Psr\Log\LoggerInterface;
use RuntimeException;
use function array_key_exists;
use function count;
final class AddressReferenceBaseImporter
{
@@ -71,16 +66,16 @@ final class AddressReferenceBaseImporter
string $street,
string $streetNumber,
string $source,
?float $lat = null,
?float $lon = null,
?int $srid = null
float $lat = null,
float $lon = null,
int $srid = null
): void {
if (!$this->isInitialized) {
$this->initialize($source);
}
if ($this->currentSource !== $source) {
throw new LogicException('Cannot store addresses from different sources during same import. Execute finalize to commit inserts before changing the source');
throw new \LogicException('Cannot store addresses from different sources during same import. Execute finalize to commit inserts before changing the source');
}
$this->waitingForInsert[] = [
@@ -95,7 +90,7 @@ final class AddressReferenceBaseImporter
$srid,
];
if (100 <= count($this->waitingForInsert)) {
if (100 <= \count($this->waitingForInsert)) {
$this->doInsertPending();
}
}
@@ -122,7 +117,7 @@ final class AddressReferenceBaseImporter
private function doInsertPending(): void
{
if (!array_key_exists($forNumber = count($this->waitingForInsert), $this->cachingStatements)) {
if (!\array_key_exists($forNumber = \count($this->waitingForInsert), $this->cachingStatements)) {
$sql = strtr(self::INSERT, [
'{{ values }}' => implode(
', ',
@@ -130,7 +125,7 @@ final class AddressReferenceBaseImporter
),
]);
$this->logger->debug(self::LOG_PREFIX . ' generated sql for insert', [
$this->logger->debug(self::LOG_PREFIX.' generated sql for insert', [
'sql' => $sql,
'forNumber' => $forNumber,
]);
@@ -142,7 +137,7 @@ final class AddressReferenceBaseImporter
return;
}
$this->logger->debug(self::LOG_PREFIX . ' inserting pending addresses', [
$this->logger->debug(self::LOG_PREFIX.' inserting pending addresses', [
'number' => $forNumber,
'first' => $this->waitingForInsert[0] ?? null,
]);
@@ -153,11 +148,11 @@ final class AddressReferenceBaseImporter
$affected = $statement->executeStatement(array_merge(...$this->waitingForInsert));
if (0 === $affected) {
throw new RuntimeException('no row affected');
throw new \RuntimeException('no row affected');
}
} catch (Exception $e) {
} catch (\Exception $e) {
// in some case, we can add debug code here
//dump($this->waitingForInsert);
// dump($this->waitingForInsert);
throw $e;
} finally {
$this->waitingForInsert = [];
@@ -178,8 +173,8 @@ final class AddressReferenceBaseImporter
'CREATE INDEX idx_ref_add_temp ON reference_address_temp (refid)'
);
//1) Add new addresses
$this->logger->info(self::LOG_PREFIX . 'upsert new addresses');
// 1) Add new addresses
$this->logger->info(self::LOG_PREFIX.'upsert new addresses');
$affected = $this->defaultConnection->executeStatement("INSERT INTO chill_main_address_reference
(id, postcode_id, refid, street, streetnumber, municipalitycode, source, point, createdat, deletedat, updatedat)
SELECT
@@ -198,16 +193,16 @@ final class AddressReferenceBaseImporter
ON CONFLICT (refid, source) DO UPDATE
SET postcode_id = excluded.postcode_id, refid = excluded.refid, street = excluded.street, streetnumber = excluded.streetnumber, municipalitycode = excluded.municipalitycode, source = excluded.source, point = excluded.point, updatedat = NOW(), deletedAt = NULL
");
$this->logger->info(self::LOG_PREFIX . 'addresses upserted', ['upserted' => $affected]);
$this->logger->info(self::LOG_PREFIX.'addresses upserted', ['upserted' => $affected]);
//3) Delete addresses
$this->logger->info(self::LOG_PREFIX . 'soft delete adresses');
// 3) Delete addresses
$this->logger->info(self::LOG_PREFIX.'soft delete adresses');
$affected = $this->defaultConnection->executeStatement('UPDATE chill_main_address_reference
SET deletedat = NOW()
WHERE
chill_main_address_reference.refid NOT IN (SELECT refid FROM reference_address_temp WHERE source LIKE ?)
AND chill_main_address_reference.source LIKE ?
', [$this->currentSource, $this->currentSource]);
$this->logger->info(self::LOG_PREFIX . 'addresses deleted', ['deleted' => $affected]);
$this->logger->info(self::LOG_PREFIX.'addresses deleted', ['deleted' => $affected]);
}
}

View File

@@ -11,12 +11,9 @@ declare(strict_types=1);
namespace Chill\MainBundle\Service\Import;
use Exception;
use League\Csv\Reader;
use League\Csv\Statement;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use UnexpectedValueException;
use function is_int;
class AddressReferenceFromBano
{
@@ -24,8 +21,8 @@ class AddressReferenceFromBano
public function import(string $departementNo): void
{
if (!is_numeric($departementNo) || !is_int((int) $departementNo)) {
throw new UnexpectedValueException('Could not parse this department number');
if (!is_numeric($departementNo) || !\is_int((int) $departementNo)) {
throw new \UnexpectedValueException('Could not parse this department number');
}
$url = "https://bano.openstreetmap.fr/data/bano-{$departementNo}.csv";
@@ -33,7 +30,7 @@ class AddressReferenceFromBano
$response = $this->client->request('GET', $url);
if (200 !== $response->getStatusCode()) {
throw new Exception('Could not download CSV: ' . $response->getStatusCode());
throw new \Exception('Could not download CSV: '.$response->getStatusCode());
}
$file = tmpfile();
@@ -65,7 +62,7 @@ class AddressReferenceFromBano
$record['postcode'],
$record['street'],
$record['streetNumber'],
'BANO.' . $departementNo,
'BANO.'.$departementNo,
(float) $record['lat'],
(float) $record['lon'],
4326

View File

@@ -17,7 +17,7 @@ use Psr\Log\LoggerInterface;
/**
* Mark existing addresses as to be reviewed regarding the
* address reference
* address reference.
*/
final readonly class AddressToReferenceMatcher
{
@@ -61,7 +61,7 @@ final readonly class AddressToReferenceMatcher
private const SUBSTITUTES = [
'{{ to_review }}' => Address::ADDR_REFERENCE_STATUS_TO_REVIEW,
'{{ matching }}' => Address::ADDR_REFERENCE_STATUS_MATCH,
'{{ reviewed }}' => Address::ADDR_REFERENCE_STATUS_REVIEWED
'{{ reviewed }}' => Address::ADDR_REFERENCE_STATUS_REVIEWED,
];
public function __construct(private Connection $connection, private LoggerInterface $logger) {}

View File

@@ -14,11 +14,7 @@ namespace Chill\MainBundle\Service\Import;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Statement;
use Doctrine\DBAL\Types\Types;
use Exception;
use Psr\Log\LoggerInterface;
use RuntimeException;
use function array_key_exists;
use function count;
final class GeographicalUnitBaseImporter
{
@@ -68,7 +64,7 @@ final class GeographicalUnitBaseImporter
string $unitName,
string $unitKey,
string $geomAsWKT,
?int $srid = null
int $srid = null
): void {
$this->initialize();
@@ -81,7 +77,7 @@ final class GeographicalUnitBaseImporter
'srid' => $srid,
];
if (100 <= count($this->waitingForInsert)) {
if (100 <= \count($this->waitingForInsert)) {
$this->doInsertPending();
}
}
@@ -106,13 +102,13 @@ final class GeographicalUnitBaseImporter
private function doInsertPending(): void
{
$forNumber = count($this->waitingForInsert);
$forNumber = \count($this->waitingForInsert);
if (0 === $forNumber) {
return;
}
if (!array_key_exists($forNumber, $this->cachingStatements)) {
if (!\array_key_exists($forNumber, $this->cachingStatements)) {
$sql = strtr(self::INSERT, [
'{{ values }}' => implode(
', ',
@@ -120,7 +116,7 @@ final class GeographicalUnitBaseImporter
),
]);
$this->logger->debug(self::LOG_PREFIX . ' generated sql for insert', [
$this->logger->debug(self::LOG_PREFIX.' generated sql for insert', [
'sql' => $sql,
'forNumber' => $forNumber,
]);
@@ -145,9 +141,9 @@ final class GeographicalUnitBaseImporter
$affected = $statement->executeStatement();
if (0 === $affected) {
throw new RuntimeException('no row affected');
throw new \RuntimeException('no row affected');
}
} catch (Exception $e) {
} catch (\Exception $e) {
throw $e;
} finally {
$this->waitingForInsert = [];
@@ -193,8 +189,8 @@ final class GeographicalUnitBaseImporter
"
);
//1) Add new units
$this->logger->info(self::LOG_PREFIX . 'upsert new units');
// 1) Add new units
$this->logger->info(self::LOG_PREFIX.'upsert new units');
$affected = $this->defaultConnection->executeStatement("INSERT INTO chill_main_geographical_unit
(id, geom, unitname, layer_id, unitrefid)
SELECT
@@ -208,10 +204,10 @@ final class GeographicalUnitBaseImporter
DO UPDATE
SET geom = EXCLUDED.geom, unitname = EXCLUDED.unitname
");
$this->logger->info(self::LOG_PREFIX . 'units upserted', ['upserted' => $affected]);
$this->logger->info(self::LOG_PREFIX.'units upserted', ['upserted' => $affected]);
//3) Delete units
$this->logger->info(self::LOG_PREFIX . 'soft delete adresses');
// 3) Delete units
$this->logger->info(self::LOG_PREFIX.'soft delete adresses');
$affected = $this->defaultConnection->executeStatement('WITH to_delete AS (
SELECT cmgu.id
FROM chill_main_geographical_unit AS cmgu
@@ -221,7 +217,7 @@ final class GeographicalUnitBaseImporter
DELETE FROM chill_main_geographical_unit
WHERE id NOT IN (SELECT id FROM to_delete)
');
$this->logger->info(self::LOG_PREFIX . 'addresses deleted', ['deleted' => $affected]);
$this->logger->info(self::LOG_PREFIX.'addresses deleted', ['deleted' => $affected]);
}
);
}

View File

@@ -13,7 +13,6 @@ namespace Chill\MainBundle\Service\Import;
use League\Csv\Reader;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
@@ -33,7 +32,7 @@ class PostalCodeBEFromBestAddress
$tmpfile = fopen($tmpname, 'r+b');
if (false === $tmpfile) {
throw new RuntimeException('could not create temporary file');
throw new \RuntimeException('could not create temporary file');
}
foreach ($this->client->stream($response) as $chunk) {
@@ -55,11 +54,11 @@ class PostalCodeBEFromBestAddress
gzclose($uncompressedStream);
unlink($tmpname);
$this->logger->info(self::class . ' list of postal code downloaded');
$this->logger->info(self::class.' list of postal code downloaded');
$this->baseImporter->finalize();
$this->logger->info(self::class . ' postal code fetched', ['offset' => $offset ?? 0]);
$this->logger->info(self::class.' postal code fetched', ['offset' => $offset ?? 0]);
}
private function getFileDownloadUrl(string $lang): string
@@ -68,10 +67,10 @@ class PostalCodeBEFromBestAddress
$release = $this->client->request('GET', self::RELEASE)
->toArray();
} catch (TransportExceptionInterface $e) {
throw new RuntimeException('could not get the release definition', 0, $e);
throw new \RuntimeException('could not get the release definition', 0, $e);
}
$postals = array_filter($release['assets'], static fn (array $item) => 'postals.' . $lang . '.csv.gz' === $item['name']);
$postals = array_filter($release['assets'], static fn (array $item) => 'postals.'.$lang.'.csv.gz' === $item['name']);
return array_values($postals)[0]['browser_download_url'];
}

View File

@@ -13,9 +13,6 @@ namespace Chill\MainBundle\Service\Import;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Statement;
use Exception;
use function array_key_exists;
use function count;
/**
* Optimized way to load postal code into database.
@@ -85,14 +82,14 @@ class PostalCodeBaseImporter
$centerSRID,
];
if (100 <= count($this->waitingForInsert)) {
if (100 <= \count($this->waitingForInsert)) {
$this->doInsertPending();
}
}
private function doInsertPending(): void
{
if (!array_key_exists($forNumber = count($this->waitingForInsert), $this->cachingStatements)) {
if (!\array_key_exists($forNumber = \count($this->waitingForInsert), $this->cachingStatements)) {
$sql = strtr(self::QUERY, [
'{{ values }}' => implode(
', ',
@@ -107,9 +104,9 @@ class PostalCodeBaseImporter
try {
$statement->executeStatement(array_merge(...$this->waitingForInsert));
} catch (Exception $e) {
} catch (\Exception $e) {
// in some case, we can add debug code here
//dump($this->waitingForInsert);
// dump($this->waitingForInsert);
throw $e;
} finally {
$this->waitingForInsert = [];

View File

@@ -13,7 +13,6 @@ namespace Chill\MainBundle\Service\Import;
use League\Csv\Reader;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
@@ -33,13 +32,13 @@ class PostalCodeFRFromOpenData
$response = $this->client->request('GET', self::CSV);
if (200 !== $response->getStatusCode()) {
throw new RuntimeException('could not download CSV');
throw new \RuntimeException('could not download CSV');
}
$tmpfile = tmpfile();
if (false === $tmpfile) {
throw new RuntimeException('could not create temporary file');
throw new \RuntimeException('could not create temporary file');
}
foreach ($this->client->stream($response) as $chunk) {
@@ -59,7 +58,7 @@ class PostalCodeFRFromOpenData
$this->baseImporter->finalize();
fclose($tmpfile);
$this->logger->info(self::class . ' postal code fetched', ['offset' => $offset ?? 0]);
$this->logger->info(self::class.' postal code fetched', ['offset' => $offset ?? 0]);
}
private function handleRecord(array $record): void
@@ -74,7 +73,7 @@ class PostalCodeFRFromOpenData
if (str_starts_with($ref, '987')) {
// some differences in French Polynesia
$ref .= '.' . trim((string) $record['Libellé_d_acheminement']);
$ref .= '.'.trim((string) $record['Libellé_d_acheminement']);
}
$this->baseImporter->importCode(

View File

@@ -24,10 +24,10 @@ class ChillMailer implements MailerInterface
public function __construct(private readonly MailerInterface $initial, private readonly LoggerInterface $chillLogger) {}
public function send(RawMessage $message, ?Envelope $envelope = null): void
public function send(RawMessage $message, Envelope $envelope = null): void
{
if ($message instanceof Email) {
$message->subject($this->prefix . $message->getSubject());
$message->subject($this->prefix.$message->getSubject());
}
$this->chillLogger->info('chill email sent', [

View File

@@ -11,8 +11,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\Service\RollingDate;
use DateTimeImmutable;
class RollingDate
{
final public const ALL_T = [
@@ -64,21 +62,21 @@ class RollingDate
final public const T_YEAR_PREVIOUS_START = 'year_previous_start';
/**
* @param string|self::T_* $roll
* @param DateTimeImmutable|null $fixedDate Only to insert if $roll equals @see{self::T_FIXED_DATE}
* @param string|self::T_* $roll
* @param \DateTimeImmutable|null $fixedDate Only to insert if $roll equals @see{self::T_FIXED_DATE}
*/
public function __construct(
private readonly string $roll,
private readonly ?\DateTimeImmutable $fixedDate = null,
private readonly DateTimeImmutable $pivotDate = new DateTimeImmutable('now')
private readonly \DateTimeImmutable $pivotDate = new \DateTimeImmutable('now')
) {}
public function getFixedDate(): ?DateTimeImmutable
public function getFixedDate(): ?\DateTimeImmutable
{
return $this->fixedDate;
}
public function getPivotDate(): DateTimeImmutable
public function getPivotDate(): \DateTimeImmutable
{
return $this->pivotDate;
}

View File

@@ -11,14 +11,9 @@ declare(strict_types=1);
namespace Chill\MainBundle\Service\RollingDate;
use DateInterval;
use DateTimeImmutable;
use LogicException;
use UnexpectedValueException;
class RollingDateConverter implements RollingDateConverterInterface
{
public function convert(?RollingDate $rollingDate): ?DateTimeImmutable
public function convert(?RollingDate $rollingDate): ?\DateTimeImmutable
{
if (null === $rollingDate) {
return null;
@@ -29,62 +24,62 @@ class RollingDateConverter implements RollingDateConverterInterface
return $this->toBeginOfMonth($rollingDate->getPivotDate());
case RollingDate::T_MONTH_NEXT_START:
return $this->toBeginOfMonth($rollingDate->getPivotDate()->add(new DateInterval('P1M')));
return $this->toBeginOfMonth($rollingDate->getPivotDate()->add(new \DateInterval('P1M')));
case RollingDate::T_MONTH_PREVIOUS_START:
return $this->toBeginOfMonth($rollingDate->getPivotDate()->sub(new DateInterval('P1M')));
return $this->toBeginOfMonth($rollingDate->getPivotDate()->sub(new \DateInterval('P1M')));
case RollingDate::T_QUARTER_CURRENT_START:
return $this->toBeginOfQuarter($rollingDate->getPivotDate());
case RollingDate::T_QUARTER_NEXT_START:
return $this->toBeginOfQuarter($rollingDate->getPivotDate()->add(new DateInterval('P3M')));
return $this->toBeginOfQuarter($rollingDate->getPivotDate()->add(new \DateInterval('P3M')));
case RollingDate::T_QUARTER_PREVIOUS_START:
return $this->toBeginOfQuarter($rollingDate->getPivotDate()->sub(new DateInterval('P3M')));
return $this->toBeginOfQuarter($rollingDate->getPivotDate()->sub(new \DateInterval('P3M')));
case RollingDate::T_WEEK_CURRENT_START:
return $this->toBeginOfWeek($rollingDate->getPivotDate());
case RollingDate::T_WEEK_NEXT_START:
return $this->toBeginOfWeek($rollingDate->getPivotDate()->add(new DateInterval('P1W')));
return $this->toBeginOfWeek($rollingDate->getPivotDate()->add(new \DateInterval('P1W')));
case RollingDate::T_WEEK_PREVIOUS_START:
return $this->toBeginOfWeek($rollingDate->getPivotDate()->sub(new DateInterval('P1W')));
return $this->toBeginOfWeek($rollingDate->getPivotDate()->sub(new \DateInterval('P1W')));
case RollingDate::T_YEAR_CURRENT_START:
return $this->toBeginOfYear($rollingDate->getPivotDate());
case RollingDate::T_YEAR_PREVIOUS_START:
return $this->toBeginOfYear($rollingDate->getPivotDate()->sub(new DateInterval('P1Y')));
return $this->toBeginOfYear($rollingDate->getPivotDate()->sub(new \DateInterval('P1Y')));
case RollingDate::T_YEAR_NEXT_START:
return $this->toBeginOfYear($rollingDate->getPivotDate()->add(new DateInterval('P1Y')));
return $this->toBeginOfYear($rollingDate->getPivotDate()->add(new \DateInterval('P1Y')));
case RollingDate::T_TODAY:
return $rollingDate->getPivotDate();
case RollingDate::T_FIXED_DATE:
if (null === $rollingDate->getFixedDate()) {
throw new LogicException('You must provide a fixed date when selecting a fixed date');
throw new \LogicException('You must provide a fixed date when selecting a fixed date');
}
return $rollingDate->getFixedDate();
default:
throw new UnexpectedValueException(sprintf('%s rolling operation not supported', $rollingDate->getRoll()));
throw new \UnexpectedValueException(sprintf('%s rolling operation not supported', $rollingDate->getRoll()));
}
}
private function toBeginOfMonth(DateTimeImmutable $date): DateTimeImmutable
private function toBeginOfMonth(\DateTimeImmutable $date): \DateTimeImmutable
{
return DateTimeImmutable::createFromFormat(
return \DateTimeImmutable::createFromFormat(
'Y-m-d His',
sprintf('%s-%s-01 000000', $date->format('Y'), $date->format('m'))
);
}
private function toBeginOfQuarter(DateTimeImmutable $date): DateTimeImmutable
private function toBeginOfQuarter(\DateTimeImmutable $date): \DateTimeImmutable
{
$month = match ((int) $date->format('n')) {
1, 2, 3 => '01',
@@ -93,26 +88,26 @@ class RollingDateConverter implements RollingDateConverterInterface
10, 11, 12 => '10',
};
return DateTimeImmutable::createFromFormat(
return \DateTimeImmutable::createFromFormat(
'Y-m-d His',
sprintf('%s-%s-01 000000', $date->format('Y'), $month)
);
}
private function toBeginOfWeek(DateTimeImmutable $date): DateTimeImmutable
private function toBeginOfWeek(\DateTimeImmutable $date): \DateTimeImmutable
{
if (1 === $dayOfWeek = (int) $date->format('N')) {
return $date->setTime(0, 0, 0);
}
return $date
->sub(new DateInterval('P' . ($dayOfWeek - 1) . 'D'))
->sub(new \DateInterval('P'.($dayOfWeek - 1).'D'))
->setTime(0, 0, 0);
}
private function toBeginOfYear(DateTimeImmutable $date): DateTimeImmutable
private function toBeginOfYear(\DateTimeImmutable $date): \DateTimeImmutable
{
return DateTimeImmutable::createFromFormat(
return \DateTimeImmutable::createFromFormat(
'Y-m-d His',
sprintf('%s-01-01 000000', $date->format('Y'))
);

View File

@@ -11,13 +11,10 @@ declare(strict_types=1);
namespace Chill\MainBundle\Service\RollingDate;
use DateTimeImmutable;
interface RollingDateConverterInterface
{
/**
* @param RollingDate|null $rollingDate
* @return ($rollingDate is null ? null : DateTimeImmutable)
* @return ($rollingDate is null ? null : \DateTimeImmutable)
*/
public function convert(?RollingDate $rollingDate): ?DateTimeImmutable;
public function convert(?RollingDate $rollingDate): ?\DateTimeImmutable;
}