Skip to content

Commit

Permalink
No Psalmy truthy falsy operatory (#275)
Browse files Browse the repository at this point in the history
Upgrade to Psalm 5.21.1.

Bigger effort because Psalm [5.20.0](https://github.com/vimeo/psalm/releases/tag/5.20.0) reports error for non-strict or empty comparison on truthy/falsy union and I like my `!$stringOrNull`.

- Replace truthy/falsy operands with strict comparison, so no `!$string`, just `$string !== null` etc.
- Replace some `empty()` calls with strict comparisons

In the end of the day I think this is a good thing.
  • Loading branch information
spaze committed Feb 7, 2024
2 parents 75d02eb + 737e015 commit e288905
Show file tree
Hide file tree
Showing 74 changed files with 518 additions and 207 deletions.
3 changes: 2 additions & 1 deletion site/app/Admin/Presenters/BlogPresenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ public function actionDefault(): void
{
$posts = [];
foreach ($this->blogPosts->getAll() as $post) {
$posts[($post->getPublishTime()?->getTimestamp() ?: PHP_INT_MAX) . '|' . $post->getSlug()] = $post;
$timestamp = $post->getPublishTime()?->getTimestamp();
$posts[($timestamp !== null ? $timestamp : PHP_INT_MAX) . '|' . $post->getSlug()] = $post;
}
krsort($posts, SORT_NATURAL);
$this->template->posts = $posts;
Expand Down
2 changes: 1 addition & 1 deletion site/app/Admin/Presenters/InvoicesPresenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function actionUnpaid(): void
$unpaidApplications = $this->trainingApplications->getValidUnpaidByDate($date->getId());
foreach ($unpaidApplications as $application) {
$invoiceId = $application->getInvoiceId();
if ($invoiceId) {
if ($invoiceId !== null) {
$this->allUnpaidInvoiceIds[] = $invoiceId;
}
}
Expand Down
2 changes: 1 addition & 1 deletion site/app/Admin/Presenters/PulsePresenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ protected function createComponentAddPasswordsStorageAlgorithm(): UiForm
{
return $this->passwordsStoragesFormFactory->create(
function (?string $message): never {
if ($message) {
if ($message !== null) {
$this->flashMessage($message);
}
$this->redirect('this');
Expand Down
2 changes: 1 addition & 1 deletion site/app/Admin/Presenters/TalksPresenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public function actionSlides(int $param): void
$this->template->talk = $this->talk;
$this->template->maxSlideUploads = $this->talkSlidesFormFactory->getMaxSlideUploads();
$new = $this->httpInput->getPostArray('new');
$this->template->newCount = $this->newCount = $new ? count($new) : (int)(count($this->slides) === 0);
$this->template->newCount = $this->newCount = $new !== null ? count($new) : (int)(count($this->slides) === 0);
$this->template->dimensions = $this->talkSlides->getSlideDimensions();
}

Expand Down
6 changes: 3 additions & 3 deletions site/app/Admin/Presenters/TrainingsPresenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ public function actionFiles(int $param): void
{
$application = $this->trainingApplications->getApplicationById($param);
$dateId = $application->getDateId();
if (!$dateId) {
if ($dateId === null) {
throw new BadRequestException("The application id '{$param}' should have a training date set");
}
if (!in_array($application->getStatus(), $this->trainingStatuses->getAllowFilesStatuses(), true)) {
Expand Down Expand Up @@ -167,7 +167,7 @@ public function actionApplication(int $param): void
$this->application = $application;

$applicationDateId = $this->application->getDateId();
if ($applicationDateId) {
if ($applicationDateId !== null) {
$training = $this->trainingDates->get($applicationDateId);
$name = $training->getName();
$start = $training->getStart();
Expand Down Expand Up @@ -272,7 +272,7 @@ protected function createComponentApplicationForm(): UiForm
}
return $this->trainingApplicationAdminFactory->create(
function (?int $dateId): never {
if ($dateId) {
if ($dateId !== null) {
$this->redirect('date', $dateId);
} else {
$this->redirect('preliminary');
Expand Down
2 changes: 1 addition & 1 deletion site/app/Application/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ private static function createConfigurator(bool $debugMode, ?string $extraConfig
$configurator->setTempDirectory(self::SITE_DIR . '/temp');

$existingFiles = array_filter(self::getConfigurationFiles($extraConfig, $finalConfig), function (?string $path) {
return $path && is_file($path);
return $path !== null && is_file($path);
});
foreach ($existingFiles as $filename) {
$configurator->addConfig($filename);
Expand Down
8 changes: 4 additions & 4 deletions site/app/Articles/Blog/BlogPostFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,22 +89,22 @@ public function create(
$translationGroupId,
$this->texyFormatter->format($titleTexy, $texy),
$titleTexy,
$leadTexy ? $this->texyFormatter->formatBlock($leadTexy, $texy) : null,
$leadTexy !== null ? $this->texyFormatter->formatBlock($leadTexy, $texy) : null,
$leadTexy,
$this->texyFormatter->formatBlock($textTexy, $texy),
$textTexy,
$published,
$needsPreviewKey,
$previewKey,
$originallyTexy ? $this->texyFormatter->formatBlock($originallyTexy, $texy) : null,
$originallyTexy !== null ? $this->texyFormatter->formatBlock($originallyTexy, $texy) : null,
$originallyTexy,
$ogImage,
$tags,
$slugTags,
$recommended,
$twitterCard,
$this->getHref($slug, $needsPreviewKey ? $previewKey : null, $locale),
$id ? $this->edits->getEdits($id) : [],
$id !== null ? $this->edits->getEdits($id) : [],
$cspSnippets,
$allowedTagsGroups,
$omitExports,
Expand Down Expand Up @@ -154,7 +154,7 @@ private function getHref(string $slug, ?string $previewKey, ?string $locale): st
'slug' => $slug,
'preview' => $previewKey,
];
if (!$locale || $locale === $this->translator->getDefaultLocale()) {
if ($locale === null || $locale === $this->translator->getDefaultLocale()) {
return $this->linkGenerator->link('Www:Post:', $params);
} else {
$links = $this->localeLinkGenerator->links('Www:Post:', $this->localeLinkGenerator->defaultParams($params));
Expand Down
2 changes: 1 addition & 1 deletion site/app/Articles/Blog/BlogPosts.php
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ public function update(BlogPost $post, ?string $editSummary, array $previousSlug
$postId,
);
$editedAt = new DateTime();
if ($editSummary) {
if ($editSummary !== null) {
$timeZone = $editedAt->getTimezone()->getName();
$this->database->query(
'INSERT INTO blog_post_edits',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ class BlogPostDoesNotExistException extends BlogPostException
public function __construct(?int $id = null, ?string $name = null, ?string $previewKey = null, ?Throwable $previous = null)
{
$message = 'Post';
if ($id) {
if ($id !== null) {
$message .= " id {$id}";
}
if ($name) {
if ($name !== null) {
$message .= " name {$name}";
}
if ($previewKey) {
if ($previewKey !== null) {
$message .= " preview key {$previewKey}";
}
parent::__construct("{$message} doesn't exist", previous: $previous);
Expand Down
15 changes: 7 additions & 8 deletions site/app/CompanyInfo/CompanyRegisterAres.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,18 +108,17 @@ private function fetch(string $companyId): string

private function formatStreet(?string $city, ?string $street, ?int $houseNumber, ?int $streetNumber, ?string $streetLetter): ?string
{
$result = $street;
if (empty($result)) {
$result = $city;
}
if (!empty($streetLetter)) {
$result = $street !== null && $street !== '' ? $street : $city;
if ($streetLetter !== null && $streetLetter !== '') {
$streetNumber = ($streetNumber ?? '') . $streetLetter;
}
if (!empty($houseNumber) && !empty($streetNumber)) {
$hasHouseNumber = $houseNumber !== null && $houseNumber !== 0;
$hasStreetNumber = $streetNumber !== null && $streetNumber !== 0;
if ($hasHouseNumber && $hasStreetNumber) {
$result = "{$result} {$houseNumber}/{$streetNumber}";
} elseif (!empty($houseNumber)) {
} elseif ($hasHouseNumber) {
$result = "{$result} {$houseNumber}";
} elseif (!empty($streetNumber)) {
} elseif ($hasStreetNumber) {
$result = "{$result} {$streetNumber}";
}
return $result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class CompanyNotFoundException extends Exception

public function __construct(?int $status = null, ?Throwable $previous = null)
{
parent::__construct($status ? "Invalid status {$status}" : 'Company not found', previous: $previous);
parent::__construct($status !== null ? "Invalid status {$status}" : 'Company not found', previous: $previous);
}

}
2 changes: 1 addition & 1 deletion site/app/DateTime/DateTimeFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function createFromFormat(string $format, string $datetime, ?DateTimeZone
*/
public function createFrom(DateTimeInterface $dateTime, ?string $timezoneId = null): DateTimeImmutable
{
$timezone = $timezoneId ? $this->dateTimeZoneFactory->get($timezoneId) : null;
$timezone = $timezoneId !== null ? $this->dateTimeZoneFactory->get($timezoneId) : null;
try {
return new DateTimeImmutable($dateTime->format('Y-m-d H:i:s.u'), $timezone);
} catch (Exception $e) {
Expand Down
2 changes: 1 addition & 1 deletion site/app/DateTime/DateTimeFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ private function localeDate(DateTimeInterface $start, ?DateTimeInterface $end, s
$formatter->setPattern($format[self::INTERVAL_FORMAT_END]);
$result .= $formatter->format($end);
}
if (!$result) {
if ($result === false) {
throw new RuntimeException("Format '{$type}' using {$locale} has failed");
}
return $result;
Expand Down
2 changes: 1 addition & 1 deletion site/app/EasterEgg/NetteCve202015227.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function rce(string $callback, array $params): NetteCve202015227Rce
$data = [];

$param = $params[$paramNames[$callback]] ?? null;
if (!$param) {
if ($param === null) {
throw new BadRequestException(sprintf("[%s] Empty param '%s' for callback '%s'", __CLASS__, $paramNames[$callback], $callback));
}
if (str_contains($param, 'ifconfig')) {
Expand Down
2 changes: 1 addition & 1 deletion site/app/EasterEgg/WinterIsComing.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function ruleEmail(): callable
is_string($input->getValue())
&& (
Arrays::contains(self::EMAILS, $input->getValue())
|| Strings::match($input->getValue(), '/@(' . implode('|', array_map('preg_quote', self::HOSTS)) . ')$/')
|| Strings::match($input->getValue(), '/@(' . implode('|', array_map('preg_quote', self::HOSTS)) . ')$/') !== null
)
) {
$this->sendSyntaxError($input);
Expand Down
8 changes: 4 additions & 4 deletions site/app/Feed/Exports.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,17 @@ public function __construct(

public function getArticles(string $self, ?string $filter = null): Feed
{
$key = sprintf('Atom/%s/%s', $this->translator->getDefaultLocale(), $filter ? "ArticlesByTag/{$filter}" : 'AllArticles');
$key = sprintf('Atom/%s/%s', $this->translator->getDefaultLocale(), $filter !== null ? "ArticlesByTag/{$filter}" : 'AllArticles');
$feed = $this->cache->load($key, function (array|null &$dependencies) use ($self, $filter): Feed {
$nearest = ($filter ? $this->articles->getNearestPublishDateByTags([$filter]) : $this->articles->getNearestPublishDate());
$nearest = $filter !== null ? $this->articles->getNearestPublishDateByTags([$filter]) : $this->articles->getNearestPublishDate();
$dependencies[Cache::Expire] = ($nearest instanceof DateTime ? $nearest->modify('+1 minute') : null);

$title = ($filter ? $this->texyFormatter->translate('messages.label.articlesbytag', [$filter]) : $this->texyFormatter->translate('messages.label.allarticles'));
$title = $filter !== null ? $this->texyFormatter->translate('messages.label.articlesbytag', [$filter]) : $this->texyFormatter->translate('messages.label.allarticles');
$feed = new Feed($self, "Michal Špaček: {$title}");
$feed->setLinkSelf($self);
$feed->setAuthor(new Person('Michal Špaček'));

$articles = ($filter ? $this->articles->getAllByTags([$filter], self::ITEMS) : $this->articles->getAll(self::ITEMS));
$articles = $filter !== null ? $this->articles->getAllByTags([$filter], self::ITEMS) : $this->articles->getAll(self::ITEMS);
if (!$articles) {
throw new BadRequestException('No articles');
}
Expand Down
8 changes: 4 additions & 4 deletions site/app/Form/InterviewFormFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ public function create(callable $onSuccess, ?Interview $interview = null): UiFor
$videoThumbnailBasename = $this->videoThumbnails->getUploadedMainFileBasename($values);
$videoThumbnailBasenameAlternative = $this->videoThumbnails->getUploadedAlternativeFileBasename($values);
if ($interview) {
$removeVideoThumbnail = $values->removeVideoThumbnail ?? false;
$removeVideoThumbnailAlternative = $values->removeVideoThumbnailAlternative ?? false;
$removeVideoThumbnail = (bool)$values->removeVideoThumbnail;
$removeVideoThumbnailAlternative = (bool)$values->removeVideoThumbnailAlternative;
$thumbnailFilename = $interview->getVideo()->getThumbnailFilename();
$thumbnailAlternativeFilename = $interview->getVideo()->getThumbnailAlternativeFilename();
$this->interviews->update(
Expand All @@ -94,10 +94,10 @@ public function create(callable $onSuccess, ?Interview $interview = null): UiFor
$values->sourceHref,
);
$this->videoThumbnails->saveVideoThumbnailFiles($interview->getId(), $values);
if ($removeVideoThumbnail && $thumbnailFilename) {
if ($removeVideoThumbnail && $thumbnailFilename !== null) {
$this->videoThumbnails->deleteFile($interview->getId(), $thumbnailFilename);
}
if ($removeVideoThumbnailAlternative && $thumbnailAlternativeFilename) {
if ($removeVideoThumbnailAlternative && $thumbnailAlternativeFilename !== null) {
$this->videoThumbnails->deleteFile($interview->getId(), $thumbnailAlternativeFilename);
}
} else {
Expand Down
26 changes: 13 additions & 13 deletions site/app/Form/PostFormFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,21 +177,21 @@ private function buildPost(stdClass $values, ?int $postId): BlogPost
$values->slug,
$values->locale,
$this->locales->getLocaleById($values->locale),
empty($values->translationGroup) ? null : $values->translationGroup,
$values->translationGroup === '' ? null : $values->translationGroup,
$values->title,
empty($values->lead) ? null : $values->lead,
$values->lead === '' ? null : $values->lead,
$values->text,
empty($values->published) ? null : new DateTime($values->published),
empty($values->previewKey) ? null : $values->previewKey,
empty($values->originally) ? null : $values->originally,
empty($values->ogImage) ? null : $values->ogImage,
empty($values->tags) ? [] : $this->tags->toArray($values->tags),
empty($values->tags) ? [] : $this->tags->toSlugArray($values->tags),
$values->published === '' ? null : new DateTime($values->published),
$values->previewKey === '' ? null : $values->previewKey,
$values->originally === '' ? null : $values->originally,
$values->ogImage === '' ? null : $values->ogImage,
$values->tags === '' ? [] : $this->tags->toArray($values->tags),
$values->tags === '' ? [] : $this->tags->toSlugArray($values->tags),
$values->recommended ? $this->recommendedLinks->getFromJson($values->recommended) : [],
empty($values->twitterCard) ? null : $this->twitterCards->getCard($values->twitterCard),
empty($values->cspSnippets) ? [] : $values->cspSnippets,
empty($values->allowedTags) ? [] : $values->allowedTags,
!empty($values->omitExports),
$values->twitterCard === '' ? null : $this->twitterCards->getCard($values->twitterCard),
$values->cspSnippets,
$values->allowedTags,
$values->omitExports,
);
}

Expand Down Expand Up @@ -226,7 +226,7 @@ private function setDefaults(BlogPost $post, UiForm $form, TextInput $editSummar
'allowedTags' => $post->getAllowedTagsGroups(),
'omitExports' => $post->omitExports(),
];
if ($post->getPreviewKey()) {
if ($post->getPreviewKey() !== null) {
$values['previewKey'] = $post->getPreviewKey();
}
$form->setDefaults($values);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ public function create(?string $rating, ?string $sort, ?string $search): UiForm
$form = $this->factory->create();
$form->setMethod('get');
$items = ['all' => 'all'] + $this->rating->getRatings();
$form->addSelect('rating', 'Rating:', $items)->setDefaultValue($rating && array_key_exists($rating, $items) ? $rating : 'all');
$form->addSelect('rating', 'Rating:', $items)->setDefaultValue($rating !== null && array_key_exists($rating, $items) ? $rating : 'all');
$sorting = $this->sorting->getSorting();
$form->addSelect('sort', 'Sort by:', $sorting)->setDefaultValue($sort && array_key_exists($sort, $sorting) ? $sort : array_key_first($sorting));
$form->addSelect('sort', 'Sort by:', $sorting)->setDefaultValue($sort !== null && array_key_exists($sort, $sorting) ? $sort : array_key_first($sorting));
$placeholder = 'company, site, disclosure';
$form->addText('search', 'Search:')
->setHtmlAttribute('placeholder', $placeholder)
Expand Down
8 changes: 4 additions & 4 deletions site/app/Form/TalkFormFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ public function create(callable $onSuccess, ?Talk $talk = null): UiForm
$videoThumbnailBasename = $this->videoThumbnails->getUploadedMainFileBasename($values);
$videoThumbnailBasenameAlternative = $this->videoThumbnails->getUploadedAlternativeFileBasename($values);
if ($talk) {
$removeVideoThumbnail = $values->removeVideoThumbnail ?? false;
$removeVideoThumbnailAlternative = $values->removeVideoThumbnailAlternative ?? false;
$removeVideoThumbnail = (bool)$values->removeVideoThumbnail;
$removeVideoThumbnailAlternative = (bool)$values->removeVideoThumbnailAlternative;
$thumbnailFilename = $talk->getVideo()->getThumbnailFilename();
$thumbnailAlternativeFilename = $talk->getVideo()->getThumbnailAlternativeFilename();
$this->talks->update(
Expand Down Expand Up @@ -141,10 +141,10 @@ public function create(callable $onSuccess, ?Talk $talk = null): UiForm
$values->publishSlides,
);
$this->videoThumbnails->saveVideoThumbnailFiles($talk->getId(), $values);
if ($removeVideoThumbnail && $thumbnailFilename) {
if ($removeVideoThumbnail && $thumbnailFilename !== null) {
$this->videoThumbnails->deleteFile($talk->getId(), $thumbnailFilename);
}
if ($removeVideoThumbnailAlternative && $thumbnailAlternativeFilename) {
if ($removeVideoThumbnailAlternative && $thumbnailAlternativeFilename !== null) {
$this->videoThumbnails->deleteFile($talk->getId(), $thumbnailAlternativeFilename);
}
$message = Html::el()->setText('Přednáška upravena ');
Expand Down
4 changes: 2 additions & 2 deletions site/app/Form/TrainingApplicationAdminFormFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public function create(callable $onSuccess, callable $onStatusHistoryDeleteSucce
$upcoming = $this->upcomingTrainingDates->getPublicUpcoming();
$dates = [];
$dateId = $application->getDateId();
if ($dateId) {
if ($dateId !== null) {
$dates[$dateId] = $this->trainingDates->formatDateVenueForAdmin($this->trainingDates->get($dateId));
}
if (isset($upcoming[$application->getTrainingAction()])) {
Expand Down Expand Up @@ -160,7 +160,7 @@ private function setApplication(UiForm $form, TrainingApplication $application):
'companyTaxId' => $application->getCompanyTaxId(),
'note' => $application->getNote(),
'price' => $application->getPrice(),
'vatRate' => $vatRate ? $vatRate * 100 : $vatRate,
'vatRate' => $vatRate !== null ? $vatRate * 100 : null,
'priceVat' => $application->getPriceVat(),
'discount' => $application->getDiscount(),
'invoiceId' => $application->getInvoiceId(),
Expand Down
2 changes: 1 addition & 1 deletion site/app/Form/TrainingApplicationFormFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function create(
$multipleDates = count($dates) > 1;
foreach ($dates as $date) {
$el = Html::el()->setText($this->trainingDates->formatDateVenueForUser($date));
if ($date->getLabel()) {
if ($date->getLabel() !== null) {
if ($multipleDates) {
$el->addText(" [{$date->getLabel()}]");
} else {
Expand Down
2 changes: 1 addition & 1 deletion site/app/Form/TrainingApplicationMultipleFormFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function create(callable $onSuccess, TrainingDate $trainingDate): UiForm
$form = $this->factory->create();
$applicationsContainer = $form->addContainer('applications');
$applications = $this->httpInput->getPostArray('applications');
$count = max($applications ? count($applications) : 1, 1);
$count = max($applications !== null ? count($applications) : 1, 1);
for ($i = 0; $i < $count; $i++) {
$dataContainer = $applicationsContainer->addContainer($i);
$this->trainingControlsFactory->addAttendee($dataContainer);
Expand Down

0 comments on commit e288905

Please sign in to comment.