From 3e1de44330affc638dce4b6cd7d3622522b1d442 Mon Sep 17 00:00:00 2001 From: Guillaume ernst Date: Tue, 1 Aug 2023 14:32:11 -0400 Subject: [PATCH] feat(readme): init documentation --- README.md | 36 ++++- config/responsive-image-craft.php | 64 ++++++++ .../scss/_responsive-background-images.scss | 15 ++ src/Commands/GenerateResponsiveImages.php | 120 ++++++++++++++- src/ImageInfoFromString.php | 86 ++++++++++- src/ResponsiveImageCraft.php | 29 +++- src/View/Components/ResponsiveImg.php | 140 +++++++++++++++--- 7 files changed, 453 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 6725239..5615da1 100644 --- a/README.md +++ b/README.md @@ -82,10 +82,44 @@ php artisan vendor:publish --tag="responsive-image-craft-scss" ## Usage +### Images generations + After configuring, the source and targets, run: +```bash +php artisan responsive-image-craft:generate +``` + +Optionally you can define the source + +```bash +php artisan responsive-image-craft:generate --source-disk=local --relative-source-path=images +``` + +### Responsive Image Component + ```php -php artisan image-craft:responsive-generate + +``` +Will generate the following html +```html +
+ + + + [...] + + the alternate text + +
``` ## Testing diff --git a/config/responsive-image-craft.php b/config/responsive-image-craft.php index 10802fb..027673f 100644 --- a/config/responsive-image-craft.php +++ b/config/responsive-image-craft.php @@ -3,11 +3,24 @@ use Spatie\Image\Manipulations; return [ + /* + | Display responsive images in srcset et css variables or display the original one + */ 'use_responsive_images' => env('USE_RESPONSIVE_IMAGES', true), + + /* + | These lines are setting the values of configuration options related to the source and target disks + | and directories for the responsive images. + */ 'source_disk' => env('RESPONSIVE_IMAGES_SOURCE_DISK', 'local'), 'target_disk' => env('RESPONSIVE_IMAGES_TARGET_DISK', 's3'), 'source_directory' => env('RESPONSIVE_IMAGES_SOURCE_DIRECTORY', 'images'), 'target_directory' => env('RESPONSIVE_IMAGES_TARGET_DIRECTORY', 'images'), + + /* + | The `sizes` array contains a list of image sizes in pixels. These sizes are used to generate + | responsive images with different dimensions. + */ 'sizes' => [ 320, 640, @@ -17,24 +30,56 @@ 1760, 2100, ], + + /* + | The `extensions` array contains a list of image formats that are supported by the code. These + | formats include JPEG (JPG), PNG, AVIF, and WEBP. + | @see Spatie\Image\Manipulation for available formats + */ 'extensions' => [ Manipulations::FORMAT_JPG, Manipulations::FORMAT_PNG, Manipulations::FORMAT_AVIF, Manipulations::FORMAT_WEBP, ], + + /* + | The `extensions_filters_rules` array is used to define the image format ignoring rules. Each + | key-value pair in the array represents a format and its corresponding ignoring conversions. + */ 'extensions_filters_rules' => [ Manipulations::FORMAT_JPG => [Manipulations::FORMAT_PNG], Manipulations::FORMAT_PNG => [Manipulations::FORMAT_JPG], Manipulations::FORMAT_WEBP => [], Manipulations::FORMAT_AVIF => [], ], + + /* + | The `extensions_to_ignore` array is used to specify image file extensions that should be ignored by + | the code. In this case, the code is ignoring SVG files. This means that + | any image file with the extension `.svg` will not be processed or included in the responsive images + | generation. + */ 'extensions_to_ignore' => [ 'svg', ], + + /* + | The `filename_to_ignore` array is used to specify image file names that should be ignored by the + | code. In this case, the code is ignoring any image file with the name "favicon". This means that any + | image file with the name "favicon" will not be processed or included in the responsive images + | generation. + */ 'filename_to_ignore' => [ 'favicon', ], + + /* + | The `supported_file_extensions` array is defining the list of image formats that are supported by + | the code. It includes the formats JPEG (JPG), PNG, AVIF, WEBP, and GIF. This means that the code + | will only process and generate responsive images for files with these extensions. Any other image + | formats will be ignored. + */ 'supported_file_extensions' => [ Manipulations::FORMAT_JPG, Manipulations::FORMAT_WEBP, @@ -42,7 +87,26 @@ Manipulations::FORMAT_AVIF, Manipulations::FORMAT_GIF, ], + + /* + | The value of `filename_spacer` is used to split filename from image size. + | e.g.: `my-image-filename.jpg` => `my-image-filename@1200.jpg` + */ 'filename_spacer' => '@', + + /* + | The `'container_css_class_name' => 'img-container',` line is setting the value of the + | `'container_css_class_name'` configuration option to `'img-container'`. This configuration + | option is used to specify the CSS class name that will be applied to the container element of + | the responsive image. By default, the container element will have the CSS class name + | `'img-container'`. + */ 'container_css_class_name' => 'img-container', + + /* + | `'scss_path' => resource_path('/scss/utilities'),` is setting the value of the `'scss_path'` + | configuration option to the path `/scss/utilities` within the `resources` directory. This + | configuration option is used to specify the path to the SCSS where .scss files should be copy + */ 'scss_path' => resource_path('/scss/utilities'), ]; diff --git a/resources/scss/_responsive-background-images.scss b/resources/scss/_responsive-background-images.scss index f9fca9c..b46e96e 100644 --- a/resources/scss/_responsive-background-images.scss +++ b/resources/scss/_responsive-background-images.scss @@ -20,6 +20,11 @@ } } +/** +* The `@mixin media-query` is a Sass mixin that generates media queries based on a given width and +* type (defaulting to "min"). It allows you to write CSS rules that will only apply when the screen +* width matches the specified condition. +*/ @mixin media-query($width, $type: min) { @if $type == max { $width: $width - 1px; @@ -39,6 +44,10 @@ $mimeTypes: ( "tiff": "image/tiff", ); +/** +* The `@mixin responsive-background-image-from-existing-css-var` is a Sass mixin that generates +* responsive background images based on existing CSS variables. +*/ @mixin responsive-background-image-from-existing-css-var( $sizes, $extensions, @@ -74,6 +83,12 @@ $mimeTypes: ( } } +/** +* The `.img-container` class is defining a responsive container for an image. It sets the maximum width of the +* container to 100% of its parent element, ensuring that the image does not exceed the width of the +* container. The height of the container is set to auto, allowing it to adjust proportionally based on +* the width. +*/ .img-container { max-width: 100%; height: auto; diff --git a/src/Commands/GenerateResponsiveImages.php b/src/Commands/GenerateResponsiveImages.php index 0cd3313..7657a5b 100644 --- a/src/Commands/GenerateResponsiveImages.php +++ b/src/Commands/GenerateResponsiveImages.php @@ -19,7 +19,7 @@ class GenerateResponsiveImages extends Command { - protected $signature = 'responsive-image-craft:responsive-generate {--source-disk=} {--relative-source-path=}'; + protected $signature = 'responsive-image-craft:generate {--source-disk=} {--relative-source-path=}'; protected $description = 'Generate responsive images'; @@ -62,9 +62,14 @@ private function generateResponsiveImages(): void }); } + /** + * The function generates and saves responsive images in different sizes and formats. + * + * @param ImageInfoFromString imageString An instance of the class `ImageInfoFromString`, which + * contains information about the image file, such as its absolute pathname and filtered extensions. + */ private function generateAndSaveResponsiveImages(ImageInfoFromString $imageString): void { - $this->temporaryDirectory = (new TemporaryDirectory())->create(); $image = Image::load($imageString->getAbsolutePathname()); @@ -86,6 +91,17 @@ private function generateAndSaveResponsiveImages(ImageInfoFromString $imageStrin $this->treatedImages++; } + /** + * The function saves an image to specified sizes by iterating through the filtered sizes, formatting + * and optimizing the image, and then saving it to a temporary file before storing it to the target + * location. + * + * @param Image image An instance of the Image class, representing the image to be saved. + * @param ImageInfoFromString imageString An instance of the `ImageInfoFromString` class, which + * contains information about the image file such as its filename and width. + * @param string extension The `extension` parameter is a string that represents the file extension of + * the image file. It is used to determine the format in which the image should be saved. + */ private function saveImageToSpecifiedSizes(Image $image, ImageInfoFromString $imageString, string $extension): void { foreach ($imageString->getFilteredSizes($image->getWidth()) as $responsiveWidth) { @@ -102,7 +118,7 @@ private function saveImageToSpecifiedSizes(Image $image, ImageInfoFromString $im $this->storeFileToTarget($imageString, $tempFileName, $fileName); $this->logGeneratedImages($imageString, $extension, $responsiveWidth); - } catch (CouldNotConvert|InvalidImageDriver|InvalidManipulation|InvalidTemporaryDirectory $e) { + } catch (CouldNotConvert | InvalidImageDriver | InvalidManipulation | InvalidTemporaryDirectory $e) { $this->error($e->getMessage()); } catch (Throwable $exception) { $this->error($exception->getMessage()); @@ -110,6 +126,15 @@ private function saveImageToSpecifiedSizes(Image $image, ImageInfoFromString $im } } + /** + * The `optimizeOriginalImage` function optimizes an original image by applying an optimizer chain and + * storing the optimized image to a target location. + * + * @param ImageInfoFromString imageString An instance of the `ImageInfoFromString` class that contains + * information about the image, such as the filename, absolute pathname, and file extension. + * @param int width The `width` parameter is an integer that represents the desired width of the + * optimized image. + */ private function optimizeOriginalImage(ImageInfoFromString $imageString, int $width): void { try { @@ -130,6 +155,18 @@ private function optimizeOriginalImage(ImageInfoFromString $imageString, int $wi } } + /** + * The function optimizes an original image to a specific file extension and saves it to a temporary + * directory. + * + * @param Image image An instance of the `Image` class, which represents the original image to be + * optimized and converted to a specific extension. + * @param ImageInfoFromString imageString An instance of the `ImageInfoFromString` class that contains + * information about the original image, such as the filename and other metadata. + * @param string extension The `extension` parameter is a string that represents the desired file + * extension for the optimized image. It specifies the format in which the image should be saved after + * optimization. + */ private function optimizeOriginalImageToSpecificExtension( Image $image, ImageInfoFromString $imageString, @@ -144,7 +181,7 @@ private function optimizeOriginalImageToSpecificExtension( ->save($tempFileName); $this->storeFileToTarget($imageString, $tempFileName, $newFileName); $this->logGeneratedImages($imageString, $extension, $image->getWidth(), $newFileName); - } catch (CouldNotConvert|InvalidImageDriver|InvalidManipulation|InvalidTemporaryDirectory $e) { + } catch (CouldNotConvert | InvalidImageDriver | InvalidManipulation | InvalidTemporaryDirectory $e) { $this->logError($imageString, $e->getMessage()); $this->error($e->getMessage()); } catch (Throwable $exception) { @@ -153,6 +190,18 @@ private function optimizeOriginalImageToSpecificExtension( } } + /** + * The function stores a file to a target location using the Laravel Storage facade. + * + * @param ImageInfoFromString imageString An instance of the ImageInfoFromString class, which contains + * information about the image file being stored. + * @param string tempFileName The temporary file name of the image that needs to be stored. This is the + * file that is currently being processed or uploaded. + * @param string newFileName The `newFileName` parameter is an optional parameter that specifies the + * name of the file to be stored in the target location. If this parameter is not provided or is empty, + * the filename from the `ImageInfoFromString` object (`->getFilename()`) will be used as + * the name + */ private function storeFileToTarget(ImageInfoFromString $imageString, string $tempFileName, string $newFileName = ''): void { Storage::disk($this->getTargetDisk()) @@ -163,19 +212,46 @@ private function storeFileToTarget(ImageInfoFromString $imageString, string $tem ); } + /** + * The function returns the relative path of an image given an ImageInfoFromString object. + * + * @param ImageInfoFromString imageString An instance of the class `ImageInfoFromString` + * + * @return string the relative path of the image as a string. + */ private function getTargetPath(ImageInfoFromString $imageString): string { return "{$imageString->getRelativePath()}"; } + /** + * The function returns the target file path by concatenating the target path and the filename without + * extension from the given ImageInfoFromString object. + * + * @param ImageInfoFromString imageString The parameter `` is an instance of the + * `ImageInfoFromString` class. + * + * @return string a string that represents the target file path for the given ImageInfoFromString + * object. + */ private function getTargetFilePath(ImageInfoFromString $imageString): string { return "{$this->getTargetPath($imageString)}/{$imageString->getFilenameWithoutExtension()}"; } + /** + * The logError function logs an error message for a given image string and increments the count of + * images in error. + * + * @param ImageInfoFromString imageString The parameter `` is an instance of the + * `ImageInfoFromString` class. It represents an image and contains information about the image, such + * as its relative pathname. + * @param string message The `` parameter is a string that represents the error message to be + * logged. + */ private function logError(ImageInfoFromString $imageString, string $message): void { - if (! Arr::exists($this->logArray['errors'], $imageString->getRelativePathname())) { + if (!Arr::exists($this->logArray['errors'], $imageString->getRelativePathname())) { $this->logArray['errors'][$imageString->getRelativePathname()] = []; } @@ -183,20 +259,37 @@ private function logError(ImageInfoFromString $imageString, string $message): vo $this->imagesInError++; } + /** + * The function logs information about generated images, including the image string, extension, width, + * and optional new file name. + * + * @param ImageInfoFromString imageString The `` parameter is an instance of the + * `ImageInfoFromString` class, which contains information about the image such as its relative + * pathname. + * @param string extension The "extension" parameter is a string that represents the file extension of + * the generated image. It is used to determine the file format of the image file, such as "jpg", + * "png", etc. + * @param int width The "width" parameter in the code snippet represents the width of the generated + * image. It is an integer value that specifies the desired width of the image. + * @param string newFileName The `newFileName` parameter is an optional parameter that allows you to + * specify a custom name for the generated image file. If you provide a value for `newFileName`, it + * will be used as the file name for the generated image. If you don't provide a value for + * `newFileName`, a + */ private function logGeneratedImages( ImageInfoFromString $imageString, string $extension, int $width, string $newFileName = '' ): void { - if (! Arr::exists($this->logArray['generated'], $imageString->getRelativePathname())) { + if (!Arr::exists($this->logArray['generated'], $imageString->getRelativePathname())) { $this->logArray['generated'][$imageString->getRelativePathname()] = []; } - if (! Arr::exists($this->logArray['generated'][$imageString->getRelativePathname()], $extension)) { + if (!Arr::exists($this->logArray['generated'][$imageString->getRelativePathname()], $extension)) { $this->logArray['generated'][$imageString->getRelativePathname()][$extension] = []; } - $filName = ! empty($newFileName) ? + $filName = !empty($newFileName) ? $newFileName : "{$this->getTargetFilePath($imageString)}{$this->getFilenameSpacer()}$width.$extension"; @@ -205,6 +298,13 @@ private function logGeneratedImages( $this->generatedImages++; } + /** + * The function `getFilteredImages()` retrieves a collection of image files from a specified disk and + * directory, filters out unsupported file types, and returns a collection of `ImageInfoFromString` + * objects. + * + * @return Collection a Collection of ImageInfoFromString objects. + */ private function getFilteredImages(): Collection { $imageFiles = Storage::disk($this->getSourceDisk())->allFiles($this->getSourceDirectory()); @@ -216,6 +316,10 @@ private function getFilteredImages(): Collection }); } + /** + * The function `storeLogToJsonFile` stores the log array as a JSON file with a timestamp in the + * specified target directory and disk. + */ private function storeLogToJsonFile(): void { $this->logArray['generated_on'] = Carbon::now()->format('Y-m-d H:i:s'); diff --git a/src/ImageInfoFromString.php b/src/ImageInfoFromString.php index bd5dccb..01f10b4 100644 --- a/src/ImageInfoFromString.php +++ b/src/ImageInfoFromString.php @@ -6,6 +6,14 @@ use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; +/** + * The `ImageInfoFromString` class is responsible for extracting information from the file path string. + * It provides methods to retrieve various details about the file, such as the absolute path, relative + * path, file name, file extension, and more. It also includes methods to check if the file is a + * supported image file and if it meets certain criteria, such as accepted extensions and file names. + * @param string file The `file` parameter is the string path to the file + * + */ class ImageInfoFromString { public function __construct( @@ -13,15 +21,21 @@ public function __construct( ) { } + /** + * The function returns the absolute path name of the file using the Laravel Storage facade. + * + * @return string the absolute path name of the file. + */ public function getAbsolutePathname(): string { return Storage::disk($this->getSourceDisk())->path($this->getRelativePathname()); } /** - * Returns the relative path. + * The function returns the relative path of the file by removing the filename and the last directory + * from the given file path. * - * This path does not contain the file name. + * @return string the relative path of the file, this path does not contain the file name. */ public function getRelativePath(): string { @@ -31,25 +45,31 @@ public function getRelativePath(): string } /** - * Returns the relative path name. + * The function "getRelativePathname" returns the file path as a string. * - * This path contains the file name. + * @return string the value of the variable `file`, which is a string. */ public function getRelativePathname(): string { return $this->file; } + /** - * Returns the relative path name. + * The function returns the relative pathname of the file without its extension. * - * This path contains the file name without extension. + * @return string a string that represents the relative pathname of the file without its extension. */ public function getRelativePathnameWithoutExtension(): string { return Str::beforeLast(Str::beforeLast($this->file, $this->getFileExtension()), '.'); } + /** + * The function `getFilenameWithoutExtension` returns the filename without the file extension. + * + * @return string the filename without the file extension. + */ public function getFilenameWithoutExtension(): string { $filename = $this->getFilename(); @@ -57,6 +77,11 @@ public function getFilenameWithoutExtension(): string return pathinfo($filename, PATHINFO_FILENAME); } + /** + * The getFileExtension function returns the lowercase file extension of a given file path. + * + * @return string the file extension in lowercase. + */ public function getFileExtension(): string { $extension = pathinfo($this->file, PATHINFO_EXTENSION); @@ -64,16 +89,32 @@ public function getFileExtension(): string return strtolower($extension); } + /** + * The function returns the base name of the file path. + * + * @return string the base name of the file. + */ public function getFilename(): string { return pathinfo($this->file, PATHINFO_BASENAME); } + /** + * The function checks if the file is an image, has an accepted extension, and has an accepted file name. + * + * @return bool a boolean value. + */ public function isSupportedFile(): bool { return $this->isImage() && $this->isAcceptedExtension() && $this->isAcceptedFileName(); } + /** + * The function returns an array of filtered extensions by excluding the ones specified in the excluded + * extensions list. + * + * @return array an array of filtered extensions. + */ public function getFilteredExtensions(): array { return array_diff( @@ -82,6 +123,14 @@ public function getFilteredExtensions(): array ); } + /** + * The function `getFilteredSizes` filters an array of sizes based on a maximum image width. + * + * @param int imagMaxWidth The `imagMaxWidth` parameter is an integer representing the maximum width of + * an image. + * + * @return array An array of sizes that are less than or equal to the given ``. + */ public function getFilteredSizes(int $imagMaxWidth): array { return array_filter(config('responsive-image-craft.sizes'), function ($width) use ($imagMaxWidth) { @@ -89,16 +138,31 @@ public function getFilteredSizes(int $imagMaxWidth): array }); } + /** + * The function checks if the file extension is not in the list of extensions to ignore. + * + * @return bool a boolean value. + */ private function isAcceptedExtension(): bool { - return ! in_array($this->getFileExtension(), $this->getExtensionsToIgnore()); + return !in_array($this->getFileExtension(), $this->getExtensionsToIgnore()); } + /** + * The function checks if the filename without extension is not in the list of filenames to ignore. + * + * @return bool a boolean value. + */ private function isAcceptedFileName(): bool { - return ! in_array($this->getFilenameWithoutExtension(), $this->getFileNamesToIgnore()); + return !in_array($this->getFilenameWithoutExtension(), $this->getFileNamesToIgnore()); } + /** + * The function checks if the file extension is in the list of supported image extensions. + * + * @return bool a boolean value. + */ private function isImage(): bool { return in_array( @@ -107,6 +171,12 @@ private function isImage(): bool ); } + /** + * The function `getExcludedExtensions` returns an array of excluded extensions based on the file + * extension of the current file. + * + * @return array an array. + */ private function getExcludedExtensions(): array { if (Arr::exists(config('responsive-image-craft.extensions_filters_rules', []), $this->getFileExtension())) { diff --git a/src/ResponsiveImageCraft.php b/src/ResponsiveImageCraft.php index 2668852..a6a3eca 100755 --- a/src/ResponsiveImageCraft.php +++ b/src/ResponsiveImageCraft.php @@ -4,7 +4,21 @@ class ResponsiveImageCraft { - public function getCssVariables(string $file, int $maxWidth, array $extensions = ['jpg', 'avif', 'webp']) + /** + * The function `getCssVariables` generates CSS variables for a given image file and its resized + * versions based on the maximum width provided. + * The variable is intended to be used in the `background-image` css property. + * + * @param string file The file parameter is a string that represents the path to an image file. + * @param int maxWidth The parameter is an integer that represents the maximum width of the + * image. It is used to filter the available image sizes and generate CSS variables for each size that + * is smaller or equal to the maximum width. + * @param array extensions An array of file extensions (e.g., ['jpg', 'avif', 'webp']) that will be + * used to generate CSS variables for different image formats. + * + * @return string a string containing CSS variables. + */ + public function getCssVariables(string $file, int $maxWidth, array $extensions = ['jpg', 'avif', 'webp']): string { $image = new ImageInfoFromString($file); $path = $image->getRelativePathnameWithoutExtension(); @@ -14,13 +28,24 @@ public function getCssVariables(string $file, int $maxWidth, array $extensions = $cssVariables = $this->generateCssVariables($path, $extensions, 'full'); foreach ($image->getFilteredSizes($maxWidth) as $width) { - $file = $path.$fileNameSpacer.$width; + $file = $path . $fileNameSpacer . $width; $cssVariables .= $this->generateCssVariables($file, $extensions, $width); } return $cssVariables; } + /** + * The function generates CSS variables for a given path, array of extensions, and width. + * + * @param string path The path parameter is a string that represents the base path or URL of the image + * file. + * @param array extensions An array of file extensions (e.g., ['jpg', 'png', 'svg']). + * @param string width The `` parameter can be either a string or an integer. It represents the + * width of an element in CSS. + * + * @return string a string containing CSS variables. + */ private function generateCssVariables(string $path, array $extensions, string|int $width): string { $cssVariables = ''; diff --git a/src/View/Components/ResponsiveImg.php b/src/View/Components/ResponsiveImg.php index 60f9fbf..be092d0 100644 --- a/src/View/Components/ResponsiveImg.php +++ b/src/View/Components/ResponsiveImg.php @@ -21,15 +21,11 @@ class ResponsiveImg extends Component 'tiff' => 'image/tiff', ]; - /** - * Create a new component instance. - */ public function __construct( public string $src, public string $alt = '', public ?int $width = null, public ?int $height = null, - public array $sizes = [], private bool $lazy = true, private bool $asyncDecoding = true, public bool $skipPictureTag = false, @@ -39,34 +35,51 @@ public function __construct( // } - /** - * Get the view / contents that represent the component. - */ public function render(): View|Closure|string { return view('responsive-image-craft::components.responsive-img'); } + /** + * The function returns the CSS class name for a container element, combining a default class name with + * an optional custom class name. + * + * @return string a string value. + */ public function getContainerCssClass(): string { - $cssClass = config('responsive-images.container_css_class_name'); + $cssClass = config('responsive-image-craft.container_css_class_name'); - if (! empty($this->containerClass)) { + if (!empty($this->containerClass)) { return "$cssClass {$this->containerClass}"; } return $cssClass; } + /** + * The function returns an array of filtered extensions by removing excluded extensions and the + * original extension. + * + * @return array an array that contains the filtered extensions. + */ public function getFilteredExtensions(): array { return array_diff( - config('responsive-images.extensions'), + config('responsive-image-craft.extensions'), $this->getExcludedExtensions(), [$this->getOriginalExtension()] ); } + /** + * The getImageType function returns the MIME type of an image based on its file extension. + * + * @param string extension A string representing the file extension of an image file. + * + * @return string a string value. If the given extension exists in the `MIME_TYPES` array, it will + * return the corresponding value from the array. Otherwise, it will return an empty string. + */ public function getImageType(string $extension): string { if (Arr::exists(self::MIME_TYPES, $extension)) { @@ -76,6 +89,15 @@ public function getImageType(string $extension): string return ''; } + /** + * The function `getSrcset` generates a string containing a list of image URLs and their corresponding + * sizes in the specified extension for use in the `srcset` attribute of an HTML `` or `` tag. + * + * @param string extension The parameter "extension" is a string that represents the file extension of + * the image. It is used to construct the image filenames in the srcset. + * + * @return string a string that represents the srcset attribute value for an image. + */ public function getSrcset(string $extension): string { $srcset = ''; @@ -92,61 +114,128 @@ public function getSrcset(string $extension): string return trim(Str::beforeLast($srcset, ',')); } + /** + * The function checks if the use of responsive images is enabled in the configuration. + * + * @return bool the value of the configuration variable 'responsive-image-craft.use_responsive_images'. + */ public function useResponsiveImages(): bool { - return config('responsive-images.use_responsive_images'); + return config('responsive-image-craft.use_responsive_images'); } + /** + * The function "getOriginalSrcset" returns the srcset attribute value for the original image + * extension. + * + * @return string a string. + */ public function getOriginalSrcset(): string { return $this->getSrcset($this->getOriginalExtension()); } + /** + * The function returns the loading type, either "lazy" or "eager", based on the value of the "lazy" + * property. + * Images in First Contentful Paint should be eager loaded + * @see https://developer.mozilla.org/docs/Web/API/HTMLImageElement/loading + * + * @return string The method is returning a string value. If the `lazy` property is true, it will + * return the string 'lazy'. Otherwise, it will return the string 'eager'. + */ public function getLoading(): string { return $this->lazy ? 'lazy' : 'eager'; } + /** + * The function returns the decoding mode, either 'async' or 'auto'. + * @see https://developer.mozilla.org/docs/Web/API/HTMLImageElement/decoding + * + * @return string The method is returning a string value. If the value of the property `asyncDecoding` + * is true, then the string 'async' is returned. Otherwise, the string 'auto' is returned. + */ public function getDecoding(): string { return $this->asyncDecoding ? 'async' : 'auto'; } + /** + * The getAltAttribute function returns the alt attribute value, using the app name if the alt + * attribute is empty. + * + * @return string a string value. If the `` property is empty, it will return the value of + * `config('app.name')`, otherwise it will return the value of `->alt`. + */ public function getAltAttribute(): string { return empty($this->alt) ? config('app.name') : $this->alt; } + /** + * The function returns an instance of the ImageInfoFromString class with the source image as a + * parameter. + * + * @return ImageInfoFromString An instance of the `ImageInfoFromString` class is being returned. + */ private function getImageInfo(): ImageInfoFromString { return new ImageInfoFromString($this->src); } + /** + * The function returns an array of filtered sizes based on the width property, or all sizes if the + * width is empty. + * + * @return array an array. + */ private function getFilteredSizes(): array { - if (! empty($this->width)) { - return array_filter(config('responsive-images.sizes'), function ($responsiveWidth) { + if (!empty($this->width)) { + return array_filter(config('responsive-image-craft.sizes'), function ($responsiveWidth) { return $responsiveWidth <= $this->width; }); } - return config('responsive-images.sizes'); + return config('responsive-image-craft.sizes'); } + /** + * The function "getOriginalExtension" returns the file extension of the image. + * + * @return string a string value. + */ private function getOriginalExtension(): string { return $this->getImageInfo()->getFileExtension(); } + /** + * The function returns an array of excluded extensions based on the original extension of the image + * and the ignoring rules. + * + * @return array an array. + */ private function getExcludedExtensions(): array { - if (Arr::exists(config('responsive-images.extensions_filters_rules', []), $this->getOriginalExtension())) { - return Arr::get(config('responsive-images.extensions_filters_rules', []), $this->getOriginalExtension()); + if (Arr::exists(config('responsive-image-craft.extensions_filters_rules', []), $this->getOriginalExtension())) { + return Arr::get( + config('responsive-image-craft.extensions_filters_rules', []), + $this->getOriginalExtension() + ); } return []; } + /** + * The `getWidth` function returns the maximum width value from the filtered sizes, or the stored width + * value if it is not empty. + * + * @return int the value of `->width` if it is not empty. Otherwise, it returns the highest value + * from the available image size. + */ private function getWidth(): int { if (empty($this->width)) { @@ -156,13 +245,28 @@ private function getWidth(): int return $this->width; } + /** + * The function returns the value of the 'filename_spacer' configuration option. + * + * @return string the value of the configuration variable 'responsive-image-craft.filename_spacer'. + */ private function getFilenameSpacer(): string { - return config('responsive-images.filename_spacer'); + return config('responsive-image-craft.filename_spacer'); } + /** + * The function returns the URL base path to image following the `useResponsiveImages` value. + * + * @return string the value of the 'url' key in the disk configuration in the 'filesystems' + * configuration file. + */ public function getUrlBasePath(): string { - return config('filesystems.disks.do.url'); + if ($this->useResponsiveImages()) { + return config('filesystems.disks.' . config("responsive-image-craft.target_disk") . '.url'); + } + + return config('filesystems.disks.' . config("responsive-image-craft.source_disk") . '.url'); } }