From 460389f84db50dddbe5f4a6c6c59bd058305fff3 Mon Sep 17 00:00:00 2001 From: Andrew Welch Date: Thu, 28 Mar 2024 13:13:25 -0400 Subject: [PATCH] refactor: PHPstan code cleanup --- phpstan.neon | 3 + src/ImageOptimize.php | 17 +++-- .../controllers/OptimizeController.php | 12 ++-- src/fields/OptimizedImages.php | 6 +- src/gql/types/OptimizedImagesType.php | 27 ------- src/helpers/Image.php | 11 +-- src/imagetransforms/ImageTransform.php | 6 +- src/jobs/ResaveOptimizedImages.php | 4 +- src/models/OptimizedImage.php | 71 ++++++++++--------- src/models/Settings.php | 6 +- src/services/Optimize.php | 24 ++++--- src/services/OptimizedImages.php | 37 +++++----- src/services/Placeholder.php | 30 ++++---- src/variables/ImageOptimizeVariable.php | 10 +-- 14 files changed, 132 insertions(+), 132 deletions(-) diff --git a/phpstan.neon b/phpstan.neon index 9ad13081..1cb34c73 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -5,3 +5,6 @@ parameters: level: 5 paths: - src + excludePaths: + # Ignore library code + - src/lib/ diff --git a/src/ImageOptimize.php b/src/ImageOptimize.php index a67e4513..9b528297 100644 --- a/src/ImageOptimize.php +++ b/src/ImageOptimize.php @@ -50,9 +50,11 @@ use nystudio107\imageoptimize\services\ServicesTrait; use nystudio107\imageoptimize\utilities\ImageOptimizeUtility; use nystudio107\imageoptimize\variables\ImageOptimizeVariable; +use Twig\Error\LoaderError; use yii\base\Event; use yii\base\Exception; use yii\base\InvalidConfigException; +use function function_exists; /** @noinspection MissingPropertyAnnotationsInspection */ @@ -206,13 +208,13 @@ public function settingsHtml() 'image-optimize/settings/_settings.twig', [ 'settings' => $settings, - 'gdInstalled' => \function_exists('imagecreatefromjpeg'), + 'gdInstalled' => function_exists('imagecreatefromjpeg'), 'imageTransformTypeOptions' => $imageTransformTypeOptions, 'allImageTransformTypes' => $allImageTransformTypes, 'imageTransform' => ImageOptimize::$plugin->transformMethod, ] ); - } catch (\Twig\Error\LoaderError $e) { + } catch (LoaderError $e) { Craft::error($e->getMessage(), __METHOD__); } catch (Exception $e) { Craft::error($e->getMessage(), __METHOD__); @@ -237,6 +239,7 @@ protected function createSettingsModel() */ protected function setImageTransformComponent() { + /** @var Settings $settings */ $settings = $this->getSettings(); $definition = array_merge( $settings->imageTransformTypeSettings[$settings->transformClass] ?? [], @@ -484,8 +487,8 @@ function(FieldEvent $event) { 'Fields::EVENT_AFTER_SAVE_FIELD', __METHOD__ ); + /** @var Settings $settings */ $settings = $this->getSettings(); - /** @var Field $field */ if (!$event->isNew && $settings->automaticallyResaveImageVariants) { $this->checkForOptimizedImagesField($event); } @@ -502,6 +505,7 @@ function(PluginEvent $event) { 'Plugins::EVENT_AFTER_SAVE_PLUGIN_SETTINGS', __METHOD__ ); + /** @var Settings $settings */ $settings = $this->getSettings(); if ($settings->automaticallyResaveImageVariants) { // After they have changed the settings, resave all of the assets @@ -520,6 +524,7 @@ function(VolumeEvent $event) { 'Volumes::EVENT_AFTER_SAVE_VOLUME', __METHOD__ ); + /** @var Settings $settings */ $settings = $this->getSettings(); // Only worry about this volume if it's not new if (!$event->isNew && $settings->automaticallyResaveImageVariants) { @@ -631,17 +636,17 @@ protected function customFrontendRoutes(): array * * @param FieldEvent $event * - * @throws \yii\base\InvalidConfigException + * @throws InvalidConfigException */ protected function checkForOptimizedImagesField(FieldEvent $event) { $thisField = $event->field; if ($thisField instanceof OptimizedImages) { $volumes = Craft::$app->getVolumes()->getAllVolumes(); + /** @var Volume $volume */ foreach ($volumes as $volume) { $needToReSave = false; - /** @var FieldLayout $fieldLayout */ - /** @var Volume $volume */ + /** @var ?FieldLayout $fieldLayout */ $fieldLayout = $volume->getFieldLayout(); // Loop through the fields in the layout to see if it contains our field if ($fieldLayout) { diff --git a/src/console/controllers/OptimizeController.php b/src/console/controllers/OptimizeController.php index 4717615a..d66b8500 100755 --- a/src/console/controllers/OptimizeController.php +++ b/src/console/controllers/OptimizeController.php @@ -11,10 +11,12 @@ namespace nystudio107\imageoptimize\console\controllers; use Craft; +use craft\base\Field; use craft\base\Volume; use craft\helpers\App; use craft\queue\QueueInterface; use nystudio107\imageoptimize\ImageOptimize; +use yii\base\InvalidConfigException; use yii\console\Controller; use yii\queue\redis\Queue as RedisQueue; @@ -68,7 +70,7 @@ public function options($actionID): array * * @param string|null $volumeHandle * - * @throws \yii\base\InvalidConfigException + * @throws InvalidConfigException */ public function actionCreate($volumeHandle = null) { @@ -79,6 +81,7 @@ public function actionCreate($volumeHandle = null) $fieldId = null; if ($this->field !== null) { + /** @var Field $field */ $field = Craft::$app->getFields()->getFieldByHandle($this->field); if ($field !== null) { $fieldId = $field->id; @@ -130,11 +133,12 @@ private function runCraftQueue() { // This might take a while App::maxPowerCaptain(); + /** @var QueueInterface|RedisQueue $queue */ $queue = Craft::$app->getQueue(); - if ($queue instanceof QueueInterface) { - $queue->run(); - } elseif ($queue instanceof RedisQueue) { + if ($queue instanceof RedisQueue) { $queue->run(false); + } elseif ($queue instanceof QueueInterface) { + $queue->run(); } } } diff --git a/src/fields/OptimizedImages.php b/src/fields/OptimizedImages.php index 33d0f73d..9b208b24 100644 --- a/src/fields/OptimizedImages.php +++ b/src/fields/OptimizedImages.php @@ -25,6 +25,7 @@ use nystudio107\imageoptimize\gql\types\generators\OptimizedImagesGenerator; use nystudio107\imageoptimize\ImageOptimize; use nystudio107\imageoptimize\models\OptimizedImage; +use nystudio107\imageoptimize\models\Settings; use ReflectionClass; use ReflectionException; use Twig\Error\LoaderError; @@ -140,6 +141,7 @@ public function init() // Handle cases where the plugin has been uninstalled if (ImageOptimize::$plugin !== null) { + /** @var ?Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); if ($settings) { if (empty($this->variants)) { @@ -267,7 +269,7 @@ public function normalizeValue($value, ElementInterface $asset = null) $model = $value; } else { // Just create a new empty model - $model = new OptimizedImage(null); + $model = new OptimizedImage([]); } return $model; @@ -511,7 +513,7 @@ protected function getFieldVolumeInfo($fieldHandle): array protected function volumeHasField(Volume $volume, string $fieldHandle): bool { $result = false; - /** @var FieldLayout $fieldLayout */ + /** @var ?FieldLayout $fieldLayout */ $fieldLayout = $volume->getFieldLayout(); // Loop through the fields in the layout to see if there is an OptimizedImages field if ($fieldLayout) { diff --git a/src/gql/types/OptimizedImagesType.php b/src/gql/types/OptimizedImagesType.php index 5d170941..8052c7e0 100644 --- a/src/gql/types/OptimizedImagesType.php +++ b/src/gql/types/OptimizedImagesType.php @@ -8,9 +8,7 @@ namespace nystudio107\imageoptimize\gql\types; use craft\gql\base\ObjectType; - use GraphQL\Type\Definition\ResolveInfo; - use nystudio107\imageoptimize\models\OptimizedImage; /** @@ -32,84 +30,63 @@ protected function resolve($source, $arguments, $context, ResolveInfo $resolveIn // Special-case the `src` field with arguments case 'src': $width = $arguments['width'] ?? 0; - return $source->src($width); - break; // Special-case the `srcWebp` field with arguments case 'srcWebp': $width = $arguments['width'] ?? 0; - return $source->srcWebp($width); - break; // Special-case the `srcset` field with arguments case 'srcset': $dpr = $arguments['dpr'] ?? false; - return $source->srcset($dpr); - break; // Special-case the `srcsetMinWidth` field with arguments case 'srcsetMinWidth': $width = $arguments['width'] ?? 0; $dpr = $arguments['dpr'] ?? false; - return $source->srcsetMinWidth($width, $dpr); - break; // Special-case the `srcsetMaxWidth` field with arguments case 'srcsetMaxWidth': $width = $arguments['width'] ?? 0; $dpr = $arguments['dpr'] ?? false; - return $source->srcsetMaxWidth($width, $dpr); - break; // Special-case the `srcsetWebp` field with arguments case 'srcsetWebp': $dpr = $arguments['dpr'] ?? false; - return $source->srcsetWebp($dpr); - break; // Special-case the `srcsetMinWidthWebp` field with arguments case 'srcsetMinWidthWebp': $width = $arguments['width'] ?? 0; $dpr = $arguments['dpr'] ?? false; - return $source->srcsetMinWidthWebp($width, $dpr); - break; // Special-case the `srcsetMaxWidthWebp` field with arguments case 'srcsetMaxWidthWebp': $width = $arguments['width'] ?? 0; $dpr = $arguments['dpr'] ?? false; - return $source->srcsetMaxWidthWebp($width, $dpr); - break; // Special-case the `maxSrcsetWidth` field case 'maxSrcsetWidth': return $source->maxSrcsetWidth(); - break; // Special-case the `placeholderImage` field case 'placeholderImage': return $source->placeholderImage(); - break; // Special-case the `placeholderBox` field case 'placeholderBox': $color = $arguments['color'] ?? null; - return $source->placeholderBox($color); - break; // Special-case the `placeholderSilhouette` field case 'placeholderSilhouette': return $source->placeholderSilhouette(); - break; // Special-case the `srcUrls` field case 'srcUrls': @@ -117,19 +94,15 @@ protected function resolve($source, $arguments, $context, ResolveInfo $resolveIn foreach ($source->optimizedImageUrls as $width => $url) { $result[] = ['width' => $width, 'url' => $url]; } - return $result; - break; // Special-case the `colorPaletteRgb` field case 'colorPaletteRgb': return $source->colorPaletteRgb(); - break; // Default to just returning the field value default: return $source[$fieldName]; - break; } } } diff --git a/src/helpers/Image.php b/src/helpers/Image.php index d0d8a5ca..ae332546 100644 --- a/src/helpers/Image.php +++ b/src/helpers/Image.php @@ -10,9 +10,10 @@ use Craft; use craft\errors\ImageException; use craft\helpers\FileHelper; - use Imagine\Gd\Imagine as GdImagine; use Imagine\Imagick\Imagine as ImagickImagine; +use Throwable; +use yii\base\InvalidConfigException; /** * @author nystudio107 @@ -33,7 +34,7 @@ class Image * @return bool * * @throws ImageException - * @throws \yii\base\InvalidConfigException + * @throws InvalidConfigException */ public static function getIsAnimatedGif(string $path): bool { @@ -61,7 +62,7 @@ public static function getIsAnimatedGif(string $path): bool if ($imageService->getIsGd()) { return false; } - + if (!is_file($path)) { Craft::error('Tried to load an image at ' . $path . ', but the file does not exist.', __METHOD__); throw new ImageException(Craft::t('app', 'No file exists at the given path.')); @@ -87,7 +88,7 @@ public static function getIsAnimatedGif(string $path): bool try { $image = $instance->open($path); - } catch (\Throwable $e) { + } catch (Throwable $e) { throw new ImageException(Craft::t( 'app', 'The file “{path}” does not appear to be an image.', @@ -97,6 +98,6 @@ public static function getIsAnimatedGif(string $path): bool $extension = pathinfo($path, PATHINFO_EXTENSION); - return $extension === 'gif' && $image->layers(); + return $extension === 'gif' && $image->layers()->count() > 1; } } diff --git a/src/imagetransforms/ImageTransform.php b/src/imagetransforms/ImageTransform.php index 3ef94c49..26a58d45 100644 --- a/src/imagetransforms/ImageTransform.php +++ b/src/imagetransforms/ImageTransform.php @@ -11,13 +11,13 @@ namespace nystudio107\imageoptimize\imagetransforms; use Craft; - use craft\base\SavableComponent; use craft\elements\Asset; use craft\helpers\FileHelper; use craft\helpers\StringHelper; use nystudio107\imageoptimize\helpers\UrlHelper; use nystudio107\imageoptimize\ImageOptimize; +use ReflectionClass; /** * @author nystudio107 @@ -47,7 +47,7 @@ public static function displayName(): string */ public static function getTemplatesRoot(): array { - $reflect = new \ReflectionClass(static::class); + $reflect = new ReflectionClass(static::class); $classPath = FileHelper::normalizePath( dirname($reflect->getFileName()) . '/../templates' @@ -148,7 +148,7 @@ public function appendExtension($pathOrUrl, $extension): string { $path = $this->decomposeUrl($pathOrUrl); $path_parts = pathinfo($path['path']); - $new_path = ($path_parts['filename'] ?? '') . '.' . ($path_parts['extension'] ?? '') . $extension; + $new_path = ($path_parts['filename']) . '.' . ($path_parts['extension'] ?? '') . $extension; if (!empty($path_parts['dirname']) && $path_parts['dirname'] !== '.') { $dirname = $path_parts['dirname']; $dirname = $dirname === '/' ? '' : $dirname; diff --git a/src/jobs/ResaveOptimizedImages.php b/src/jobs/ResaveOptimizedImages.php index 40481a86..3ca1663d 100644 --- a/src/jobs/ResaveOptimizedImages.php +++ b/src/jobs/ResaveOptimizedImages.php @@ -12,7 +12,6 @@ use Craft; use craft\base\ElementInterface; - use craft\base\Field; use craft\console\Application as ConsoleApplication; use craft\db\Paginator; @@ -22,7 +21,6 @@ use craft\queue\BaseJob; use nystudio107\imageoptimize\fields\OptimizedImages as OptimizedImagesField; use nystudio107\imageoptimize\ImageOptimize; - use yii\base\Exception; /** @@ -106,7 +104,7 @@ public function execute($queue) $layout = $element->getFieldLayout(); if ($layout !== null) { $fields = $layout->getFields(); - /** @var $field Field */ + /** @var Field $field */ foreach ($fields as $field) { if ($field instanceof OptimizedImagesField && $element instanceof Asset) { if ($this->fieldId === null || $field->id == $this->fieldId) { diff --git a/src/models/OptimizedImage.php b/src/models/OptimizedImage.php index 0dbb81fa..061b100e 100644 --- a/src/models/OptimizedImage.php +++ b/src/models/OptimizedImage.php @@ -13,12 +13,13 @@ use Craft; use craft\base\Model; use craft\helpers\Html; - use craft\helpers\Template; use craft\validators\ArrayValidator; use nystudio107\imageoptimize\helpers\Color as ColorHelper; use nystudio107\imageoptimize\helpers\UrlHelper; use nystudio107\imageoptimize\ImageOptimize; +use Twig\Markup; +use function strlen; /** * @author nystudio107 @@ -86,12 +87,12 @@ class OptimizedImage extends Model public $lightness; /** - * @var int The width of the placeholder image + * @var ?int The width of the placeholder image */ public $placeholderWidth; /** - * @var int The height of the placeholder image + * @var ?int The height of the placeholder image */ public $placeholderHeight; @@ -131,9 +132,9 @@ public function rules(): array * * @param int $width * - * @return \Twig\Markup|null + * @return Markup */ - public function src(int $width = 0): string + public function src(int $width = 0): Markup { if (empty($width)) { return Template::raw(reset($this->optimizedImageUrls)); @@ -147,7 +148,7 @@ public function src(int $width = 0): string * * @param int $width * - * @return null|string|\Twig\Markup + * @return string */ public function getSrc(int $width = 0): string { @@ -160,9 +161,9 @@ public function getSrc(int $width = 0): string * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw * srcsets * - * @return \Twig\Markup|null + * @return Markup */ - public function srcset(bool $dpr = false): string + public function srcset(bool $dpr = false): Markup { return Template::raw($this->getSrcsetFromArray($this->optimizedImageUrls, $dpr)); } @@ -186,9 +187,9 @@ public function getSrcset(bool $dpr = false): string * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw * srcsets * - * @return \Twig\Markup|null + * @return Markup */ - public function srcsetWidth(int $width, bool $dpr = false): string + public function srcsetWidth(int $width, bool $dpr = false): Markup { $subset = $this->getSrcsetSubsetArray($this->optimizedImageUrls, $width, 'width'); @@ -203,9 +204,9 @@ public function srcsetWidth(int $width, bool $dpr = false): string * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw * srcsets * - * @return \Twig\Markup|null + * @return Markup */ - public function srcsetMinWidth(int $width, bool $dpr = false): string + public function srcsetMinWidth(int $width, bool $dpr = false): Markup { $subset = $this->getSrcsetSubsetArray($this->optimizedImageUrls, $width, 'minwidth'); @@ -219,9 +220,9 @@ public function srcsetMinWidth(int $width, bool $dpr = false): string * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw * srcsets * - * @return \Twig\Markup|null + * @return Markup */ - public function srcsetMaxWidth(int $width, bool $dpr = false): string + public function srcsetMaxWidth(int $width, bool $dpr = false): Markup { $subset = $this->getSrcsetSubsetArray($this->optimizedImageUrls, $width, 'maxwidth'); @@ -234,9 +235,9 @@ public function srcsetMaxWidth(int $width, bool $dpr = false): string * * @param int $width * - * @return \Twig\Markup|null + * @return Markup */ - public function srcWebp(int $width = 0): string + public function srcWebp(int $width = 0): Markup { if (empty($width)) { return Template::raw(reset($this->optimizedWebPImageUrls)); @@ -263,9 +264,9 @@ public function getSrcWebp(int $width = 0): string * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw * srcsets * - * @return \Twig\Markup|null + * @return Markup */ - public function srcsetWebp(bool $dpr = false): string + public function srcsetWebp(bool $dpr = false): Markup { return Template::raw($this->getSrcsetFromArray($this->optimizedWebPImageUrls, $dpr)); } @@ -289,9 +290,9 @@ public function getSrcsetWebp(bool $dpr = false): string * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw * srcsets * - * @return \Twig\Markup|null + * @return Markup */ - public function srcsetWidthWebp(int $width, bool $dpr = false): string + public function srcsetWidthWebp(int $width, bool $dpr = false): Markup { $subset = $this->getSrcsetSubsetArray($this->optimizedWebPImageUrls, $width, 'width'); @@ -306,9 +307,9 @@ public function srcsetWidthWebp(int $width, bool $dpr = false): string * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw * srcsets * - * @return \Twig\Markup|null + * @return Markup */ - public function srcsetMinWidthWebp(int $width, bool $dpr = false): string + public function srcsetMinWidthWebp(int $width, bool $dpr = false): Markup { $subset = $this->getSrcsetSubsetArray($this->optimizedWebPImageUrls, $width, 'minwidth'); @@ -323,9 +324,9 @@ public function srcsetMinWidthWebp(int $width, bool $dpr = false): string * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw * srcsets * - * @return \Twig\Markup|null + * @return Markup */ - public function srcsetMaxWidthWebp(int $width, bool $dpr = false): string + public function srcsetMaxWidthWebp(int $width, bool $dpr = false): Markup { $subset = $this->getSrcsetSubsetArray($this->optimizedWebPImageUrls, $width, 'maxwidth'); @@ -385,7 +386,7 @@ public function colorPaletteRgb(): array * * @param array $linkAttrs * - * @return \Twig\Markup + * @return Markup */ public function linkPreloadTag($linkAttrs = []) { @@ -419,7 +420,7 @@ public function linkPreloadTag($linkAttrs = []) * @param string $placeHolder 'box', 'color', 'image', 'silhouette' * @param array $imgAttrs * - * @return \Twig\Markup + * @return Markup */ public function imgTag($loading = 'eager', $placeHolder = 'box', $imgAttrs = []) { @@ -457,7 +458,7 @@ public function imgTag($loading = 'eager', $placeHolder = 'box', $imgAttrs = []) * @param array $srcsetAttrs * @param array $imgAttrs * - * @return \Twig\Markup + * @return Markup */ public function pictureTag($loading = 'eager', $placeHolder = 'box', $pictureAttrs = [], $srcsetAttrs = [], $imgAttrs = []) { @@ -535,7 +536,7 @@ public function pictureTag($loading = 'eager', $placeHolder = 'box', $pictureAtt /** * Return a base64-encoded placeholder image * - * @return \Twig\Markup|null + * @return Markup|null */ public function placeholderImage() { @@ -566,7 +567,7 @@ public function getPlaceholderImage(): string public function placeholderImageSize(): string { $placeholder = $this->placeholderImage(); - $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0; + $contentLength = !empty(strlen($placeholder)) ? strlen($placeholder) : 0; return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1); } @@ -576,7 +577,7 @@ public function placeholderImageSize(): string * * @param string|null $color * - * @return \Twig\Markup|null + * @return Markup|null */ public function placeholderBox(string $color = null) { @@ -605,7 +606,7 @@ public function getPlaceholderBox(string $color = null): string public function placeholderBoxSize(): string { $placeholder = $this->placeholderBox(); - $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0; + $contentLength = !empty(strlen($placeholder)) ? strlen($placeholder) : 0; return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1); } @@ -613,7 +614,7 @@ public function placeholderBoxSize(): string /** * Return a silhouette of the image as an SVG placeholder * - * @return \Twig\Markup|null + * @return Markup|null */ public function placeholderSilhouette() { @@ -644,7 +645,7 @@ public function getPlaceholderSilhouette(): string public function placeholderSilhouetteSize(): string { $placeholder = $this->placeholderSilhouette(); - $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0; + $contentLength = !empty(strlen($placeholder)) ? strlen($placeholder) : 0; return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1); } @@ -770,9 +771,9 @@ protected function getSrcsetFromArray(array $array, bool $dpr = false): string /** * Return a default placeholder image * - * @return \Twig\Markup + * @return Markup */ - protected function defaultPlaceholderImage(): \Twig\Markup + protected function defaultPlaceholderImage(): Markup { $width = 1; $height = 1; diff --git a/src/models/Settings.php b/src/models/Settings.php index 36459e7a..60a40319 100644 --- a/src/models/Settings.php +++ b/src/models/Settings.php @@ -15,11 +15,9 @@ use craft\validators\ArrayValidator; use nystudio107\imageoptimize\ImageOptimize; use nystudio107\imageoptimize\imagetransforms\CraftImageTransform; - use nystudio107\imageoptimize\imagetransforms\ImageTransformInterface; -use nystudio107\imageoptimize\imagetransforms\ImgixImageTransform; -use nystudio107\imageoptimize\imagetransforms\ThumborImageTransform; - +use nystudio107\imageoptimizeimgix\imagetransforms\ImgixImageTransform; +use nystudio107\imageoptimizethumbor\imagetransforms\ThumborImageTransform; use yii\behaviors\AttributeTypecastBehavior; /** diff --git a/src/services/Optimize.php b/src/services/Optimize.php index 6e11fc34..762ec166 100644 --- a/src/services/Optimize.php +++ b/src/services/Optimize.php @@ -35,6 +35,7 @@ use nystudio107\imageoptimize\imagetransforms\CraftImageTransform; use nystudio107\imageoptimize\imagetransforms\ImageTransform; use nystudio107\imageoptimize\imagetransforms\ImageTransformInterface; +use nystudio107\imageoptimize\models\Settings; use nystudio107\imageoptimizeimgix\imagetransforms\ImgixImageTransform; use nystudio107\imageoptimizesharp\imagetransforms\SharpImageTransform; use nystudio107\imageoptimizethumbor\imagetransforms\ThumborImageTransform; @@ -114,9 +115,9 @@ public function getAllImageTransformTypes(): array * @param mixed $config The Image Transform’s class name, or its config, * with a `type` value and optionally a `settings` value * - * @return null|ImageTransformInterface The Image Transform + * @return ?ImageTransformInterface The Image Transform */ - public function createImageTransformType($config): ImageTransformInterface + public function createImageTransformType($config): ?ImageTransformInterface { if (is_string($config)) { $config = ['type' => $config]; @@ -158,7 +159,7 @@ public function handleGetAssetUrlEvent(GetAssetUrlEvent $event) } // If we're passed in null, make a dummy AssetTransform model for Thumbor // For backwards compatibility - if ($transform === null && ImageOptimize::$plugin->transformMethod instanceof ThumborImageTransform) { + if (ImageOptimize::$plugin->transformMethod instanceof ThumborImageTransform) { $transform = new AssetTransform([ 'width' => $asset->width, 'interlace' => 'line', @@ -238,6 +239,8 @@ public function handleGetAssetThumbUrlEvent(GetAssetThumbUrlEvent $event) } // Generate an image transform url if ($transformMethod->hasProperty('generateTransformsBeforePageLoad')) { + // This is a dynamic property that some image transforms have + /** @phpstan-ignore-next-line */ $transformMethod->generateTransformsBeforePageLoad = $event->generate; } $url = $transformMethod->getTransformUrl($asset, $transform); @@ -276,9 +279,6 @@ public function serverSupportsWebP(): bool public function renderLazySizesFallbackJs($scriptAttrs = [], $variables = []) { $minifier = 'minify'; - if ($scriptAttrs === null) { - $minifier = 'jsMin'; - } $vars = array_merge([ 'scriptSrc' => 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.0/lazysizes.min.js', ], @@ -311,9 +311,6 @@ public function renderLazySizesFallbackJs($scriptAttrs = [], $variables = []) public function renderLazySizesJs($scriptAttrs = [], $variables = []) { $minifier = 'minify'; - if ($scriptAttrs === null) { - $minifier = 'jsMin'; - } $vars = array_merge([ 'scriptSrc' => 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.0/lazysizes.min.js', ], @@ -447,6 +444,7 @@ public function saveTransformToTempFile(AssetTransformIndex $index, Image $image public function optimizeImage(AssetTransformIndex $index, string $tempPath) { Craft::beginProfile('optimizeImage', __METHOD__); + /** @var Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); // Get the active processors for the transform format $activeImageProcessors = $settings->activeImageProcessors; @@ -496,6 +494,7 @@ public function humanFileSize($bytes, $decimals = 1): string public function createImageVariants(AssetTransformIndex $index, Asset $asset, string $tempPath) { Craft::beginProfile('createImageVariants', __METHOD__); + /** @var Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); // Get the active image variant creators $activeImageVariantCreators = $settings->activeImageVariantCreators; @@ -569,6 +568,7 @@ public function createImageVariants(AssetTransformIndex $index, Asset $asset, st public function getActiveImageProcessors(): array { $result = []; + /** @var Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); // Get the active processors for the transform format $activeImageProcessors = $settings->activeImageProcessors; @@ -601,6 +601,7 @@ public function getActiveImageProcessors(): array public function getActiveVariantCreators(): array { $result = []; + /** @var Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); // Get the active image variant creators $activeImageVariantCreators = $settings->activeImageVariantCreators; @@ -636,6 +637,7 @@ public function getActiveVariantCreators(): array protected function applyFiltersToImage(AssetTransform $transform, Asset $asset, Image $image) { + /** @var Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); // Only try to apply filters to Raster images if ($image instanceof Raster) { @@ -808,6 +810,7 @@ protected function executeVariantCreator($variantCreatorCommand, string $tempPat */ protected function cleanupImageVariants(Asset $asset, AssetTransformIndex $transformIndex) { + /** @var Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); $assetTransforms = Craft::$app->getAssetTransforms(); // Get the active image variant creators @@ -877,7 +880,8 @@ protected function copyImageVariantToVolume( Asset $asset, AssetTransformIndex $index, $outputPath - ) { + ) + { // If the image variant creation succeeded, copy it into place if (!empty($outputPath) && is_file($outputPath)) { // Figure out the resulting path for the image variant diff --git a/src/services/OptimizedImages.php b/src/services/OptimizedImages.php index 7b1e7472..1bef4187 100644 --- a/src/services/OptimizedImages.php +++ b/src/services/OptimizedImages.php @@ -15,7 +15,6 @@ use craft\base\ElementInterface; use craft\base\Field; use craft\base\Volume; - use craft\console\Application as ConsoleApplication; use craft\elements\Asset; use craft\errors\ImageException; @@ -30,8 +29,11 @@ use nystudio107\imageoptimize\ImageOptimize; use nystudio107\imageoptimize\jobs\ResaveOptimizedImages; use nystudio107\imageoptimize\models\OptimizedImage; - +use nystudio107\imageoptimize\models\Settings; +use Throwable; use yii\base\InvalidConfigException; +use yii\db\Exception; +use function in_array; /** * @author nystudio107 @@ -59,6 +61,7 @@ public function createOptimizedImages(Asset $asset, array $variants = []) { Craft::beginProfile('createOptimizedImages', __METHOD__); if (empty($variants)) { + /** @var ?Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); if ($settings) { $variants = $settings->defaultVariants; @@ -81,6 +84,7 @@ public function createOptimizedImages(Asset $asset, array $variants = []) public function populateOptimizedImageModel(Asset $asset, $variants, OptimizedImage $model, $force = false) { Craft::beginProfile('populateOptimizedImageModel', __METHOD__); + /** @var Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); // Empty our the optimized image URLs $model->optimizedImageUrls = []; @@ -100,7 +104,7 @@ public function populateOptimizedImageModel(Asset $asset, $variants, OptimizedIm // Only try the transform if it's possible if (Image::canManipulateAsImage($finalFormat) && Image::canManipulateAsImage($asset->getExtension()) - && $asset->height > 0) { + && (int)$asset->height > 0) { // Create the transform based on the variant /** @var AssetTransform $transform */ list($transform, $aspectRatio) = $this->getTransformFromVariant($asset, $variant, $retinaSize); @@ -109,15 +113,15 @@ public function populateOptimizedImageModel(Asset $asset, $variants, OptimizedIm $transforms = Craft::$app->getAssetTransforms(); try { $index = $transforms->getTransformIndex($asset, $transform); - $index->fileExists = 0; + $index->fileExists = false; $transforms->storeTransformIndexData($index); $volume = $asset->getVolume(); $transformPath = $asset->folderPath . $transforms->getTransformSubpath($asset, $index); try { $volume->deleteFile($transformPath); - } catch (\Throwable $exception) { + } catch (Throwable $exception) { } - } catch (\Throwable $e) { + } catch (Throwable $e) { $msg = 'Failed to update transform: ' . $e->getMessage(); Craft::error($msg, __METHOD__); if (Craft::$app instanceof ConsoleApplication) { @@ -158,8 +162,7 @@ public function populateOptimizedImageModel(Asset $asset, $variants, OptimizedIm if (empty($model->optimizedImageUrls)) { $finalFormat = $asset->getExtension(); if (Image::canManipulateAsImage($finalFormat) - && Image::canManipulateAsImage($finalFormat) - && $asset->height > 0) { + && (int)$asset->height > 0) { $variant = [ 'width' => $asset->width, 'useAspectRatio' => false, @@ -231,10 +234,10 @@ public function shouldCreateVariants($field, $asset): bool if (!empty($field->ignoreFilesOfType) && $sourceType !== null) { $ignoreTypes = array_values($field->ignoreFilesOfType); // If `image/svg` is being ignored, add `image/svg+xml` to the mime types to ignore as well - if (\in_array('image/svg', $ignoreTypes, false)) { + if (in_array('image/svg', $ignoreTypes, false)) { $ignoreTypes[] = 'image/svg+xml'; } - if (\in_array($sourceType, $ignoreTypes, false)) { + if (in_array($sourceType, $ignoreTypes, false)) { $createVariants = false; } } @@ -246,7 +249,7 @@ public function shouldCreateVariants($field, $asset): bool * @param ElementInterface $asset * @param boolean $force * - * @throws \yii\db\Exception + * @throws Exception * @throws InvalidConfigException */ public function updateOptimizedImageFieldData(Field $field, ElementInterface $asset, $force = false) @@ -296,9 +299,9 @@ public function updateOptimizedImageFieldData(Field $field, ElementInterface $as * Re-save all of the assets in all of the volumes * * @param int|null $fieldId only for this specific id - * @param boolean Should image variants be forced to be recreated? + * @param bool $force Should image variants be forced to be recreated? * - * @throws \yii\base\InvalidConfigException + * @throws InvalidConfigException */ public function resaveAllVolumesAssets($fieldId = null, $force = false) { @@ -317,14 +320,14 @@ public function resaveAllVolumesAssets($fieldId = null, $force = false) * * @param Volume $volume for this volume * @param int|null $fieldId only for this specific id - * @param boolean Should image variants be forced to be recreated? + * @param bool $force Should image variants be forced to be recreated? * * @throws InvalidConfigException */ public function resaveVolumeAssets(Volume $volume, $fieldId = null, $force = false) { $needToReSave = false; - /** @var FieldLayout $fieldLayout */ + /** @var ?FieldLayout $fieldLayout */ $fieldLayout = $volume->getFieldLayout(); // Loop through the fields in the layout to see if there is an OptimizedImages field if ($fieldLayout) { @@ -375,7 +378,7 @@ public function resaveVolumeAssets(Volume $volume, $fieldId = null, $force = fal * Re-save an individual asset * * @param int $id - * @param boolean Should image variants be forced to be recreated? + * @param bool $force Should image variants be forced to be recreated? */ public function resaveAsset(int $id, $force = false) { @@ -450,6 +453,7 @@ protected function generatePlaceholders(Asset $element, OptimizedImage $model, $ 'generatePlaceholders for: ' . print_r($model, true), __METHOD__ ); + /** @var Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); if ($settings->generatePlaceholders && ImageOptimize::$generatePlaceholders) { $placeholder = ImageOptimize::$plugin->placeholder; @@ -487,6 +491,7 @@ protected function generatePlaceholders(Asset $element, OptimizedImage $model, $ */ protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array { + /** @var Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); $transform = new AssetTransform(); $transform->format = $variant['format'] ?? null; diff --git a/src/services/Placeholder.php b/src/services/Placeholder.php index 9be11729..fc7545e7 100644 --- a/src/services/Placeholder.php +++ b/src/services/Placeholder.php @@ -13,15 +13,18 @@ use ColorThief\ColorThief; use Craft; use craft\base\Component; - use craft\elements\Asset; use craft\helpers\Image; use craft\helpers\StringHelper; use craft\image\Raster; +use Exception; use nystudio107\imageoptimize\helpers\Color as ColorHelper; use nystudio107\imageoptimize\ImageOptimize; - use nystudio107\imageoptimize\lib\Potracio; +use nystudio107\imageoptimize\models\Settings; +use Throwable; +use function function_exists; +use function strlen; /** * @author nystudio107 @@ -117,7 +120,7 @@ public function generateColorPalette(string $tempPath): array // Extract the color palette try { $palette = ColorThief::getPalette($tempPath, 5); - } catch (\Exception $e) { + } catch (Exception $e) { Craft::error($e->getMessage(), __METHOD__); return []; @@ -172,7 +175,7 @@ public function generatePlaceholderSvg(string $tempPath): string if (!empty($tempPath)) { // Potracio depends on `gd` being installed - if (\function_exists('imagecreatefromjpeg')) { + if (function_exists('imagecreatefromjpeg')) { $pot = new Potracio(); $pot->loadImageFromFile($tempPath); $pot->process(); @@ -184,12 +187,13 @@ public function generatePlaceholderSvg(string $tempPath): string $result = ImageOptimize::$plugin->optimizedImages->encodeOptimizedSVGDataUri($result); } } + /** @var Settings $settings */ $settings = ImageOptimize::$plugin->getSettings(); /** * If Potracio failed or gd isn't installed, or this is larger * than MAX_SILHOUETTE_SIZE bytes, just return a box */ - if (empty($result) || ((\strlen($result) > self::MAX_SILHOUETTE_SIZE) && $settings->capSilhouetteSvgSize)) { + if (empty($result) || ((strlen($result) > self::MAX_SILHOUETTE_SIZE) && $settings->capSilhouetteSvgSize)) { $size = getimagesize($tempPath); if ($size !== false) { list($width, $height) = $size; @@ -264,17 +268,17 @@ public function createImageFromPath( int $height, int $quality, $position - ): string { + ): string + { $images = Craft::$app->getImages(); $pathParts = pathinfo($filePath); - /** @var Image $image */ try { if (StringHelper::toLowerCase($pathParts['extension']) === 'svg') { $image = $images->loadImage($filePath, true, $width); } else { $image = $images->loadImage($filePath); } - } catch (\Throwable $e) { + } catch (Throwable $e) { Craft::error( 'Error creating temporary image: ' . $e->getMessage(), __METHOD__ @@ -291,9 +295,11 @@ public function createImageFromPath( $image->scaleAndCrop($width, $height, true, $position); // Strip any EXIF data from the image before trying to save it - $imagineImage = $image->getImagineImage(); - if ($imagineImage) { - $imagineImage->strip(); + if ($image instanceof Raster) { + $imagineImage = $image->getImagineImage(); + if ($imagineImage) { + $imagineImage->strip(); + } } // Save the image out to a temp file, then return its contents @@ -302,7 +308,7 @@ public function createImageFromPath( clearstatcache(true, $tempPath); try { $image->saveAs($tempPath); - } catch (\Throwable $e) { + } catch (Throwable $e) { Craft::error( 'Error saving temporary image: ' . $e->getMessage(), __METHOD__ diff --git a/src/variables/ImageOptimizeVariable.php b/src/variables/ImageOptimizeVariable.php index 599e7f01..c1ae99e6 100755 --- a/src/variables/ImageOptimizeVariable.php +++ b/src/variables/ImageOptimizeVariable.php @@ -13,12 +13,11 @@ use craft\elements\Asset; use craft\helpers\Template; use nystudio107\imageoptimize\ImageOptimize; - use nystudio107\imageoptimize\imagetransforms\ImageTransformInterface; use nystudio107\imageoptimize\models\OptimizedImage; - use nystudio107\pluginvite\variables\ViteVariableInterface; use nystudio107\pluginvite\variables\ViteVariableTrait; +use Twig\Markup; /** * @author nystudio107 @@ -63,7 +62,7 @@ public function renderLazySizesJs($scriptAttrs = [], $variables = []) * @param $height * @param string|null $color * - * @return \Twig_Markup|null + * @return Markup|null */ public function placeholderBox($width, $height, $color = null) { @@ -81,7 +80,8 @@ public function createOptimizedImages( Asset $asset, $variants = null, $generatePlaceholders = false - ) { + ) + { // Override our settings for lengthy operations, since we're doing this via Twig ImageOptimize::$generatePlaceholders = $generatePlaceholders; @@ -106,7 +106,7 @@ public function serverSupportsWebP(): bool * * @return null|ImageTransformInterface The Image Transform */ - public function createImageTransformType($config): ImageTransformInterface + public function createImageTransformType($config): ?ImageTransformInterface { return ImageOptimize::$plugin->optimize->createImageTransformType($config); }