Skip to content

Commit

Permalink
refactor: PHPstan code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
khalwat committed Feb 4, 2024
1 parent 1a5beca commit 05e5632
Show file tree
Hide file tree
Showing 14 changed files with 63 additions and 41 deletions.
5 changes: 3 additions & 2 deletions src/Retour.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
* @author nystudio107
* @package Retour
* @since 3.0.0
* @method Settings getSettings()
*/
class Retour extends Plugin
{
Expand Down Expand Up @@ -309,7 +310,7 @@ function(Event $event) {
$prepareRedirectOnElementChange = function(ElementEvent $event) {
/** @var Element $element */
$element = $event->element;
if ($element !== null && !$event->isNew && $element->getUrl() !== null && !$element->propagating) {
if (!$event->isNew && $element->getUrl() !== null && !$element->propagating) {
$checkElementSlug = true;
// If we're running Craft 3.2 or later, also check that isn't not a draft or revision
if (ElementHelper::isDraftOrRevision($element)) {
Expand All @@ -320,7 +321,7 @@ function(Event $event) {
if (self::$settings->createUriChangeRedirects && $checkElementSlug) {
// Make sure this isn't a transitioning temporary draft/revision and that it's
// not propagating to other sites
if (strpos($element->uri, '__temp_') === false && !$element->propagating) {
if (!str_contains($element->uri, '__temp_')) {
Retour::$plugin->events->stashElementUris($element);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,6 @@ public function actionGetRedirects($siteId = null): Response
{
$redirects = Retour::$plugin->redirects->getAllStaticRedirects(null, $siteId);

return $this->asJson($redirects ?? []);
return $this->asJson($redirects);
}
}
2 changes: 1 addition & 1 deletion src/controllers/ChartsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class ChartsController extends Controller
// =========================================================================

/**
* @var bool|array
* @inerhitdoc
*/
protected array|bool|int $allowAnonymous = [
];
Expand Down
9 changes: 6 additions & 3 deletions src/controllers/FileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ public function actionImportCsvColumns(): void
if (!ini_get('auto_detect_line_endings')) {
ini_set('auto_detect_line_endings', '1');
}
$csv = null;
$this->requirePostRequest();
$filename = Craft::$app->getRequest()->getRequiredBodyParam('filename');
$columns = Craft::$app->getRequest()->getRequiredBodyParam('columns');
Expand Down Expand Up @@ -137,7 +138,7 @@ public function actionImportCsvColumns(): void
}
$hasErrors = false;
// If we have headers, then we have a file, so parse it
if ($headers !== null) {
if ($csv && $headers) {
switch (VersionHelper::getLeagueCsvVersion()) {
case 8:
$hasErrors = $this->importCsvApi8($csv, $columns, $headers);
Expand Down Expand Up @@ -171,9 +172,11 @@ public function actionImportCsvColumns(): void
protected function importCsvApi8(AbstractCsv $csv, array $columns, array $headers): bool
{
$hasErrors = false;
/** @phpstan-ignore-next-line */
$csv->setOffset(1);
$columns = ArrayHelper::filterEmptyStringsFromArray($columns);
$rowIndex = 1;
/** @phpstan-ignore-next-line */
$csv->each(function($row) use ($headers, $columns, &$rowIndex, &$hasErrors) {
$redirectConfig = [
'id' => 0,
Expand Down Expand Up @@ -202,13 +205,13 @@ protected function importCsvApi8(AbstractCsv $csv, array $columns, array $header
}

/**
* @param AbstractCsv $csv
* @param Reader $csv
* @param array $columns
* @param array $headers
* @return bool whether the import has any errors
* @throws Exception
*/
protected function importCsvApi9(AbstractCsv $csv, array $columns, array $headers): bool
protected function importCsvApi9(Reader $csv, array $columns, array $headers): bool
{
$hasErrors = false;
$stmt = (new Statement())
Expand Down
35 changes: 23 additions & 12 deletions src/controllers/RedirectsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,18 @@
namespace nystudio107\retour\controllers;

use Craft;
use craft\errors\ElementNotFoundException;
use craft\errors\MissingComponentException;
use craft\helpers\UrlHelper;
use craft\web\Controller;
use craft\web\UrlManager;
use nystudio107\retour\assetbundles\retour\RetourAsset;
use nystudio107\retour\assetbundles\retour\RetourRedirectsAsset;
use nystudio107\retour\helpers\MultiSite as MultiSiteHelper;
use nystudio107\retour\helpers\Permission as PermissionHelper;
use nystudio107\retour\models\StaticRedirects as StaticRedirectsModel;
use nystudio107\retour\Retour;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
Expand Down Expand Up @@ -206,9 +209,8 @@ public function actionEditRedirect(
}

/**
* @return Response|void
* @throws MissingComponentException
* @throws ForbiddenHttpException
* @throws ForbiddenHttpException|BadRequestHttpException
*/
public function actionDeleteRedirects(): ?Response
{
Expand Down Expand Up @@ -247,7 +249,6 @@ public function actionSaveRedirect(): ?Response
{
PermissionHelper::controllerPermissionCheck('retour:redirects');
$this->requirePostRequest();
/** @var StaticRedirectsModel $redirect */
$redirectConfig = Craft::$app->getRequest()->getRequiredBodyParam('redirectConfig');
if ($redirectConfig === null) {
throw new NotFoundHttpException('Redirect not found');
Expand All @@ -269,9 +270,12 @@ public function actionSaveRedirect(): ?Response
if (!$redirect->validate()) {
Craft::$app->getSession()->setError(Craft::t('app', "Couldn't save redirect settings."));
// Send the redirect back to the template
Craft::$app->getUrlManager()->setRouteParams([
'redirect' => $redirect,
]);
$urlManager = Craft::$app->getUrlManager();
if ($urlManager instanceof UrlManager) {
$urlManager->setRouteParams([
'redirect' => $redirect,
]);
}

return null;
}
Expand All @@ -286,9 +290,12 @@ public function actionSaveRedirect(): ?Response
if ($testRedirectConfig === null) {
Craft::$app->getSession()->setError(Craft::t('app', "Couldn't save redirect settings because it'd create a redirect loop."));
// Send the redirect back to the template
Craft::$app->getUrlManager()->setRouteParams([
'redirect' => $redirect,
]);
$urlManager = Craft::$app->getUrlManager();
if ($urlManager instanceof UrlManager) {
$urlManager->setRouteParams([
'redirect' => $redirect,
]);
}

return null;
}
Expand Down Expand Up @@ -356,8 +363,12 @@ public function actionShortlinks(string $siteHandle = null): Response

/**
* @return Response|void
* @throws \craft\errors\MissingComponentException
* @throws \yii\web\ForbiddenHttpException
* @throws BadRequestHttpException
* @throws ForbiddenHttpException
* @throws MissingComponentException
* @throws \Throwable
* @throws ElementNotFoundException
* @throws Exception
*/
public function actionDeleteShortlinks()
{
Expand All @@ -366,7 +377,7 @@ public function actionDeleteShortlinks()
$redirectIds = $request->getRequiredBodyParam('redirectIds');
$stickyError = false;
foreach ($redirectIds as $redirectId) {
if (Retour::$plugin->redirects->deleteShortlinkById($redirectId) === 0) {
if (Retour::$plugin->redirects->deleteShortlinkById($redirectId)) {
$stickyError = true;
}
}
Expand Down
10 changes: 7 additions & 3 deletions src/controllers/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use craft\errors\MissingComponentException;
use craft\helpers\UrlHelper;
use craft\web\Controller;
use craft\web\UrlManager;
use nystudio107\retour\assetbundles\retour\RetourAsset;
use nystudio107\retour\helpers\Permission as PermissionHelper;
use nystudio107\retour\models\Settings;
Expand Down Expand Up @@ -128,9 +129,12 @@ public function actionSavePluginSettings(): ?Response
Craft::$app->getSession()->setError(Craft::t('app', "Couldn't save plugin settings."));

// Send the plugin back to the template
Craft::$app->getUrlManager()->setRouteParams([
'plugin' => $plugin,
]);
$urlManager = Craft::$app->getUrlManager();
if ($urlManager instanceof UrlManager) {
$urlManager->setRouteParams([
'plugin' => $plugin,
]);
}

return null;
}
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/StatisticsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public function actionClearStatistics(): Response
}

/**
* @return Response|void
* @return ?Response
* @throws MissingComponentException
* @throws BadRequestHttpException
* @throws ForbiddenHttpException
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/TablesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class TablesController extends Controller
// =========================================================================

/**
* @var bool|array
* @inerhitdoc
*/
protected array|bool|int $allowAnonymous = [
];
Expand Down Expand Up @@ -177,7 +177,7 @@ public function actionDashboard(
* @param int $page
* @param int $per_page
* @param string $filter
* @param null $siteId
* @param int $siteId
*
* @return Response
* @throws ForbiddenHttpException
Expand Down
1 change: 1 addition & 0 deletions src/gql/resolvers/RetourResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ public static function resolve(mixed $source, array $arguments, mixed $context,
if ($redirect === null && Craft::$app->getElements()->getElementByUri(trim($uri, '/'), $siteId) === null) {
// Set the `site` virtual field
$redirect['site'] = null;
$redirect['siteId'] = $siteId;
if (isset($redirect['siteId']) && (int)$redirect['siteId'] !== 0) {
$site = Craft::$app->getSites()->getSiteById((int)$redirect['siteId']);
if ($site !== null) {
Expand Down
2 changes: 0 additions & 2 deletions src/helpers/MultiSite.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ public static function setSitesMenuVariables(array &$variables): void
$sites = Craft::$app->getSites();
if (Craft::$app->getIsMultiSite()) {
$editableSites = $sites->getEditableSiteIds();
/** @var Site $site */
foreach ($sites->getAllGroups() as $group) {
$groupSites = $sites->getSitesByGroupId($group->id);
$variables['sitesMenu'][$group->name]
Expand Down Expand Up @@ -77,7 +76,6 @@ public static function setMultiSiteVariables($siteHandle, &$siteId, array &$vari
$variables['enabledSiteIds'] = [];
$variables['siteIds'] = [];

/** @var Site $site */
foreach ($sites->getEditableSiteIds() as $editableSiteId) {
$variables['enabledSiteIds'][] = $editableSiteId;
$variables['siteIds'][] = $editableSiteId;
Expand Down
6 changes: 3 additions & 3 deletions src/migrations/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ protected function createIndexes(): void
protected function addForeignKeys(): void
{
$this->addForeignKey(
$this->db->getForeignKeyName('{{%retour_redirects}}', 'associatedElementId'),
$this->db->getForeignKeyName(),
'{{%retour_redirects}}',
'associatedElementId',
'{{%elements}}',
Expand All @@ -240,7 +240,7 @@ protected function addForeignKeys(): void
);

$this->addForeignKey(
$this->db->getForeignKeyName('{{%retour_static_redirects}}', 'siteId'),
$this->db->getForeignKeyName(),
'{{%retour_static_redirects}}',
'siteId',
'{{%sites}}',
Expand All @@ -250,7 +250,7 @@ protected function addForeignKeys(): void
);

$this->addForeignKey(
$this->db->getForeignKeyName('{{%retour_stats}}', 'siteId'),
$this->db->getForeignKeyName(),
'{{%retour_stats}}',
'siteId',
'{{%sites}}',
Expand Down
4 changes: 2 additions & 2 deletions src/migrations/m181213_233502_add_site_id.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public function safeUp(): bool
protected function addForeignKeys(): void
{
$this->addForeignKey(
$this->db->getForeignKeyName('{{%retour_static_redirects}}', 'siteId'),
$this->db->getForeignKeyName(),
'{{%retour_static_redirects}}',
'siteId',
'{{%sites}}',
Expand All @@ -75,7 +75,7 @@ protected function addForeignKeys(): void
);

$this->addForeignKey(
$this->db->getForeignKeyName('{{%retour_stats}}', 'siteId'),
$this->db->getForeignKeyName(),
'{{%retour_stats}}',
'siteId',
'{{%sites}}',
Expand Down
20 changes: 11 additions & 9 deletions src/services/Redirects.php
Original file line number Diff line number Diff line change
Expand Up @@ -303,9 +303,7 @@ public function findRedirectMatch(string $fullUrl, string $pathOnly, $siteId = n
$siteId = $currentSite->id;
} else {
$primarySite = Craft::$app->getSites()->primarySite;
if ($currentSite) {
$siteId = $primarySite->id;
}
}
}
// Try getting the full URL redirect from the cache
Expand Down Expand Up @@ -789,11 +787,11 @@ public function resolveRedirect(string $fullUrl, string $pathOnly, array $redire

/**
* @param ResolveRedirectEvent $event
* @param string|null $url
* @param null $redirect
* @param ?string $url
* @param ?array $redirect
* @return null|array
*/
public function resolveEventRedirect(ResolveRedirectEvent $event, ?string $url = null, $redirect = null): ?array
public function resolveEventRedirect(ResolveRedirectEvent $event, ?string $url = null, ?array $redirect = null): ?array
{
$result = null;

Expand All @@ -805,7 +803,7 @@ public function resolveEventRedirect(ResolveRedirectEvent $event, ?string $url =
]);
$result = $resolvedRedirect->toArray();

if ($url !== null && $redirect !== null) {
if ($url !== null) {
// Save the modified redirect to the cache
$redirect['redirectDestUrl'] = $event->redirectDestUrl;
$redirect['redirectHttpCode'] = $event->redirectHttpCode;
Expand Down Expand Up @@ -979,7 +977,7 @@ public function deleteRedirectById(int $id): int
]);
$this->trigger(self::EVENT_BEFORE_DELETE_REDIRECT, $event);
if (!$event->isValid) {
return false;
return 0;
}
// Delete a row from the db table
try {
Expand Down Expand Up @@ -1102,14 +1100,16 @@ public function getRedirectsByElementId(int $elementId, int $siteId = null)
/**
* Delete a short link by its ID.
*
* @param int $redirectId
* @throws \Throwable
* @throws \craft\errors\ElementNotFoundException
* @throws \yii\base\Exception
*/
public function deleteShortlinkById(int $redirectId): void
public function deleteShortlinkById(int $redirectId): bool
{
$redirect = $this->getRedirectById($redirectId);
if (!$redirect) {
return false;
}
$elementId = $redirect['associatedElementId'];
$siteId = $redirect['siteId'];
$element = Craft::$app->getElements()->getElementById($elementId, null, $siteId);
Expand All @@ -1122,6 +1122,8 @@ public function deleteShortlinkById(int $redirectId): void
Craft::$app->getElements()->saveElement($element);
}
}

return true;
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/validators/UriValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace nystudio107\retour\validators;

use craft\helpers\UrlHelper;
use nystudio107\retour\models\StaticRedirects;
use yii\validators\Validator;

/**
Expand Down Expand Up @@ -44,6 +45,7 @@ public function init(): void
*/
public function validateAttribute($model, $attribute): void
{
/** @var StaticRedirects $model */
$value = $model->$attribute;
$redirectMatchType = 'redirectMatchType';
// Always remove whitespace
Expand Down

0 comments on commit 05e5632

Please sign in to comment.