diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 00000000..e89ee99b --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,6 @@ +parameters: + level: 1 + paths: + - src + ignoreErrors: + - '#Unsafe usage of new static\(\)#' diff --git a/src/Api/Admin/AdminApi.php b/src/Api/Admin/AdminApi.php index dff21d28..1617e630 100644 --- a/src/Api/Admin/AdminApi.php +++ b/src/Api/Admin/AdminApi.php @@ -47,10 +47,10 @@ class AdminApi /** * AdminApi constructor. * - * @param mixed $configuration + * @param mixed|null $configuration * * @noinspection UnusedConstructorDependenciesInspection*/ - public function __construct($configuration = null) + public function __construct(mixed $configuration = null) { $this->apiClient = new ApiClient($configuration); diff --git a/src/Api/Admin/AnalysisTrait.php b/src/Api/Admin/AnalysisTrait.php index 382fd811..e7b632cf 100644 --- a/src/Api/Admin/AnalysisTrait.php +++ b/src/Api/Admin/AnalysisTrait.php @@ -26,37 +26,42 @@ trait AnalysisTrait /** * Analyzes an asset with the requested analysis type. * - * @param string $inputType The type of input for the asset to analyze ('uri'). - * @param string $analysisType The type of analysis to run ('google_tagging', 'captioning', 'fashion'). - * @param string $uri The URI of the asset to analyze. - * @param array $parameters Additional parameters. + * @param string $inputType The type of input for the asset to analyze ('uri'). + * @param string $analysisType The type of analysis to run ('google_tagging', 'captioning', 'fashion'). + * @param string|null $uri The URI of the asset to analyze. + * @param array|null $parameters Additional parameters. * * - * @return ApiResponse * * @see AdminApi::analyzeAsync() * * @see https://cloudinary.com/documentation/media_analyzer_api_reference */ - public function analyze($inputType, $analysisType, $uri = null, $parameters = null) - { + public function analyze( + string $inputType, + string $analysisType, + ?string $uri = null, + ?array $parameters = null + ): ApiResponse { return $this->analyzeAsync($inputType, $analysisType, $uri, $parameters)->wait(); } /** * Analyzes an asset with the requested analysis type asynchronously. * - * @param string $inputType The type of input for the asset to analyze ('uri'). - * @param string $analysisType The type of analysis to run ('google_tagging', 'captioning', 'fashion'). - * @param string $uri The URI of the asset to analyze. - * @param array $parameters Additional parameters. - * - * @return PromiseInterface + * @param string $inputType The type of input for the asset to analyze ('uri'). + * @param string $analysisType The type of analysis to run ('google_tagging', 'captioning', 'fashion'). + * @param string|null $uri The URI of the asset to analyze. + * @param array|null $parameters Additional parameters. * * @see https://cloudinary.com/documentation/media_analyzer_api_reference */ - public function analyzeAsync($inputType, $analysisType, $uri = null, $parameters = null) - { + public function analyzeAsync( + string $inputType, + string $analysisType, + ?string $uri = null, + ?array $parameters = null + ): PromiseInterface { $endPoint = [ApiEndPoint::ANALYSIS, 'analyze', $inputType]; $params = ['analysis_type' => $analysisType, 'uri' => $uri, 'parameters' => $parameters]; diff --git a/src/Api/Admin/ApiEndPoint.php b/src/Api/Admin/ApiEndPoint.php index 6da5cd28..b1810b06 100644 --- a/src/Api/Admin/ApiEndPoint.php +++ b/src/Api/Admin/ApiEndPoint.php @@ -15,18 +15,18 @@ */ class ApiEndPoint { - const PING = 'ping'; - const CONFIG = 'config'; - const USAGE = 'usage'; - const ASSETS = 'resources'; - const DERIVED_ASSETS = 'derived_resources'; - const RELATED_ASSETS = 'related_assets'; - const FOLDERS = 'folders'; - const TAGS = 'tags'; - const STREAMING_PROFILES = 'streaming_profiles'; - const TRANSFORMATIONS = 'transformations'; - const UPLOAD_PRESETS = 'upload_presets'; - const UPLOAD_MAPPINGS = 'upload_mappings'; - const METADATA_FIELDS = 'metadata_fields'; - const ANALYSIS = 'analysis'; + public const PING = 'ping'; + public const CONFIG = 'config'; + public const USAGE = 'usage'; + public const ASSETS = 'resources'; + public const DERIVED_ASSETS = 'derived_resources'; + public const RELATED_ASSETS = 'related_assets'; + public const FOLDERS = 'folders'; + public const TAGS = 'tags'; + public const STREAMING_PROFILES = 'streaming_profiles'; + public const TRANSFORMATIONS = 'transformations'; + public const UPLOAD_PRESETS = 'upload_presets'; + public const UPLOAD_MAPPINGS = 'upload_mappings'; + public const METADATA_FIELDS = 'metadata_fields'; + public const ANALYSIS = 'analysis'; } diff --git a/src/Api/Admin/AssetsTrait.php b/src/Api/Admin/AssetsTrait.php index c23d86a2..d058e3b3 100644 --- a/src/Api/Admin/AssetsTrait.php +++ b/src/Api/Admin/AssetsTrait.php @@ -18,7 +18,6 @@ use Cloudinary\Asset\AssetType; use Cloudinary\Asset\DeliveryType; use Cloudinary\Asset\ModerationStatus; -use Cloudinary\StringUtils; /** * Enables you to manage the assets in your cloud. @@ -36,9 +35,8 @@ trait AssetsTrait /** * Lists available asset types. * - * @return ApiResponse */ - public function assetTypes() + public function assetTypes(): ApiResponse { return $this->apiClient->get(ApiEndPoint::ASSETS); } @@ -49,11 +47,10 @@ public function assetTypes() * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_resources */ - public function assets($options = []) + public function assets(array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $uri = [ApiEndPoint::ASSETS, $assetType]; @@ -76,11 +73,10 @@ public function assets($options = []) * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_resources_by_tag */ - public function assetsByTag($tag, $options = []) + public function assetsByTag(string $tag, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $uri = [ApiEndPoint::ASSETS, $assetType, 'tags', $tag]; @@ -94,18 +90,17 @@ public function assetsByTag($tag, $options = []) * * This method does not return matching deleted assets, even if they have been backed up. * - * @param string $key Only assets with this context key are returned. - * @param string $value Only assets with this context value for the specified context key are returned. + * @param string $key Only assets with this context key are returned. + * @param string|null $value Only assets with this context value for the specified context key are returned. * If this parameter is not provided, all assets with the specified context key are returned, * regardless of the key value. - * @param array $options The optional parameters. See the + * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_resources_by_context */ - public function assetsByContext($key, $value = null, $options = []) + public function assetsByContext(string $key, ?string $value = null, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $uri = [ApiEndPoint::ASSETS, $assetType, 'context']; @@ -126,11 +121,10 @@ public function assetsByContext($key, $value = null, $options = []) * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_resources_in_moderation_queues */ - public function assetsByModeration($kind, $status, $options = []) + public function assetsByModeration(string $kind, string $status, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $uri = [ApiEndPoint::ASSETS, $assetType, 'moderations', $kind, $status]; @@ -143,15 +137,14 @@ public function assetsByModeration($kind, $status, $options = []) /** * Lists assets with the specified public IDs. * - * @param string|array $publicIds The requested public_ids (up to 100). + * @param array|string $publicIds The requested public_ids (up to 100). * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_resources */ - public function assetsByIds($publicIds, $options = []) + public function assetsByIds(array|string $publicIds, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $type = ArrayUtils::get($options, DeliveryType::KEY, DeliveryType::UPLOAD); @@ -166,15 +159,14 @@ public function assetsByIds($publicIds, $options = []) /** * Lists assets with the specified asset IDs. * - * @param string|array $assetIds The requested asset IDs. - * @param array $options The optional parameters. See the + * @param array|string $assetIds The requested asset IDs. + * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_resources */ - public function assetsByAssetIds($assetIds, $options = []) + public function assetsByAssetIds(array|string $assetIds, array $options = []): ApiResponse { $uri = [ApiEndPoint::ASSETS, 'by_asset_ids']; @@ -192,11 +184,10 @@ public function assetsByAssetIds($assetIds, $options = []) * Admin * API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/dynamic_folders */ - public function assetsByAssetFolder($assetFolder, $options = []) + public function assetsByAssetFolder(string $assetFolder, array $options = []): ApiResponse { $uri = [ApiEndPoint::ASSETS, 'by_asset_folder']; @@ -214,13 +205,12 @@ public function assetsByAssetFolder($assetFolder, $options = []) * AdminAPI documentation. * - * @return ApiResponse * * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#visual_search_for_resources */ - public function visualSearch($options = []) + public function visualSearch(array $options = []): ApiResponse { $uri = [ApiEndPoint::ASSETS, 'visual_search']; @@ -249,11 +239,10 @@ public function visualSearch($options = []) * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_the_details_of_a_single_resource */ - public function asset($publicId, $options = []) + public function asset(string $publicId, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $type = ArrayUtils::get($options, DeliveryType::KEY, DeliveryType::UPLOAD); @@ -278,11 +267,10 @@ public function asset($publicId, $options = []) * href=https://cloudinary.com/documentation/admin_api#get_the_details_of_a_single_resource * target="_blank"> Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_the_details_of_a_single_resource */ - public function assetByAssetId($assetId, $options = []) + public function assetByAssetId(string $assetId, array $options = []): ApiResponse { $uri = [ApiEndPoint::ASSETS, $assetId]; @@ -294,16 +282,15 @@ public function assetByAssetId($assetId, $options = []) /** * Reverts to the latest backed up version of the specified deleted assets. * - * @param string|array $publicIds The public IDs of the backed up assets to restore. They can be existing or + * @param array|string $publicIds The public IDs of the backed up assets to restore. They can be existing or * deleted assets. * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#restore_resources */ - public function restore($publicIds, $options = []) + public function restore(array|string $publicIds, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $type = ArrayUtils::get($options, DeliveryType::KEY, DeliveryType::UPLOAD); @@ -320,15 +307,14 @@ public function restore($publicIds, $options = []) * Update one or more of the attributes associated with a specified asset. Note that you can also update * most attributes of an existing asset using the Uploader::explicit method, which is not rate limited. * - * @param string|array $publicId The public ID of the asset to update. + * @param array|string $publicId The public ID of the asset to update. * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#update_details_of_an_existing_resource */ - public function update($publicId, $options = []) + public function update(array|string $publicId, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $type = ArrayUtils::get($options, DeliveryType::KEY, DeliveryType::UPLOAD); @@ -370,17 +356,13 @@ public function update($publicId, $options = []) /** * Deletes the specified assets. * - * @param string|array $publicIds The public IDs of the assets to delete (up to 100). + * @param array|string $publicIds The public IDs of the assets to delete (up to 100). * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse - * - * @throws ApiError - * * @see https://cloudinary.com/documentation/admin_api#delete_resources */ - public function deleteAssets($publicIds, $options = []) + public function deleteAssets(array|string $publicIds, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $type = ArrayUtils::get($options, DeliveryType::KEY, DeliveryType::UPLOAD); @@ -401,13 +383,11 @@ public function deleteAssets($publicIds, $options = []) * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#delete_resources */ - public function deleteAssetsByPrefix($prefix, $options = []) + public function deleteAssetsByPrefix(string $prefix, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $type = ArrayUtils::get($options, DeliveryType::KEY, DeliveryType::UPLOAD); @@ -426,13 +406,11 @@ public function deleteAssetsByPrefix($prefix, $options = []) * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * - * @throws ApiError * * https://cloudinary.com/documentation/admin_api#delete_resources */ - public function deleteAllAssets($options = []) + public function deleteAllAssets(array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $type = ArrayUtils::get($options, DeliveryType::KEY, DeliveryType::UPLOAD); @@ -451,13 +429,11 @@ public function deleteAllAssets($options = []) * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#delete_resources_by_tags */ - public function deleteAssetsByTag($tag, $options = []) + public function deleteAssetsByTag(string $tag, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $uri = [ApiEndPoint::ASSETS, $assetType, 'tags', $tag]; @@ -472,15 +448,13 @@ public function deleteAssetsByTag($tag, $options = []) * The derived asset IDs for a particular original asset are returned when calling the `asset` method to * return the details of a single asset. * - * @param string|array $derived_asset_ids The derived asset IDs (up to 100 ids). + * @param array|string $derived_asset_ids The derived asset IDs (up to 100 ids). * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api##delete_resources */ - public function deleteDerivedAssets($derived_asset_ids) + public function deleteDerivedAssets(array|string $derived_asset_ids): ApiResponse { $uri = ApiEndPoint::DERIVED_ASSETS; $params = ['derived_resource_ids' => $derived_asset_ids]; @@ -491,16 +465,14 @@ public function deleteDerivedAssets($derived_asset_ids) /** * Deletes derived assets identified by transformation and public_ids. * - * @param string|array $publicIds The public IDs for which you want to delete derived assets. - * @param string|array $transformations The transformation(s) associated with the derived assets to delete. + * @param array|string $publicIds The public IDs for which you want to delete derived assets. + * @param array|string $transformations The transformation(s) associated with the derived assets to delete. * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * - * @throws ApiError */ - public function deleteDerivedByTransformation($publicIds, $transformations = [], $options = []) + public function deleteDerivedByTransformation(array|string $publicIds, array|string $transformations = [], array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $type = ArrayUtils::get($options, DeliveryType::KEY, DeliveryType::UPLOAD); @@ -519,15 +491,14 @@ public function deleteDerivedByTransformation($publicIds, $transformations = [], /** * Relates an asset to other assets by public IDs. * - * @param string $publicId The public ID of the asset to update. - * @param array $assetsToRelate The array of up to 10 fully_qualified_public_ids given as + * @param string $publicId The public ID of the asset to update. + * @param array $assetsToRelate The array of up to 10 fully_qualified_public_ids given as * resource_type/type/public_id. - * @param array $options The optional parameters. See the + * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse */ - public function addRelatedAssets($publicId, $assetsToRelate, $options = []) + public function addRelatedAssets(string $publicId, array $assetsToRelate, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $type = ArrayUtils::get($options, DeliveryType::KEY, DeliveryType::UPLOAD); @@ -544,12 +515,11 @@ public function addRelatedAssets($publicId, $assetsToRelate, $options = []) /** * Relates an asset to other assets by asset IDs. * - * @param string $assetId The asset ID of the asset to update. - * @param array $assetsToRelate The array of up to 10 asset IDs. + * @param string $assetId The asset ID of the asset to update. + * @param array $assetsToRelate The array of up to 10 asset IDs. * - * @return ApiResponse */ - public function addRelatedAssetsByAssetIds($assetId, $assetsToRelate) + public function addRelatedAssetsByAssetIds(string $assetId, array $assetsToRelate): ApiResponse { $uri = [ApiEndPoint::ASSETS, ApiEndPoint::RELATED_ASSETS, $assetId]; @@ -563,15 +533,14 @@ public function addRelatedAssetsByAssetIds($assetId, $assetsToRelate) /** * Unrelates an asset from other assets by public IDs. * - * @param string $publicId The public ID of the asset to update. - * @param array $assetsToUnrelate The array of up to 10 fully_qualified_public_ids given as + * @param string $publicId The public ID of the asset to update. + * @param array $assetsToUnrelate The array of up to 10 fully_qualified_public_ids given as * resource_type/type/public_id. - * @param array $options The optional parameters. See the + * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse */ - public function deleteRelatedAssets($publicId, $assetsToUnrelate, $options = []) + public function deleteRelatedAssets(string $publicId, array $assetsToUnrelate, array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $type = ArrayUtils::get($options, DeliveryType::KEY, DeliveryType::UPLOAD); @@ -591,9 +560,8 @@ public function deleteRelatedAssets($publicId, $assetsToUnrelate, $options = []) * @param string $assetId The asset ID of the asset to update. * @param array $assetsToUnrelate The array of up to 10 asset IDs. * - * @return ApiResponse */ - public function deleteRelatedAssetsByAssetIds($assetId, $assetsToUnrelate) + public function deleteRelatedAssetsByAssetIds(string $assetId, array $assetsToUnrelate): ApiResponse { $uri = [ApiEndPoint::ASSETS, ApiEndPoint::RELATED_ASSETS, $assetId]; @@ -614,7 +582,7 @@ public function deleteRelatedAssetsByAssetIds($assetId, $assetsToUnrelate) * * @internal */ - protected static function prepareDeleteAssetParams($options, $params = []) + protected static function prepareDeleteAssetParams(array $options, array $params = []): array { $filtered = ArrayUtils::whitelist($options, ['keep_original', 'next_cursor', 'invalidate']); if (isset($options['transformations'])) { @@ -633,7 +601,7 @@ protected static function prepareDeleteAssetParams($options, $params = []) * * @internal */ - protected static function prepareAssetDetailsParams($options) + protected static function prepareAssetDetailsParams(array $options): array { return ArrayUtils::whitelist( $options, @@ -667,10 +635,10 @@ protected static function prepareAssetDetailsParams($options) * * @internal */ - protected static function prepareAssetsParams($options) + protected static function prepareAssetsParams(array $options): array { $params = ArrayUtils::whitelist($options, ['tags', 'context', 'metadata', 'moderations']); - $params['fields'] = ApiUtils::serializeSimpleApiParam((ArrayUtils::get($options, 'fields'))); + $params['fields'] = ApiUtils::serializeSimpleApiParam(ArrayUtils::get($options, 'fields')); return $params; } @@ -684,7 +652,7 @@ protected static function prepareAssetsParams($options) * * @internal */ - protected static function prepareListAssetsParams($options) + protected static function prepareListAssetsParams(array $options): array { return array_merge( self::prepareAssetsParams($options), diff --git a/src/Api/Admin/FoldersTrait.php b/src/Api/Admin/FoldersTrait.php index 7274089f..7ce93eb9 100644 --- a/src/Api/Admin/FoldersTrait.php +++ b/src/Api/Admin/FoldersTrait.php @@ -35,11 +35,10 @@ trait FoldersTrait * Admin API * documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_root_folders */ - public function rootFolders($options = []) + public function rootFolders(array $options = []): ApiResponse { $params = ArrayUtils::whitelist($options, ['next_cursor', 'max_results']); @@ -55,13 +54,11 @@ public function rootFolders($options = []) * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#get_subfolders */ - public function subFolders($ofFolderPath, $options = []) + public function subFolders(string $ofFolderPath, array $options = []): ApiResponse { $uri = [ApiEndPoint::FOLDERS, $ofFolderPath]; $params = ArrayUtils::whitelist($options, ['next_cursor', 'max_results']); @@ -74,13 +71,11 @@ public function subFolders($ofFolderPath, $options = []) * * @param string $path The full path of the new folder to create. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#create_folder */ - public function createFolder($path) + public function createFolder(string $path): ApiResponse { $uri = [ApiEndPoint::FOLDERS, $path]; @@ -93,13 +88,11 @@ public function createFolder($path) * @param string $fromPath The full path of an existing asset folder. * @param string $toPath The full path of the new asset folder. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#rename_folder */ - public function renameFolder($fromPath, $toPath) + public function renameFolder(string $fromPath, string $toPath): ApiResponse { $uri = [ApiEndPoint::FOLDERS, $fromPath]; @@ -115,13 +108,11 @@ public function renameFolder($fromPath, $toPath) * * @param string $path The full path of the empty folder to delete. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#delete_folder */ - public function deleteFolder($path) + public function deleteFolder(string $path): ApiResponse { $uri = [ApiEndPoint::FOLDERS, $path]; diff --git a/src/Api/Admin/MetadataFieldsTrait.php b/src/Api/Admin/MetadataFieldsTrait.php index d466b003..c3e53d05 100644 --- a/src/Api/Admin/MetadataFieldsTrait.php +++ b/src/Api/Admin/MetadataFieldsTrait.php @@ -34,7 +34,7 @@ trait MetadataFieldsTrait * * @return ApiResponse A list containing the field definitions maps. */ - public function listMetadataFields() + public function listMetadataFields(): ApiResponse { return $this->apiClient->get(ApiEndPoint::METADATA_FIELDS); } @@ -48,7 +48,7 @@ public function listMetadataFields() * * @return ApiResponse Field definitions. */ - public function metadataFieldByFieldId($fieldExternalId) + public function metadataFieldByFieldId(string $fieldExternalId): ApiResponse { $uri = [ApiEndPoint::METADATA_FIELDS, $fieldExternalId]; @@ -64,7 +64,7 @@ public function metadataFieldByFieldId($fieldExternalId) * * @return ApiResponse A map defining the new field. */ - public function addMetadataField(MetadataField $field) + public function addMetadataField(MetadataField $field): ApiResponse { return $this->apiClient->postJson([ApiEndPoint::METADATA_FIELDS], $field); } @@ -81,9 +81,8 @@ public function addMetadataField(MetadataField $field) * * @return ApiResponse The updated fields definition. * - * @throws ApiError */ - public function updateMetadataField($fieldExternalId, MetadataField $field) + public function updateMetadataField(string $fieldExternalId, MetadataField $field): ApiResponse { $uri = [ApiEndPoint::METADATA_FIELDS, $fieldExternalId]; @@ -102,9 +101,8 @@ public function updateMetadataField($fieldExternalId, MetadataField $field) * * @return ApiResponse An array with a "message" key. "ok" value indicates a successful deletion. * - * @throws ApiError */ - public function deleteMetadataField($fieldExternalId) + public function deleteMetadataField(string $fieldExternalId): ApiResponse { $uri = [ApiEndPoint::METADATA_FIELDS, $fieldExternalId]; @@ -125,9 +123,8 @@ public function deleteMetadataField($fieldExternalId) * * @return ApiResponse The remaining datasource entries. * - * @throws ApiError */ - public function deleteDatasourceEntries($fieldExternalId, array $entriesExternalId) + public function deleteDatasourceEntries(string $fieldExternalId, array $entriesExternalId): ApiResponse { $uri = [ApiEndPoint::METADATA_FIELDS, $fieldExternalId, 'datasource']; @@ -149,9 +146,8 @@ public function deleteDatasourceEntries($fieldExternalId, array $entriesExternal * * @return ApiResponse The updated field definition. * - * @throws ApiError */ - public function updateMetadataFieldDatasource($fieldExternalId, array $entries) + public function updateMetadataFieldDatasource(string $fieldExternalId, array $entries): ApiResponse { $uri = [ApiEndPoint::METADATA_FIELDS, $fieldExternalId, 'datasource']; @@ -171,12 +167,11 @@ public function updateMetadataFieldDatasource($fieldExternalId, array $entries) * @param string $fieldExternalId The ID of the metadata field. * @param array $entriesExternalIds An array of IDs of datasource entries to restore (unblock). * - * @return ApiResponse */ - public function restoreMetadataFieldDatasource($fieldExternalId, array $entriesExternalIds) + public function restoreMetadataFieldDatasource(string $fieldExternalId, array $entriesExternalIds): ApiResponse { - $uri = [ApiEndPoint::METADATA_FIELDS, $fieldExternalId, 'datasource_restore']; - $params['external_ids'] = $entriesExternalIds; + $uri = [ApiEndPoint::METADATA_FIELDS, $fieldExternalId, 'datasource_restore']; + $params = ['external_ids' => $entriesExternalIds]; return $this->apiClient->postJson($uri, $params); } @@ -184,14 +179,16 @@ public function restoreMetadataFieldDatasource($fieldExternalId, array $entriesE /** * Reorders metadata field datasource. Currently, supports only value. * - * @param string $fieldExternalId The ID of the metadata field. - * @param string $orderBy Criteria for the order. Currently, supports only value. - * @param string $direction Optional (gets either asc or desc). + * @param string $fieldExternalId The ID of the metadata field. + * @param string $orderBy Criteria for the order. Currently, supports only value. + * @param string|null $direction Optional (gets either asc or desc). * - * @return ApiResponse */ - public function reorderMetadataFieldDatasource($fieldExternalId, $orderBy, $direction = null) - { + public function reorderMetadataFieldDatasource( + string $fieldExternalId, + string $orderBy, + ?string $direction = null + ): ApiResponse { $uri = [ApiEndPoint::METADATA_FIELDS, $fieldExternalId, 'datasource', 'order']; $params = [ 'order_by' => $orderBy, @@ -204,12 +201,11 @@ public function reorderMetadataFieldDatasource($fieldExternalId, $orderBy, $dire /** * Reorders metadata fields. * - * @param string $orderBy Criteria for the order (one of the fields 'label', 'external_id', 'created_at'). - * @param string $direction Optional (gets either asc or desc). + * @param string $orderBy Criteria for the order (one of the fields 'label', 'external_id', 'created_at'). + * @param string|null $direction Optional (gets either asc or desc). * - * @return ApiResponse */ - public function reorderMetadataFields($orderBy, $direction = null) + public function reorderMetadataFields(string $orderBy, ?string $direction = null): ApiResponse { $uri = [ApiEndPoint::METADATA_FIELDS, 'order']; $params = [ diff --git a/src/Api/Admin/MiscTrait.php b/src/Api/Admin/MiscTrait.php index 9288fc4b..45103e43 100644 --- a/src/Api/Admin/MiscTrait.php +++ b/src/Api/Admin/MiscTrait.php @@ -30,13 +30,12 @@ trait MiscTrait /** * Tests the reachability of the Cloudinary API. * - * @return ApiResponse * * @see AdminApi::pingAsync() * * @see https://cloudinary.com/documentation/admin_api#ping */ - public function ping() + public function ping(): ApiResponse { return $this->pingAsync()->wait(); } @@ -44,11 +43,10 @@ public function ping() /** * Tests the reachability of the Cloudinary API asynchronously. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/admin_api#ping */ - public function pingAsync() + public function pingAsync(): PromiseInterface { return $this->apiClient->getAsync(ApiEndPoint::PING); } @@ -60,11 +58,10 @@ public function pingAsync() * * @param array $options The optional parameters for the API request. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#config */ - public function config($options = []) + public function config(array $options = []): ApiResponse { $params = ArrayUtils::whitelist($options, ['settings']); @@ -81,13 +78,11 @@ public function config($options = []) * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#usage */ - public function usage($options = []) + public function usage(array $options = []): ApiResponse { $uri = [ApiEndPoint::USAGE, Utils::formatDate(ArrayUtils::get($options, 'date'))]; @@ -101,13 +96,11 @@ public function usage($options = []) * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#get_tags */ - public function tags($options = []) + public function tags(array $options = []): ApiResponse { $assetType = ArrayUtils::get($options, AssetType::KEY, AssetType::IMAGE); $uri = [ApiEndPoint::TAGS, $assetType]; diff --git a/src/Api/Admin/StreamingProfilesTrait.php b/src/Api/Admin/StreamingProfilesTrait.php index 45067fb0..3e33a3d9 100644 --- a/src/Api/Admin/StreamingProfilesTrait.php +++ b/src/Api/Admin/StreamingProfilesTrait.php @@ -34,11 +34,10 @@ trait StreamingProfilesTrait * * @return ApiResponse An array with a "data" key for results. * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#get_adaptive_streaming_profiles */ - public function listStreamingProfiles() + public function listStreamingProfiles(): ApiResponse { return $this->apiClient->get(ApiEndPoint::STREAMING_PROFILES); } @@ -50,11 +49,10 @@ public function listStreamingProfiles() * * @return ApiResponse An array with a "data" key for results. * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#get_details_of_a_single_streaming_profile */ - public function getStreamingProfile($name) + public function getStreamingProfile(string $name): ApiResponse { $uri = [ApiEndPoint::STREAMING_PROFILES, $name]; @@ -71,13 +69,10 @@ public function getStreamingProfile($name) * * @param string $name The name of the streaming profile to delete or revert. * - * @return ApiResponse - * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#delete_or_revert_the_specified_streaming_profile */ - public function deleteStreamingProfile($name) + public function deleteStreamingProfile(string $name): ApiResponse { $uri = [ApiEndPoint::STREAMING_PROFILES, $name]; @@ -92,16 +87,14 @@ public function deleteStreamingProfile($name) * * @param string $name The name of the streaming profile to update. * @param array $options The optional parameters. See the - * Admin API - * documentation. + * Admin API documentation. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#create_a_streaming_profile */ - public function updateStreamingProfile($name, $options = []) + public function updateStreamingProfile(string $name, array $options = []): ApiResponse { $uri = [ApiEndPoint::STREAMING_PROFILES, $name]; $params = $this->prepareStreamingProfileParams($options); @@ -116,17 +109,14 @@ public function updateStreamingProfile($name, $options = []) * The name is case-insensitive and can contain alphanumeric characters, underscores (_) and * hyphens (-). If the name is of a predefined profile, the profile will be modified. * @param array $options The optional parameters. See the - * Admin API - * documentation. - * - * @return ApiResponse + * Admin API documentation. * - * @throws ApiError * * @see self::createStreamingProfile() * @see https://cloudinary.com/documentation/admin_api#create_a_streaming_profile */ - public function createStreamingProfile($name, $options = []) + public function createStreamingProfile(string $name, array $options = []): ApiResponse { $uri = [ApiEndPoint::STREAMING_PROFILES]; @@ -145,15 +135,14 @@ public function createStreamingProfile($name, $options = []) * * @internal */ - protected function prepareStreamingProfileParams($options) + protected function prepareStreamingProfileParams(array $options): array { $params = ArrayUtils::whitelist($options, ['display_name']); if (isset($options['representations'])) { $representations = array_map( - static function ($representation) { - return ['transformation' => ApiUtils::serializeAssetTransformations($representation)]; - }, + static fn($representation + ) => ['transformation' => ApiUtils::serializeAssetTransformations($representation)], $options['representations'] ); $params['representations'] = json_encode($representations); diff --git a/src/Api/Admin/TransformationsTrait.php b/src/Api/Admin/TransformationsTrait.php index b345b55c..f5700e6e 100644 --- a/src/Api/Admin/TransformationsTrait.php +++ b/src/Api/Admin/TransformationsTrait.php @@ -37,11 +37,10 @@ trait TransformationsTrait * Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_transformations */ - public function transformations($options = []) + public function transformations(array $options = []): ApiResponse { $params = ArrayUtils::whitelist($options, ['named', 'next_cursor', 'max_results']); @@ -51,16 +50,15 @@ public function transformations($options = []) /** * Returns the details of a single transformation. * - * @param string|array $transformation The transformation. Can be either a string or an array of parameters. + * @param array|string $transformation The transformation. Can be either a string or an array of parameters. * For example: "w_150,h_100,c_fill" or array("width" => 150, "height" => * 100,"crop" => "fill"). * @param array $options The optional parameters. See the admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_transformation_details */ - public function transformation($transformation, $options = []) + public function transformation(array|string $transformation, array $options = []): ApiResponse { $params = ArrayUtils::whitelist($options, ['next_cursor', 'max_results']); $params['transformation'] = ApiUtils::serializeAssetTransformations($transformation); @@ -74,20 +72,18 @@ public function transformation($transformation, $options = []) * Deleting a transformation also deletes all the stored derived assets based on this transformation (up to 1000). * The method returns an error if there are more than 1000 derived assets based on this transformation. * - * @param string|array $transformation The transformation to delete. Can be either a string or an array of + * @param array|string $transformation The transformation to delete. Can be either a string or an array of * parameters. For example: * "w_150,h_100,c_fill" or ["width" => 150, "height" => 100,"crop" => "fill"]. * @param array $options The optional parameters. See the * Admin API documentation. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#delete_transformation */ - public function deleteTransformation($transformation, $options = []) + public function deleteTransformation(array|string $transformation, array $options = []): ApiResponse { $params = ['transformation' => ApiUtils::serializeAssetTransformations($transformation)]; if (isset($options['invalidate'])) { @@ -100,20 +96,18 @@ public function deleteTransformation($transformation, $options = []) /** * Updates the specified transformation. * - * @param string|array $transformation The transformation. Can be either a string or an array of parameters. + * @param array|string $transformation The transformation. Can be either a string or an array of parameters. * For example: "w_150,h_100,c_fill" or array("width" => 150, "height" => * 100,"crop" => "fill"). * @param array $updates The update parameters. See the * Admin API documentation. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#update_transformation */ - public function updateTransformation($transformation, $updates = []) + public function updateTransformation(array|string $transformation, array $updates = []): ApiResponse { $params = ArrayUtils::whitelist($updates, ['allowed_for_strict']); if (isset($updates['unsafe_update'])) { @@ -130,14 +124,13 @@ public function updateTransformation($transformation, $updates = []) * @see https://cloudinary.com/documentation/admin_api#create_named_transformation * * @param string $name The name of the transformation. - * @param Transformation|string|array $definition The transformation. Can be either a defined Transformation, + * @param array|string|Transformation $definition The transformation. Can be either a defined Transformation, * a string or an array of parameters. For example: * "w_150,h_100,c_fill" or ["width" => 150, "height" => 100, * "crop" => "fill"]. * - * @return ApiResponse */ - public function createTransformation($name, $definition) + public function createTransformation(string $name, Transformation|array|string $definition): ApiResponse { $params = [ 'name' => $name, diff --git a/src/Api/Admin/UploadMappingsTrait.php b/src/Api/Admin/UploadMappingsTrait.php index 5ef153ca..ed5fc99b 100644 --- a/src/Api/Admin/UploadMappingsTrait.php +++ b/src/Api/Admin/UploadMappingsTrait.php @@ -35,11 +35,10 @@ trait UploadMappingsTrait * Admin API * documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_upload_mappings */ - public function uploadMappings($options = []) + public function uploadMappings(array $options = []): ApiResponse { $uri = ApiEndPoint::UPLOAD_MAPPINGS; $params = ArrayUtils::whitelist($options, ['next_cursor', 'max_results']); @@ -54,11 +53,10 @@ public function uploadMappings($options = []) * * @param string $name The name of the upload mapping folder. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_the_details_of_a_single_upload_mapping */ - public function uploadMapping($name) + public function uploadMapping(string $name): ApiResponse { $uri = ApiEndPoint::UPLOAD_MAPPINGS; $params = ['folder' => $name]; @@ -72,13 +70,11 @@ public function uploadMapping($name) * * @param string $name The name of the upload mapping folder to delete. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#delete_an_upload_mapping */ - public function deleteUploadMapping($name) + public function deleteUploadMapping(string $name): ApiResponse { $uri = ApiEndPoint::UPLOAD_MAPPINGS; $params = ['folder' => $name]; @@ -95,13 +91,11 @@ public function deleteUploadMapping($name) * Admin API * documentation. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#update_an_upload_mapping */ - public function updateUploadMapping($name, $options = []) + public function updateUploadMapping(string $name, array $options = []): ApiResponse { $uri = ApiEndPoint::UPLOAD_MAPPINGS; $params = array_merge(['folder' => $name], ArrayUtils::whitelist($options, ['template'])); @@ -118,11 +112,10 @@ public function updateUploadMapping($name, $options = []) * Admin API * documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#create_an_upload_mapping */ - public function createUploadMapping($name, $options = []) + public function createUploadMapping(string $name, array $options = []): ApiResponse { $uri = ApiEndPoint::UPLOAD_MAPPINGS; $params = array_merge(['folder' => $name], ArrayUtils::whitelist($options, ['template'])); diff --git a/src/Api/Admin/UploadPresetsTrait.php b/src/Api/Admin/UploadPresetsTrait.php index 14dca56b..0fd81523 100644 --- a/src/Api/Admin/UploadPresetsTrait.php +++ b/src/Api/Admin/UploadPresetsTrait.php @@ -36,11 +36,10 @@ trait UploadPresetsTrait * Admin API * documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_upload_presets */ - public function uploadPresets($options = []) + public function uploadPresets(array $options = []): ApiResponse { $uri = [ApiEndPoint::UPLOAD_PRESETS]; $params = ArrayUtils::whitelist($options, ['next_cursor', 'max_results']); @@ -56,11 +55,10 @@ public function uploadPresets($options = []) * Admin API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#get_the_details_of_a_single_upload_preset */ - public function uploadPreset($name, $options = []) + public function uploadPreset(string $name, array $options = []): ApiResponse { $uri = [ApiEndPoint::UPLOAD_PRESETS, $name]; @@ -72,17 +70,15 @@ public function uploadPreset($name, $options = []) * * @param string $name The name of the upload preset to delete. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#delete_an_upload_preset */ - public function deleteUploadPreset($name) + public function deleteUploadPreset(string $name): ApiResponse { $uri = [ApiEndPoint::UPLOAD_PRESETS, $name]; - return $this->apiClient->delete($uri, []); + return $this->apiClient->delete($uri); } /** @@ -94,13 +90,11 @@ public function deleteUploadPreset($name) * Admin API * documentation. * - * @return ApiResponse * - * @throws ApiError * * @see https://cloudinary.com/documentation/admin_api#update_an_upload_preset */ - public function updateUploadPreset($name, $options = []) + public function updateUploadPreset(string $name, array $options = []): ApiResponse { $uri = [ApiEndPoint::UPLOAD_PRESETS, $name]; $params = UploadApi::buildUploadParams($options); @@ -116,11 +110,10 @@ public function updateUploadPreset($name, $options = []) * Admin API * documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/admin_api#create_an_upload_preset */ - public function createUploadPreset($options = []) + public function createUploadPreset(array $options = []): ApiResponse { $params = UploadApi::buildUploadParams($options); $params = array_merge( diff --git a/src/Api/ApiClient.php b/src/Api/ApiClient.php index d7691326..096f816b 100644 --- a/src/Api/ApiClient.php +++ b/src/Api/ApiClient.php @@ -37,12 +37,11 @@ class ApiClient extends BaseApiClient /** * @var CloudConfig $cloud The cloud configuration. */ - protected $cloud; + protected CloudConfig $cloud; /** * ApiClient constructor. * - * @param $configuration */ public function __construct($configuration = null) { @@ -58,7 +57,7 @@ public function __construct($configuration = null) $this->createHttpClient(); } - protected function createHttpClient() + protected function createHttpClient(): void { $this->httpClient = new Client($this->buildHttpClientConfig()); } @@ -66,11 +65,10 @@ protected function createHttpClient() /** * Gets cloud configuration of the current client. * - * @return CloudConfig * * @internal */ - public function getCloud() + public function getCloud(): CloudConfig { return $this->cloud; } @@ -80,11 +78,10 @@ public function getCloud() * * @param mixed $configuration The configuration source. * - * @return static * * @internal */ - public function configuration($configuration) + public function configuration(mixed $configuration): static { $tempConfiguration = new Configuration($configuration); // TODO: improve performance here @@ -98,14 +95,13 @@ public function configuration($configuration) /** * Performs an HTTP POST request with the given form parameters. * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param array $formParams The form parameters * - * @return ApiResponse * * @internal */ - public function postForm($endPoint, $formParams) + public function postForm(array|string $endPoint, array $formParams): ApiResponse { return $this->postFormAsync($endPoint, $formParams)->wait(); } @@ -115,16 +111,15 @@ public function postForm($endPoint, $formParams) * * Please note that form parameters are encoded in a slightly different way, see Utils::buildHttpQuery for details. * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param array $formParams The form parameters * - * @return PromiseInterface * * @see Utils::buildHttpQuery * * @internal */ - public function postFormAsync($endPoint, $formParams) + public function postFormAsync(array|string $endPoint, array $formParams): PromiseInterface { return $this->callAsync(HttpMethod::POST, $endPoint, ['body' => Utils::buildHttpQuery($formParams)]); } @@ -132,14 +127,13 @@ public function postFormAsync($endPoint, $formParams) /** * Signs posted parameters using configured cloud credentials and posts to the endpoint. * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param array $formParams The form parameters * - * @return PromiseInterface * * @internal */ - public function postAndSignFormAsync($endPoint, $formParams) + public function postAndSignFormAsync(array|string $endPoint, array $formParams): PromiseInterface { if (! $this->cloud->oauthToken) { ApiUtils::signRequest($formParams, $this->cloud); @@ -151,14 +145,13 @@ public function postAndSignFormAsync($endPoint, $formParams) /** * Signs posted parameters using configured account credentials and posts as a JSON to the endpoint. * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param array $params The parameters * - * @return PromiseInterface * * @internal */ - public function postAndSignJsonAsync($endPoint, $params) + public function postAndSignJsonAsync(array|string $endPoint, array $params): PromiseInterface { ApiUtils::signRequest($params, $this->cloud); @@ -168,17 +161,18 @@ public function postAndSignJsonAsync($endPoint, $params) /** * Helper method for posting multipart data asynchronously. * - * @param string|array $endPoint The API endpoint path. - * @param $multiPart - * @param array $headers + * @param array|string $endPoint The API endpoint path. * @param array $options Additional options for Http client * - * @return PromiseInterface * * @internal */ - public function postMultiPartAsync($endPoint, $multiPart, $headers = null, $options = []) - { + public function postMultiPartAsync( + array|string $endPoint, + mixed $multiPart, + ?array $headers = null, + array $options = [] + ): PromiseInterface { ArrayUtils::addNonEmpty($options, 'multipart', $multiPart); ArrayUtils::addNonEmpty($options, 'headers', $headers); @@ -188,36 +182,36 @@ public function postMultiPartAsync($endPoint, $multiPart, $headers = null, $opti /** * Helper method for posting multipart data. * - * @param string|array $endPoint The API endpoint path. - * @param $multiPart - * @param array $headers + * @param array|string $endPoint The API endpoint path. * @param array $options Additional options for Http client * - * @return ApiResponse * * @internal * */ - public function postMultiPart($endPoint, $multiPart, $headers = null, $options = []) - { + public function postMultiPart( + array|string $endPoint, + mixed $multiPart, + ?array $headers = null, + array $options = [] + ): ApiResponse { return $this->postMultiPartAsync($endPoint, $multiPart, $headers, $options)->wait(); } /** * Uploads a file to the Cloudinary server. * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param mixed $file File to upload, can be a local path, URL, stream, etc. * @param array $parameters Additional parameters to be sent in the body * @param array $options Additional options, including options for the HTTP client * - * @return ApiResponse * * @throws ApiError * * @internal */ - public function postFile($endPoint, $file, $parameters, $options = []) + public function postFile(array|string $endPoint, mixed $file, array $parameters, array $options = []): ApiResponse { return $this->postFileAsync($endPoint, $file, $parameters, $options)->wait(); } @@ -225,23 +219,26 @@ public function postFile($endPoint, $file, $parameters, $options = []) /** * Uploads a file to the Cloudinary server asynchronously. * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param mixed $file File to upload, can be a local path, URL, stream, etc. * @param array $parameters Additional parameters to be sent in the body * @param array $options Additional options, including options for the HTTP client * - * @return PromiseInterface * * @throws ApiError * @throws Exception * * @internal */ - public function postFileAsync($endPoint, $file, $parameters, $options = []) - { + public function postFileAsync( + array|string $endPoint, + mixed $file, + array $parameters, + array $options = [] + ): PromiseInterface { $unsigned = ArrayUtils::get($options, 'unsigned'); - if (! $this->cloud->oauthToken && ! $unsigned) { + if (! isset($this->cloud->oauthToken) && ! $unsigned) { ApiUtils::signRequest($parameters, $this->cloud); } @@ -287,14 +284,13 @@ public function postFileAsync($endPoint, $file, $parameters, $options = []) * Performs an HTTP call asynchronously. * * @param string $method An HTTP method. - * @param string|array $endPoint An API endpoint path. + * @param array|string $endPoint An API endpoint path. * @param array $options An array containing request body and additional options passed to the HTTP Client. * - * @return PromiseInterface * * @internal */ - protected function callAsync($method, $endPoint, $options) + protected function callAsync(string $method, array|string $endPoint, array $options): PromiseInterface { static::validateAuthorization($this->cloud, $options); @@ -304,18 +300,21 @@ protected function callAsync($method, $endPoint, $options) /** * Posts a large file in chunks asynchronously * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param StreamInterface $fileHandle The file handle * @param array $parameters Additional form parameters * @param array $options Additional options * - * @return PromiseInterface * @throws Exception * * @internal */ - private function postLargeFileAsync($endPoint, $fileHandle, $parameters, $options = []) - { + private function postLargeFileAsync( + array|string $endPoint, + StreamInterface $fileHandle, + array $parameters, + array $options = [] + ): PromiseInterface { $this->getLogger()->debug('Making a Large File Async POST request'); $uploadResult = null; @@ -368,18 +367,21 @@ private function postLargeFileAsync($endPoint, $fileHandle, $parameters, $option /** * Posts a single chunk of the large file upload request asynchronously * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param mixed $singleChunk The data of a single chunk of the file * @param array $parameters Additional form parameters * @param array $options Additional options * - * @return PromiseInterface * * @internal * */ - protected function postSingleChunkAsync($endPoint, $singleChunk, $parameters, $options = []) - { + protected function postSingleChunkAsync( + array|string $endPoint, + mixed $singleChunk, + array $parameters, + array $options = [] + ): PromiseInterface { $filePart = [ 'name' => ArrayUtils::get($options, 'file_field', 'file'), 'contents' => $singleChunk, @@ -398,11 +400,10 @@ protected function postSingleChunkAsync($endPoint, $singleChunk, $parameters, $o /** * Build configuration used by HTTP client * - * @return array * * @internal */ - protected function buildHttpClientConfig() + protected function buildHttpClientConfig(): array { $clientConfig = [ 'base_uri' => $this->baseUri, @@ -431,17 +432,14 @@ protected function buildHttpClientConfig() * * @param array $parameters The input parameters * - * @return array * * @internal */ - private static function buildMultiPart($parameters) + private static function buildMultiPart(array $parameters): array { return array_values( ArrayUtils::mapAssoc( - static function ($key, $value) { - return ['name' => $key, 'contents' => $value]; - }, + static fn($key, $value) => ['name' => $key, 'contents' => $value], $parameters ) ); @@ -458,7 +456,7 @@ static function ($key, $value) { * * @internal */ - protected static function validateAuthorization($cloudConfig, $options) + protected static function validateAuthorization(CloudConfig $cloudConfig, array $options): void { $keysToValidate = ['cloudName']; diff --git a/src/Api/ApiResponse.php b/src/Api/ApiResponse.php index 430d33c4..d4bc90e3 100644 --- a/src/Api/ApiResponse.php +++ b/src/Api/ApiResponse.php @@ -25,40 +25,38 @@ class ApiResponse extends ArrayObject * * @var false|int */ - public $rateLimitResetAt; + public int|false $rateLimitResetAt; /** * Per-hour limit. * * @var int */ - public $rateLimitAllowed; + public int $rateLimitAllowed; /** * Remaining number of actions. * * @var int */ - public $rateLimitRemaining; + public int $rateLimitRemaining; /** * Response headers. * * @var array $headers */ - public $headers; + public array $headers; /** * ApiResponse constructor. * - * @param $responseJson - * @param $headers */ public function __construct($responseJson, $headers) { $this->headers = $headers; // According to RFC 2616, header names are case-insensitive. - $lcHeaders = array_change_key_case($headers, CASE_LOWER); + $lcHeaders = array_change_key_case($headers); $this->rateLimitResetAt = strtotime(ArrayUtils::get($lcHeaders, ['x-featureratelimit-reset', 0], 0)); $this->rateLimitAllowed = (int)ArrayUtils::get($lcHeaders, ['x-featureratelimit-limit', 0], 0); diff --git a/src/Api/BaseApiClient.php b/src/Api/BaseApiClient.php index ca18bf47..f6cc08ac 100644 --- a/src/Api/BaseApiClient.php +++ b/src/Api/BaseApiClient.php @@ -46,7 +46,7 @@ class BaseApiClient /** * @var array Cloudinary API Error Classes mapping between http error codes and Cloudinary exceptions */ - const CLOUDINARY_API_ERROR_CLASSES + protected const CLOUDINARY_API_ERROR_CLASSES = [ HttpStatusCode::BAD_REQUEST => BadRequest::class, HttpStatusCode::UNAUTHORIZED => AuthorizationRequired::class, @@ -60,17 +60,17 @@ class BaseApiClient /** * @var Client The Http client instance. Performs actual network calls. */ - public $httpClient; + public Client $httpClient; /** * @var ApiConfig $api The API configuration. */ - protected $api; + protected ApiConfig $api; /** * @var string Base API URI. Stored here to allow sharing it publicly (for example upload form tag) */ - protected $baseUri; + protected string $baseUri; /** * Contains information about SDK user agent. Passed to the Cloudinary servers. @@ -83,7 +83,7 @@ class BaseApiClient * * Do not change this value */ - private static $userAgent = 'CloudinaryPHP/' . Cloudinary::VERSION . ' (PHP ' . PHP_VERSION . ')'; + private static string $userAgent = 'CloudinaryPHP/' . Cloudinary::VERSION . ' (PHP ' . PHP_VERSION . ')'; /** * Additional information to be passed with the USER_AGENT, e.g. 'CloudinaryMagento/1.0.1'. @@ -100,16 +100,15 @@ class BaseApiClient * * @var string */ - public static $userPlatform = ''; + public static string $userPlatform = ''; /** * Gets base API url. * - * @return string * * @internal */ - public function getBaseUri() + public function getBaseUri(): string { return $this->baseUri; } @@ -117,14 +116,13 @@ public function getBaseUri() /** * Performs an HTTP GET request with the given query parameters asynchronously. * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param array $queryParams Query parameters * - * @return PromiseInterface * * @internal */ - public function getAsync($endPoint, $queryParams = []) + public function getAsync(array|string $endPoint, array $queryParams = []): PromiseInterface { return $this->callAsync(HttpMethod::GET, $endPoint, ['query' => Utils::buildHttpQuery($queryParams)]); } @@ -132,14 +130,13 @@ public function getAsync($endPoint, $queryParams = []) /** * Performs an HTTP GET request with the given query parameters. * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param array $queryParams Query parameters. * - * @return ApiResponse * * @internal */ - public function get($endPoint, $queryParams = []) + public function get(array|string $endPoint, array $queryParams = []): ApiResponse { return $this->getAsync($endPoint, $queryParams)->wait(); } @@ -147,14 +144,12 @@ public function get($endPoint, $queryParams = []) /** * Performs an HTTP POST request with the given JSON object. * - * @param string|array $endPoint The API endpoint path. - * @param $parameters + * @param array|string $endPoint The API endpoint path. * - * @return ApiResponse * * @internal */ - public function postJson($endPoint, $parameters = []) + public function postJson(array|string $endPoint, array|JsonSerializable $parameters = []): ApiResponse { return $this->postJsonAsync($endPoint, $parameters)->wait(); } @@ -162,15 +157,14 @@ public function postJson($endPoint, $parameters = []) /** * Performs an HTTP POST request with the given JSON object asynchronously. * - * @param string|array $endPoint The API endpoint path. - * @param JsonSerializable|array $json The json object + * @param array|string $endPoint The API endpoint path. + * @param array|JsonSerializable $json The json object * - * @return PromiseInterface * * @internal * */ - public function postJsonAsync($endPoint, $json) + public function postJsonAsync(array|string $endPoint, array|JsonSerializable $json): PromiseInterface { return $this->callAsync(HttpMethod::POST, $endPoint, ['json' => $json]); } @@ -178,16 +172,14 @@ public function postJsonAsync($endPoint, $json) /** * Performs an HTTP DELETE request with the given params * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param array $fields Fields to send * - * @return ApiResponse * - * @throws ApiError * * @internal */ - public function delete($endPoint, $fields = []) + public function delete(array|string $endPoint, array $fields = []): ApiResponse { return $this->callAsync(HttpMethod::DELETE, $endPoint, ['form_params' => $fields])->wait(); } @@ -195,14 +187,13 @@ public function delete($endPoint, $fields = []) /** * Performs an HTTP DELETE request with the given params. * - * @param string|array $endPoint The API endpoint path. - * @param JsonSerializable|array $json JSON data. + * @param array|string $endPoint The API endpoint path. + * @param array|JsonSerializable $json JSON data. * - * @return ApiResponse * * @internal */ - public function deleteJson($endPoint, $json = []) + public function deleteJson(array|string $endPoint, array|JsonSerializable $json = []): ApiResponse { return $this->callAsync(HttpMethod::DELETE, $endPoint, ['json' => $json])->wait(); } @@ -210,14 +201,12 @@ public function deleteJson($endPoint, $json = []) /** * Performs an HTTP POST request with the given parameters. * - * @param string|array $endPoint The API endpoint path. - * @param $parameters + * @param array|string $endPoint The API endpoint path. * - * @return ApiResponse * * @internal */ - public function post($endPoint, $parameters = []) + public function post(array|string $endPoint, array $parameters = []): ApiResponse { return $this->postAsync($endPoint, $parameters)->wait(); } @@ -225,14 +214,12 @@ public function post($endPoint, $parameters = []) /** * Performs an HTTP POST request with the given parameters asynchronously. * - * @param string|array $endPoint The API endpoint path. - * @param $options + * @param array|string $endPoint The API endpoint path. * - * @return PromiseInterface * * @internal */ - public function postAsync($endPoint, $options = []) + public function postAsync(array|string $endPoint, array $options = []): PromiseInterface { return $this->callAsync(HttpMethod::POST, $endPoint, $options); } @@ -240,16 +227,14 @@ public function postAsync($endPoint, $options = []) /** * Performs an HTTP PUT request with the given form params * - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param array $fields Fields to send. * - * @return ApiResponse * - * @throws ApiError * * @internal */ - public function put($endPoint, $fields) + public function put(array|string $endPoint, array $fields): ApiResponse { return $this->callAsync(HttpMethod::PUT, $endPoint, ['form_params' => $fields])->wait(); } @@ -257,12 +242,11 @@ public function put($endPoint, $fields) /** * Performs an HTTP PUT request with the given form params. * - * @param string|array $endPoint The API endpoint path. - * @param JsonSerializable|array $json JSON data. + * @param array|string $endPoint The API endpoint path. + * @param array|JsonSerializable $json JSON data. * - * @return ApiResponse */ - public function putJson($endPoint, $json) + public function putJson(array|string $endPoint, array|JsonSerializable $json): ApiResponse { return $this->callAsync(HttpMethod::PUT, $endPoint, ['json' => $json])->wait(); } @@ -276,7 +260,7 @@ public function putJson($endPoint, $json) * * @internal */ - public static function apiVersion($apiVersion = ApiConfig::DEFAULT_API_VERSION) + public static function apiVersion(string $apiVersion = ApiConfig::DEFAULT_API_VERSION): string { return 'v' . str_replace('.', '_', $apiVersion); } @@ -286,11 +270,11 @@ public static function apiVersion($apiVersion = ApiConfig::DEFAULT_API_VERSION) * * @param array|string $endPoint The API endpoint path. * - * @return string resulting URL path + * @return array|string resulting URL path * * @internal */ - protected static function finalizeEndPoint($endPoint) + protected static function finalizeEndPoint(array|string $endPoint): array|string { if (is_array($endPoint)) { $endPoint = ArrayUtils::implodeUrl($endPoint); @@ -303,14 +287,13 @@ protected static function finalizeEndPoint($endPoint) * Performs an HTTP call asynchronously * * @param string $method HTTP method - * @param string|array $endPoint The API endpoint path. + * @param array|string $endPoint The API endpoint path. * @param array $options Array containing request body and additional options passed to the HTTP Client * - * @return PromiseInterface * * @internal */ - protected function callAsync($method, $endPoint, $options) + protected function callAsync(string $method, array|string $endPoint, array $options): PromiseInterface { $endPoint = self::finalizeEndPoint($endPoint); $options['headers'] = ArrayUtils::mergeNonEmpty( @@ -364,11 +347,10 @@ function (Exception $error) { * * Prepends {@see ApiClient::$userPlatform} if it is defined. * - * @return string * * @internal */ - protected static function userAgent() + protected static function userAgent(): string { if (empty(self::$userPlatform)) { return self::$userAgent; @@ -382,13 +364,12 @@ protected static function userAgent() * * @param ResponseInterface $response Response from HTTP request to the Cloudinary server * - * @return ApiResponse * * @throws ApiError * * @internal */ - private function handleApiResponse($response) + private function handleApiResponse(ResponseInterface $response): ApiResponse { $statusCode = $response->getStatusCode(); @@ -428,16 +409,15 @@ private function handleApiResponse($response) * * @param ResponseInterface $response Response from HTTP request to Cloudinary server * - * @return mixed * * @throws GeneralError * * @internal */ - private function parseJsonResponse($response) + private function parseJsonResponse(ResponseInterface $response): mixed { try { - $responseJson = JsonUtils::decode($response->getBody(), true); + $responseJson = JsonUtils::decode($response->getBody()); } catch (InvalidArgumentException $iae) { $message = sprintf( 'Error parsing server response (%s) - %s. Got - %s', diff --git a/src/Api/Metadata/DateMetadataField.php b/src/Api/Metadata/DateMetadataField.php index 4e77c784..65b65c62 100644 --- a/src/Api/Metadata/DateMetadataField.php +++ b/src/Api/Metadata/DateMetadataField.php @@ -24,9 +24,8 @@ class DateMetadataField extends MetadataField /** * The DateMetadataField constructor. * - * @param string $label */ - public function __construct($label) + public function __construct(string $label) { parent::__construct($label); $this->type = MetadataFieldType::DATE; @@ -35,9 +34,9 @@ public function __construct($label) /** * Sets the default date for this field. * - * @param DateTime $defaultValue The date to set. + * @param mixed $defaultValue The date to set. */ - public function setDefaultValue($defaultValue) + public function setDefaultValue(mixed $defaultValue): void { $this->defaultValue = Utils::toISO8601DateOnly($defaultValue); } @@ -45,10 +44,9 @@ public function setDefaultValue($defaultValue) /** * Gets the default date of this field. * - * @return DateTime|null * @throws Exception When the underlying value is malformed. */ - public function getDefaultValue() + public function getDefaultValue(): ?DateTime { return $this->defaultValue ? new DateTime($this->defaultValue) : null; } diff --git a/src/Api/Metadata/EnumMetadataField.php b/src/Api/Metadata/EnumMetadataField.php index 5d862a5b..8c964435 100644 --- a/src/Api/Metadata/EnumMetadataField.php +++ b/src/Api/Metadata/EnumMetadataField.php @@ -19,11 +19,8 @@ class EnumMetadataField extends MetadataFieldList { /** * The EnumMetadataField constructor. - * - * @param string $label - * @param array|MetadataDataSource $dataSource */ - public function __construct($label, $dataSource = []) + public function __construct(string $label, array|MetadataDataSource $dataSource = []) { parent::__construct($label, $dataSource); $this->type = MetadataFieldType::ENUM; diff --git a/src/Api/Metadata/IntMetadataField.php b/src/Api/Metadata/IntMetadataField.php index 5ee5183e..6ae798e6 100644 --- a/src/Api/Metadata/IntMetadataField.php +++ b/src/Api/Metadata/IntMetadataField.php @@ -20,9 +20,8 @@ class IntMetadataField extends MetadataField /** * The IntMetadataField constructor. * - * @param string $label */ - public function __construct($label) + public function __construct(string $label) { parent::__construct($label); $this->type = MetadataFieldType::INTEGER; @@ -31,9 +30,8 @@ public function __construct($label) /** * Sets the default value for this field. * - * @param int $defaultValue */ - public function setDefaultValue($defaultValue) + public function setDefaultValue(mixed $defaultValue): void { $this->defaultValue = (int)$defaultValue; } diff --git a/src/Api/Metadata/Metadata.php b/src/Api/Metadata/Metadata.php index a2b233f6..53a902df 100644 --- a/src/Api/Metadata/Metadata.php +++ b/src/Api/Metadata/Metadata.php @@ -26,22 +26,20 @@ abstract class Metadata implements JsonSerializable * * @return string[] */ - abstract protected function getPropertyKeys(); + abstract protected function getPropertyKeys(): array; /** * Returns data that should be serialized to JSON. * Serializes the object to a value that can be serialized natively by json_encode(). * - * @return array */ - #[\ReturnTypeWillChange] - public function jsonSerialize() + public function jsonSerialize(): array { $propertyKeys = $this->getPropertyKeys(); $snakeCaseProperties = []; foreach ($propertyKeys as $key) { - $value = $this->{$key}; + $value = $this->{$key} ?? null; if ($value === null) { continue; } diff --git a/src/Api/Metadata/MetadataDataEntry.php b/src/Api/Metadata/MetadataDataEntry.php index 70db34eb..4f9cf45f 100644 --- a/src/Api/Metadata/MetadataDataEntry.php +++ b/src/Api/Metadata/MetadataDataEntry.php @@ -19,23 +19,15 @@ */ class MetadataDataEntry extends Metadata { - /** - * @var string - */ - protected $externalId; + protected ?string $externalId; - /** - * @var string - */ - protected $value; + protected string $value; /** * MetadataDataEntry constructor. * - * @param string $value - * @param string $externalId */ - public function __construct($value, $externalId = null) + public function __construct(string $value, ?string $externalId = null) { $this->setValue($value); $this->setExternalId($externalId); @@ -44,9 +36,8 @@ public function __construct($value, $externalId = null) /** * Gets the keys for all the properties of this object. * - * @return array */ - public function getPropertyKeys() + public function getPropertyKeys(): array { return ['externalId', 'value']; } @@ -54,9 +45,8 @@ public function getPropertyKeys() /** * Gets the value of the entry. * - * @return string */ - public function getValue() + public function getValue(): string { return $this->value; } @@ -64,9 +54,8 @@ public function getValue() /** * Sets the value of the entry. * - * @param string $value */ - public function setValue($value) + public function setValue(string $value): void { if (is_null($value)) { throw new InvalidArgumentException('Metadata data entry value is not valid'); @@ -77,9 +66,8 @@ public function setValue($value) /** * Gets the ID of the entry. * - * @return string */ - public function getExternalId() + public function getExternalId(): string { return $this->externalId; } @@ -87,9 +75,9 @@ public function getExternalId() /** * Sets the ID of the entry. Will be auto-generated if left blank. * - * @param string $externalId + * @param ?string $externalId The external ID. */ - public function setExternalId($externalId) + public function setExternalId(?string $externalId): void { $this->externalId = $externalId; } diff --git a/src/Api/Metadata/MetadataDataSource.php b/src/Api/Metadata/MetadataDataSource.php index b8cf7c7b..9db1a97b 100644 --- a/src/Api/Metadata/MetadataDataSource.php +++ b/src/Api/Metadata/MetadataDataSource.php @@ -23,12 +23,11 @@ class MetadataDataSource extends Metadata /** * @var MetadataDataEntry[] */ - protected $values; + protected array $values; /** * The MetadataDataSource constructor. * - * @param array $values * * @throws InvalidArgumentException */ @@ -40,9 +39,8 @@ public function __construct(array $values) /** * Gets the keys for all the properties of this object. * - * @return array */ - public function getPropertyKeys() + public function getPropertyKeys(): array { return ['values']; } @@ -54,7 +52,7 @@ public function getPropertyKeys() * * @throws InvalidArgumentException */ - public function setValues(array $values) + public function setValues(array $values): void { $this->values = []; foreach ($values as $value) { @@ -63,7 +61,7 @@ public function setValues(array $values) } elseif (is_array($value) && isset($value['value'])) { $this->values[] = new MetadataDataEntry( $value['value'], - isset($value['external_id']) ? $value['external_id'] : null + $value['external_id'] ?? null ); } else { throw new InvalidArgumentException('The specified metadata datasource values are not valid.'); @@ -76,7 +74,7 @@ public function setValues(array $values) * * @return MetadataDataEntry[] */ - public function getValues() + public function getValues(): array { return $this->values; } diff --git a/src/Api/Metadata/MetadataField.php b/src/Api/Metadata/MetadataField.php index a061e7df..2cb33e21 100644 --- a/src/Api/Metadata/MetadataField.php +++ b/src/Api/Metadata/MetadataField.php @@ -19,52 +19,27 @@ */ abstract class MetadataField extends Metadata { - /** - * @var string - */ - protected $externalId; + protected string $externalId; - /** - * @var string - */ - protected $label; + protected string $label; - /** - * @var bool - */ - protected $mandatory; + protected bool $mandatory; - /** - * @var mixed - */ - protected $defaultValue; + protected mixed $defaultValue; - /** - * @var string - */ - protected $type; + protected string $type; - /** - * @var MetadataValidation - */ - protected $validation; + protected MetadataValidation $validation; - /** - * @var array - */ - protected $restrictions; + protected array $restrictions; - /** - * @var bool - */ - protected $defaultDisabled; + protected bool $defaultDisabled; /** * The MetadataField constructor. * - * @param string $label */ - public function __construct($label) + public function __construct(string $label) { $this->label = $label; } @@ -74,7 +49,7 @@ public function __construct($label) * * @return string[] */ - public function getPropertyKeys() + public function getPropertyKeys(): array { return [ 'externalId', @@ -93,7 +68,7 @@ public function getPropertyKeys() * * @return string The type name. */ - public function getType() + public function getType(): string { return $this->type; } @@ -101,9 +76,8 @@ public function getType() /** * Gets the default value of this field. * - * @return mixed */ - public function getDefaultValue() + public function getDefaultValue(): mixed { return $this->defaultValue; } @@ -111,9 +85,8 @@ public function getDefaultValue() /** * Sets the default value of this field. * - * @param mixed $defaultValue */ - public function setDefaultValue($defaultValue) + public function setDefaultValue(mixed $defaultValue): void { $this->defaultValue = $defaultValue; } @@ -123,7 +96,7 @@ public function setDefaultValue($defaultValue) * * @return string The field ID. */ - public function getExternalId() + public function getExternalId(): string { return $this->externalId; } @@ -133,7 +106,7 @@ public function getExternalId() * * @param string $externalId The ID to set. */ - public function setExternalId($externalId) + public function setExternalId(string $externalId): void { $this->externalId = $externalId; } @@ -143,7 +116,7 @@ public function setExternalId($externalId) * * @return string The label of the field. */ - public function getLabel() + public function getLabel(): string { return $this->label; } @@ -153,7 +126,7 @@ public function getLabel() * * @param string $label The label to set. */ - public function setLabel($label) + public function setLabel(string $label): void { $this->label = $label; } @@ -163,7 +136,7 @@ public function setLabel($label) * * @return bool A boolean indicating whether the field is mandatory. */ - public function getMandatory() + public function getMandatory(): bool { return $this->mandatory; } @@ -173,7 +146,7 @@ public function getMandatory() * * @param bool $mandatory A boolean indicating whether the field should be mandatory. */ - public function setMandatory($mandatory = true) + public function setMandatory(bool $mandatory = true): void { $this->mandatory = $mandatory; } @@ -183,7 +156,7 @@ public function setMandatory($mandatory = true) * * @return MetadataValidation The validation rules. */ - public function getValidation() + public function getValidation(): MetadataValidation { return $this->validation; } @@ -193,7 +166,7 @@ public function getValidation() * * @param MetadataValidation $validation The rules to set. */ - public function setValidation(MetadataValidation $validation) + public function setValidation(MetadataValidation $validation): void { $this->validation = $validation; } @@ -201,9 +174,8 @@ public function setValidation(MetadataValidation $validation) /** * Gets the restrictions of this field. * - * @return array */ - public function getRestrictions() + public function getRestrictions(): array { return $this->restrictions; } @@ -211,9 +183,8 @@ public function getRestrictions() /** * Sets the restrictions of this field. * - * @param array $restrictions */ - public function setRestrictions($restrictions) + public function setRestrictions(array $restrictions): void { $this->restrictions = $restrictions; } @@ -221,9 +192,8 @@ public function setRestrictions($restrictions) /** * Gets the value indicating whether the field should be disabled by default. * - * @return bool */ - public function isDefaultDisabled() + public function isDefaultDisabled(): bool { return $this->defaultDisabled; } @@ -233,7 +203,7 @@ public function isDefaultDisabled() * * @param bool $defaultDisabled The value to set. */ - public function setDefaultDisabled($defaultDisabled = true) + public function setDefaultDisabled(bool $defaultDisabled = true): void { $this->defaultDisabled = $defaultDisabled; } diff --git a/src/Api/Metadata/MetadataFieldList.php b/src/Api/Metadata/MetadataFieldList.php index 80a48f39..c98e5b64 100644 --- a/src/Api/Metadata/MetadataFieldList.php +++ b/src/Api/Metadata/MetadataFieldList.php @@ -19,18 +19,15 @@ */ abstract class MetadataFieldList extends MetadataField { - /** - * @var MetadataDataSource $datasource - */ - protected $datasource; + protected MetadataDataSource $datasource; /** * The MetadataFieldList constructor. * - * @param string $label - * @param array|MetadataDataSource $dataSource + * @param string $label The label to assign. + * @param array|MetadataDataSource $dataSource The data source. */ - public function __construct($label, $dataSource = []) + public function __construct(string $label, array|MetadataDataSource $dataSource = []) { parent::__construct($label); $this->type = MetadataFieldType::STRING; @@ -42,7 +39,7 @@ public function __construct($label, $dataSource = []) * * @return string[] */ - public function getPropertyKeys() + public function getPropertyKeys(): array { return array_merge(parent::getPropertyKeys(), ['datasource']); } @@ -52,7 +49,7 @@ public function getPropertyKeys() * * @return MetadataDataSource The data source. */ - public function getDataSource() + public function getDataSource(): MetadataDataSource { return $this->datasource; } @@ -64,7 +61,7 @@ public function getDataSource() * * @throws InvalidArgumentException */ - public function setDataSource($metadataDataSource) + public function setDataSource(array|MetadataDataSource $metadataDataSource): void { if ($metadataDataSource instanceof MetadataDataSource) { $this->datasource = $metadataDataSource; diff --git a/src/Api/Metadata/MetadataFieldType.php b/src/Api/Metadata/MetadataFieldType.php index 84bec6a4..2578c162 100644 --- a/src/Api/Metadata/MetadataFieldType.php +++ b/src/Api/Metadata/MetadataFieldType.php @@ -17,9 +17,9 @@ */ class MetadataFieldType { - const STRING = 'string'; - const INTEGER = 'integer'; - const DATE = 'date'; - const ENUM = 'enum'; - const SET = 'set'; + public const STRING = 'string'; + public const INTEGER = 'integer'; + public const DATE = 'date'; + public const ENUM = 'enum'; + public const SET = 'set'; } diff --git a/src/Api/Metadata/SetMetadataField.php b/src/Api/Metadata/SetMetadataField.php index 4d80efb2..63f3c297 100644 --- a/src/Api/Metadata/SetMetadataField.php +++ b/src/Api/Metadata/SetMetadataField.php @@ -19,11 +19,8 @@ class SetMetadataField extends MetadataFieldList { /** * The SetMetadataField constructor. - * - * @param string $label - * @param array|MetadataDataSource $dataSource */ - public function __construct($label, $dataSource = []) + public function __construct(string $label, array|MetadataDataSource $dataSource = []) { parent::__construct($label, $dataSource); $this->type = MetadataFieldType::SET; diff --git a/src/Api/Metadata/StringMetadataField.php b/src/Api/Metadata/StringMetadataField.php index f066d491..072a1086 100644 --- a/src/Api/Metadata/StringMetadataField.php +++ b/src/Api/Metadata/StringMetadataField.php @@ -19,10 +19,8 @@ class StringMetadataField extends MetadataField { /** * The StringMetadataField constructor. - * - * @param string $label */ - public function __construct($label) + public function __construct(string $label) { parent::__construct($label); $this->type = MetadataFieldType::STRING; @@ -31,9 +29,8 @@ public function __construct($label) /** * Sets the default value. * - * @param string $defaultValue */ - public function setDefaultValue($defaultValue) + public function setDefaultValue(mixed $defaultValue): void { $this->defaultValue = (string)$defaultValue; } diff --git a/src/Api/Metadata/Validators/AndValidator.php b/src/Api/Metadata/Validators/AndValidator.php index 476299c0..8d7396fd 100644 --- a/src/Api/Metadata/Validators/AndValidator.php +++ b/src/Api/Metadata/Validators/AndValidator.php @@ -17,12 +17,12 @@ */ class AndValidator extends MetadataValidation { - const RULE_AND = 'and'; + protected const RULE_AND = 'and'; /** * @var MetadataValidation[] */ - protected $rules; + protected array $rules; /** * Create a new instance of the validator with the given rules. @@ -40,7 +40,7 @@ public function __construct(array $rules) * * @return string[] */ - public function getPropertyKeys() + public function getPropertyKeys(): array { return array_merge(parent::getPropertyKeys(), ['rules']); } diff --git a/src/Api/Metadata/Validators/ComparisonRule.php b/src/Api/Metadata/Validators/ComparisonRule.php index d8888511..09bed495 100644 --- a/src/Api/Metadata/Validators/ComparisonRule.php +++ b/src/Api/Metadata/Validators/ComparisonRule.php @@ -17,27 +17,21 @@ */ abstract class ComparisonRule extends MetadataValidation { - const GREATER_THAN = 'greater_than'; - const LESS_THAN = 'less_than'; + public const GREATER_THAN = 'greater_than'; + public const LESS_THAN = 'less_than'; /** * ComparisonRule constructor. * - * @param string $type - * @param mixed $value - * @param bool $equals */ - public function __construct($type, $value, $equals = false) + public function __construct(string $type, mixed $value, bool $equals = false) { $this->type = $type; $this->setValue($value); $this->equals = $equals; } - /** - * @param mixed $value - */ - protected function setValue($value) + protected function setValue(mixed $value): void { $this->value = $value; } diff --git a/src/Api/Metadata/Validators/DateGreaterThan.php b/src/Api/Metadata/Validators/DateGreaterThan.php index 038ace26..d8b77de0 100644 --- a/src/Api/Metadata/Validators/DateGreaterThan.php +++ b/src/Api/Metadata/Validators/DateGreaterThan.php @@ -31,10 +31,7 @@ public function __construct($value, $equals = false) parent::__construct(self::GREATER_THAN, $value, $equals); } - /** - * @param DateTime $value - */ - protected function setValue($value) + protected function setValue(mixed $value): void { $this->value = Utils::toISO8601DateOnly($value); } diff --git a/src/Api/Metadata/Validators/DateLessThan.php b/src/Api/Metadata/Validators/DateLessThan.php index 9bca75b9..45f2783f 100644 --- a/src/Api/Metadata/Validators/DateLessThan.php +++ b/src/Api/Metadata/Validators/DateLessThan.php @@ -31,10 +31,7 @@ public function __construct($value, $equals = false) parent::__construct(self::LESS_THAN, $value, $equals); } - /** - * @param DateTime $value - */ - protected function setValue($value) + protected function setValue(mixed $value): void { $this->value = Utils::toISO8601DateOnly($value); } diff --git a/src/Api/Metadata/Validators/MetadataValidation.php b/src/Api/Metadata/Validators/MetadataValidation.php index d07a0fa2..63bc2b36 100644 --- a/src/Api/Metadata/Validators/MetadataValidation.php +++ b/src/Api/Metadata/Validators/MetadataValidation.php @@ -19,37 +19,22 @@ */ abstract class MetadataValidation extends Metadata { - /** - * @var string $type - */ - protected $type; + protected string $type; - /** - * @var int $min - */ - protected $min; + protected int $min; - /** - * @var int $max - */ - protected $max; + protected int $max; - /** - * @var bool $equals - */ - protected $equals; + protected bool $equals; - /** - * @var mixed $value - */ - protected $value; + protected mixed $value; /** * Gets the keys for all the properties of this object. * * @return string[] */ - public function getPropertyKeys() + public function getPropertyKeys(): array { return ['type', 'min', 'max', 'equals', 'value']; } diff --git a/src/Api/Metadata/Validators/StringLength.php b/src/Api/Metadata/Validators/StringLength.php index b28cc9c4..9c7298e6 100644 --- a/src/Api/Metadata/Validators/StringLength.php +++ b/src/Api/Metadata/Validators/StringLength.php @@ -17,7 +17,7 @@ */ class StringLength extends MetadataValidation { - const STRLEN = 'strlen'; + public const STRLEN = 'strlen'; /** * Create a new instance with the given min and max. @@ -25,7 +25,7 @@ class StringLength extends MetadataValidation * @param int $min Minimum valid string length. * @param int $max Maximum valid string length. */ - public function __construct($min, $max) + public function __construct(int $min, int $max) { $this->type = self::STRLEN; $this->min = $min; diff --git a/src/Api/Provisioning/AccountApi.php b/src/Api/Provisioning/AccountApi.php index ec6ad518..fdc93edc 100644 --- a/src/Api/Provisioning/AccountApi.php +++ b/src/Api/Provisioning/AccountApi.php @@ -25,15 +25,11 @@ */ class AccountApi { - /** - * @var AccountApiClient $accountApiClient - */ - protected $accountApiClient; + protected AccountApiClient $accountApiClient; /** * AccountApi constructor. * - * @param ProvisioningConfiguration $configuration */ public function __construct(?ProvisioningConfiguration $configuration = null) { @@ -49,7 +45,7 @@ public function __construct(?ProvisioningConfiguration $configuration = null) * * @api */ - public function user($userId) + public function user(string $userId): ApiResponse { $uri = [AccountEndPoint::USERS, $userId]; @@ -59,17 +55,21 @@ public function user($userId) /** * Gets a list of the users according to filters. * - * @param bool $pending Whether to fetch pending users. Default all. - * @param array $userIds List of user IDs. Up to 100. - * @param string $prefix Search by prefix of the user's name or email. Case-insensitive. - * @param string $subAccountId Return only users who have access to the given sub-account. + * @param bool|null $pending Whether to fetch pending users. Default all. + * @param array $userIds List of user IDs. Up to 100. + * @param string|null $prefix Search by prefix of the user's name or email. Case-insensitive. + * @param string|null $subAccountId Return only users who have access to the given sub-account. * * @return ApiResponse List of users associated with the account. * * @api */ - public function users($pending = null, array $userIds = [], $prefix = null, $subAccountId = null) - { + public function users( + ?bool $pending = null, + array $userIds = [], + ?string $prefix = null, + ?string $subAccountId = null + ): ApiResponse { $uri = [AccountEndPoint::USERS]; $params = [ @@ -93,7 +93,7 @@ public function users($pending = null, array $userIds = [], $prefix = null, $sub * * @return ApiResponse Details of created user. */ - public function createUser($name, $email, $role, array $subAccountIds = []) + public function createUser(string $name, string $email, string $role, array $subAccountIds = []): ApiResponse { $uri = [AccountEndPoint::USERS]; @@ -118,12 +118,16 @@ public function createUser($name, $email, $role, array $subAccountIds = []) * If not provided or empty, user should have access to all accounts. * * @return ApiResponse The updated user details. - * @throws ApiError * * @api */ - public function updateUser($userId, $name, $email, $role, array $subAccountIds = []) - { + public function updateUser( + string $userId, + string $name, + string $email, + string $role, + array $subAccountIds = [] + ): ApiResponse { $uri = [AccountEndPoint::USERS, $userId]; $params = [ @@ -142,11 +146,10 @@ public function updateUser($userId, $name, $email, $role, array $subAccountIds = * @param string $userId Id of the user to delete. * * @return ApiResponse Result message. - * @throws ApiError * * @api */ - public function deleteUser($userId) + public function deleteUser(string $userId): ApiResponse { $uri = [AccountEndPoint::USERS, $userId]; @@ -154,18 +157,18 @@ public function deleteUser($userId) } /** - * Lists all sub accounts. + * Lists all sub-accounts. * - * @param bool $enabled Whether to only return enabled sub-accounts (true) or disabled accounts (false). - * Default: all accounts are returned (both enabled and disabled). - * @param array $ids List of sub-account IDs. Up to 100. When provided, other filters are ignored. - * @param string $prefix Search by prefix of the sub-account name. Case-insensitive. + * @param bool|null $enabled Whether to only return enabled sub-accounts (true) or disabled accounts (false). + * Default: all accounts are returned (both enabled and disabled). + * @param array|null $ids List of sub-account IDs. Up to 100. When provided, other filters are ignored. + * @param string|null $prefix Search by prefix of the sub-account name. Case-insensitive. * * @return ApiResponse A list of sub accounts * * @api */ - public function subAccounts($enabled = null, $ids = [], $prefix = null) + public function subAccounts(?bool $enabled = null, ?array $ids = [], ?string $prefix = null): ApiResponse { $uri = [AccountEndPoint::SUB_ACCOUNTS]; @@ -181,25 +184,25 @@ public function subAccounts($enabled = null, $ids = [], $prefix = null) /** * Creates a new sub account. * - * @param string $name Name of the new sub account. - * @param string $cloudName A case-insensitive cloud name comprised of alphanumeric and underscore. - * characters. Generates an error if the cloud name is not unique across all - * Cloudinary accounts. - * @param array $customAttributes Any custom attributes you want to associate with the sub-account. - * @param bool $enabled Whether to create the account as enabled (default is enabled). - * @param string $baseAccount ID of sub-account from which to copy settings. + * @param string $name Name of the new sub account. + * @param string|null $cloudName A case-insensitive cloud name comprised of alphanumeric and underscore. + * characters. Generates an error if the cloud name is not unique across all + * Cloudinary accounts. + * @param array|null $customAttributes Any custom attributes you want to associate with the sub-account. + * @param bool|null $enabled Whether to create the account as enabled (default is enabled). + * @param string|null $baseAccount ID of sub-account from which to copy settings. * * @return ApiResponse The created sub account. * * @api */ public function createSubAccount( - $name, - $cloudName = null, - $customAttributes = null, - $enabled = null, - $baseAccount = null - ) { + string $name, + ?string $cloudName = null, + ?array $customAttributes = null, + ?bool $enabled = null, + ?string $baseAccount = null + ): ApiResponse { $uri = [AccountEndPoint::SUB_ACCOUNTS]; $params = [ @@ -219,11 +222,10 @@ public function createSubAccount( * @param string $subAccountId The id of the sub account. * * @return ApiResponse The message. - * @throws ApiError * * @api */ - public function deleteSubAccount($subAccountId) + public function deleteSubAccount(string $subAccountId): ApiResponse { $uri = [AccountEndPoint::SUB_ACCOUNTS, $subAccountId]; @@ -239,7 +241,7 @@ public function deleteSubAccount($subAccountId) * * @api */ - public function subAccount($subAccountId) + public function subAccount(string $subAccountId): ApiResponse { $uri = [AccountEndPoint::SUB_ACCOUNTS, $subAccountId]; @@ -249,24 +251,23 @@ public function subAccount($subAccountId) /** * Updates a sub account. * - * @param string $subAccountId The id of the sub account. - * @param string $name The name displayed in the management console. - * @param string $cloudName The cloud name to set. - * @param array $customAttributes Custom attributes associated with the sub-account, as a map of key/value pairs. - * @param bool $enabled Set the sub-account as enabled or not. + * @param string $subAccountId The id of the sub account. + * @param string|null $name The name displayed in the management console. + * @param string|null $cloudName The cloud name to set. + * @param array|null $customAttributes Custom attributes associated with the sub-account, as a map of key/value + * pairs. + * @param bool|null $enabled Set the sub-account as enabled or not. * - * @return ApiResponse - * @throws ApiError * * @api */ public function updateSubAccount( - $subAccountId, - $name = null, - $cloudName = null, - $customAttributes = null, - $enabled = null - ) { + string $subAccountId, + ?string $name = null, + ?string $cloudName = null, + ?array $customAttributes = null, + ?bool $enabled = null + ): ApiResponse { $uri = [AccountEndPoint::SUB_ACCOUNTS, $subAccountId]; $params = [ @@ -288,7 +289,7 @@ public function updateSubAccount( * * @api */ - public function createUserGroup($name) + public function createUserGroup(string $name): ApiResponse { $uri = [AccountEndPoint::USER_GROUPS]; @@ -302,11 +303,10 @@ public function createUserGroup($name) * @param string $name The name of the group. * * @return ApiResponse The updated group. - * @throws ApiError * * @api */ - public function updateUserGroup($groupId, $name) + public function updateUserGroup(string $groupId, string $name): ApiResponse { $uri = [AccountEndPoint::USER_GROUPS, $groupId]; @@ -319,11 +319,10 @@ public function updateUserGroup($groupId, $name) * @param string $groupId The group id to delete. * * @return ApiResponse A result message. - * @throws ApiError * * @api */ - public function deleteUserGroup($groupId) + public function deleteUserGroup(string $groupId): ApiResponse { $uri = [AccountEndPoint::USER_GROUPS, $groupId]; @@ -339,7 +338,7 @@ public function deleteUserGroup($groupId) * * @api */ - public function userGroup($groupId) + public function userGroup(string $groupId): ApiResponse { $uri = [AccountEndPoint::USER_GROUPS, $groupId]; @@ -354,7 +353,7 @@ public function userGroup($groupId) * * @api */ - public function userGroups() + public function userGroups(): ApiResponse { $uri = [AccountEndPoint::USER_GROUPS]; @@ -371,7 +370,7 @@ public function userGroups() * * @api */ - public function addUserToGroup($groupId, $userId) + public function addUserToGroup(string $groupId, string $userId): ApiResponse { $uri = [AccountEndPoint::USER_GROUPS, $groupId, AccountEndPoint::USERS, $userId]; @@ -385,11 +384,10 @@ public function addUserToGroup($groupId, $userId) * @param string $userId The id of the user to remove. * * @return ApiResponse A list of users in the group. - * @throws ApiError * * @api */ - public function removeUserFromGroup($groupId, $userId) + public function removeUserFromGroup(string $groupId, string $userId): ApiResponse { $uri = [AccountEndPoint::USER_GROUPS, $groupId, AccountEndPoint::USERS, $userId]; @@ -405,7 +403,7 @@ public function removeUserFromGroup($groupId, $userId) * * @api */ - public function userGroupUsers($groupId) + public function userGroupUsers(string $groupId): ApiResponse { $uri = [AccountEndPoint::USER_GROUPS, $groupId, AccountEndPoint::USERS]; @@ -422,7 +420,7 @@ public function userGroupUsers($groupId) * * @api */ - public function accessKeys($subAccountId, $options = []) + public function accessKeys(string $subAccountId, array $options = []): ApiResponse { $uri = [AccountEndPoint::SUB_ACCOUNTS, $subAccountId, AccountEndPoint::ACCESS_KEYS]; @@ -441,7 +439,7 @@ public function accessKeys($subAccountId, $options = []) * * @api */ - public function generateAccessKey($subAccountId, $options = []) + public function generateAccessKey(string $subAccountId, array $options = []): ApiResponse { $uri = [AccountEndPoint::SUB_ACCOUNTS, $subAccountId, AccountEndPoint::ACCESS_KEYS]; @@ -461,7 +459,7 @@ public function generateAccessKey($subAccountId, $options = []) * * @api */ - public function updateAccessKey($subAccountId, $apiKey, $options = []) + public function updateAccessKey(string $subAccountId, string $apiKey, array $options = []): ApiResponse { $uri = [AccountEndPoint::SUB_ACCOUNTS, $subAccountId, AccountEndPoint::ACCESS_KEYS, $apiKey]; diff --git a/src/Api/Provisioning/AccountApiClient.php b/src/Api/Provisioning/AccountApiClient.php index c0e35e36..79181c1f 100644 --- a/src/Api/Provisioning/AccountApiClient.php +++ b/src/Api/Provisioning/AccountApiClient.php @@ -11,7 +11,6 @@ namespace Cloudinary\Api\Provisioning; use Cloudinary\Api\BaseApiClient; -use Cloudinary\Configuration\ApiConfig; use Cloudinary\Configuration\Provisioning\ProvisioningAccountConfig; use Cloudinary\Configuration\Provisioning\ProvisioningConfiguration; use Cloudinary\Exception\ConfigurationException; @@ -26,28 +25,24 @@ */ class AccountApiClient extends BaseApiClient { - const PROVISIONING = 'provisioning'; - const ACCOUNTS = 'accounts'; + public const PROVISIONING = 'provisioning'; + public const ACCOUNTS = 'accounts'; /** * @var ProvisioningAccountConfig $provisioningAccount The Account API configuration. */ - protected $provisioningAccount; + protected ProvisioningAccountConfig $provisioningAccount; /** * AccountApiClient constructor * - * @param ProvisioningConfiguration $configuration */ public function __construct(?ProvisioningConfiguration $configuration = null) { $this->init($configuration); } - /** - * @param ProvisioningConfiguration $configuration - */ - public function init(?ProvisioningConfiguration $configuration = null) + public function init(?ProvisioningConfiguration $configuration = null): void { if ($configuration === null) { $configuration = ProvisioningConfiguration::instance(); @@ -78,15 +73,12 @@ public function init(?ProvisioningConfiguration $configuration = null) $this->createHttpClient(); } - protected function createHttpClient() + protected function createHttpClient(): void { $this->httpClient = new Client($this->buildHttpClientConfig()); } - /** - * @return array - */ - protected function buildHttpClientConfig() + protected function buildHttpClientConfig(): array { return [ 'auth' => [ diff --git a/src/Api/Provisioning/AccountEndPoint.php b/src/Api/Provisioning/AccountEndPoint.php index 93014683..68db0c60 100644 --- a/src/Api/Provisioning/AccountEndPoint.php +++ b/src/Api/Provisioning/AccountEndPoint.php @@ -17,8 +17,8 @@ */ class AccountEndPoint { - const USERS = 'users'; - const USER_GROUPS = 'user_groups'; - const SUB_ACCOUNTS = 'sub_accounts'; - const ACCESS_KEYS = 'access_keys'; + public const USERS = 'users'; + public const USER_GROUPS = 'user_groups'; + public const SUB_ACCOUNTS = 'sub_accounts'; + public const ACCESS_KEYS = 'access_keys'; } diff --git a/src/Api/Provisioning/UserRole.php b/src/Api/Provisioning/UserRole.php index 93e0d7f4..703b882b 100644 --- a/src/Api/Provisioning/UserRole.php +++ b/src/Api/Provisioning/UserRole.php @@ -17,11 +17,11 @@ */ class UserRole { - const MASTER_ADMIN = 'master_admin'; - const ADMIN = 'admin'; - const TECHNICAL_ADMIN = 'technical_admin'; - const BILLING = 'billing'; - const REPORTS = 'reports'; - const MEDIA_LIBRARY_ADMIN = 'media_library_admin'; - const MEDIA_LIBRARY_USER = 'media_library_user'; + public const MASTER_ADMIN = 'master_admin'; + public const ADMIN = 'admin'; + public const TECHNICAL_ADMIN = 'technical_admin'; + public const BILLING = 'billing'; + public const REPORTS = 'reports'; + public const MEDIA_LIBRARY_ADMIN = 'media_library_admin'; + public const MEDIA_LIBRARY_USER = 'media_library_user'; } diff --git a/src/Api/Search/SearchApi.php b/src/Api/Search/SearchApi.php index 8f81c16d..b1e00b18 100644 --- a/src/Api/Search/SearchApi.php +++ b/src/Api/Search/SearchApi.php @@ -42,29 +42,29 @@ class SearchApi implements JsonSerializable, SearchQueryInterface /** * @internal */ - const ASSETS = 'resources'; + protected const ASSETS = 'resources'; /** * @var string The Search API endpoint. */ - private $endpoint = self::ASSETS; + private string $endpoint = self::ASSETS; /** * @var ApiClient $apiClient The HTTP API client instance. */ - protected $apiClient; + protected ApiClient $apiClient; /** * @var SearchAsset $searchAsset The Search Asset for building Search URL. */ - protected $searchAsset; + protected SearchAsset $searchAsset; /** * SearchApi constructor. * - * @param mixed $configuration + * @param mixed|null $configuration */ - public function __construct($configuration = null) + public function __construct(mixed $configuration = null) { $this->apiClient = new ApiClient($configuration); $this->searchAsset = new SearchAsset($configuration); @@ -77,7 +77,7 @@ public function __construct($configuration = null) * * @return $this */ - public function endpoint($endpoint) + public function endpoint(string $endpoint): static { $this->endpoint = $endpoint; @@ -87,11 +87,10 @@ public function endpoint($endpoint) /** * Executes the search API request asynchronously. * - * @return PromiseInterface * * @api */ - public function executeAsync() + public function executeAsync(): PromiseInterface { return $this->apiClient->postJsonAsync($this->getSearchEndpoint(), $this); } @@ -99,13 +98,11 @@ public function executeAsync() /** * Executes the search API request. * - * @return ApiResponse * - * @throws GeneralError * * @api */ - public function execute() + public function execute(): ApiResponse { return $this->executeAsync()->wait(); } @@ -113,12 +110,12 @@ public function execute() /** * Creates a signed Search URL that can be used on the client side. * - * @param int $ttl The time to live in seconds. - * @param string $nextCursor Starting position. + * @param int|null $ttl The time to live in seconds. + * @param string|null $nextCursor Starting position. * * @return string The resulting search URL. */ - public function toUrl($ttl = null, $nextCursor = null) + public function toUrl(?int $ttl = null, ?string $nextCursor = null): string { $this->searchAsset->query($this->asArray()); @@ -134,18 +131,15 @@ public function toUrl($ttl = null, $nextCursor = null) * * @return array data which can be serialized by json_encode */ - #[\ReturnTypeWillChange] - public function jsonSerialize() + public function jsonSerialize(): array { return $this->asArray(); } /** * Returns the search endpoint. - * - * @return string */ - private function getSearchEndpoint() + private function getSearchEndpoint(): string { return "{$this->endpoint}/search"; } diff --git a/src/Api/Search/SearchFoldersApi.php b/src/Api/Search/SearchFoldersApi.php index 50355241..6f98e050 100644 --- a/src/Api/Search/SearchFoldersApi.php +++ b/src/Api/Search/SearchFoldersApi.php @@ -23,14 +23,14 @@ class SearchFoldersApi extends SearchApi /** * @internal */ - const FOLDERS = 'folders'; + protected const FOLDERS = 'folders'; /** * SearchFoldersApi constructor. * - * @param mixed $configuration + * @param mixed|null $configuration */ - public function __construct($configuration = null) + public function __construct(mixed $configuration = null) { parent::__construct($configuration); diff --git a/src/Api/Search/SearchQueryInterface.php b/src/Api/Search/SearchQueryInterface.php index 26382cfb..118f44c3 100644 --- a/src/Api/Search/SearchQueryInterface.php +++ b/src/Api/Search/SearchQueryInterface.php @@ -10,34 +10,34 @@ interface SearchQueryInterface /** * @internal */ - const SORT_BY = 'sort_by'; + public const SORT_BY = 'sort_by'; /** * @internal */ - const AGGREGATE = 'aggregate'; + public const AGGREGATE = 'aggregate'; /** * @internal */ - const WITH_FIELD = 'with_field'; + public const WITH_FIELD = 'with_field'; /** * @internal */ - const FIELDS = 'fields'; + public const FIELDS = 'fields'; /** * @internal */ - const EXPRESSION = 'expression'; + public const EXPRESSION = 'expression'; /** * @internal */ - const MAX_RESULTS = 'max_results'; + public const MAX_RESULTS = 'max_results'; /** * @internal */ - const NEXT_CURSOR = 'next_cursor'; + public const NEXT_CURSOR = 'next_cursor'; /** * @internal */ - const KEYS_WITH_UNIQUE_VALUES = [self::SORT_BY, self::AGGREGATE, self::WITH_FIELD, self::FIELDS]; + public const KEYS_WITH_UNIQUE_VALUES = [self::SORT_BY, self::AGGREGATE, self::WITH_FIELD, self::FIELDS]; } diff --git a/src/Api/Search/SearchQueryTrait.php b/src/Api/Search/SearchQueryTrait.php index 8e217658..fbac722c 100644 --- a/src/Api/Search/SearchQueryTrait.php +++ b/src/Api/Search/SearchQueryTrait.php @@ -12,7 +12,7 @@ trait SearchQueryTrait /** * @var array query object that includes the search query */ - private $query + private array $query = [ self::SORT_BY => [], self::AGGREGATE => [], @@ -31,7 +31,7 @@ trait SearchQueryTrait * * @api */ - public function expression($value) + public function expression(mixed $value): static { $this->query[self::EXPRESSION] = $value; @@ -47,7 +47,7 @@ public function expression($value) * * @api */ - public function maxResults($value) + public function maxResults(int $value): static { $this->query[self::MAX_RESULTS] = $value; @@ -66,7 +66,7 @@ public function maxResults($value) * * @api */ - public function nextCursor($value) + public function nextCursor(string $value): static { $this->query[self::NEXT_CURSOR] = $value; @@ -84,7 +84,7 @@ public function nextCursor($value) * * @api */ - public function sortBy($fieldName, $dir = 'desc') + public function sortBy(string $fieldName, string $dir = 'desc'): static { $this->query[self::SORT_BY][$fieldName] = [$fieldName => $dir]; @@ -107,7 +107,7 @@ public function sortBy($fieldName, $dir = 'desc') * * @api */ - public function aggregate($value) + public function aggregate(string $value): static { $this->query[self::AGGREGATE][$value] = $value; @@ -123,7 +123,7 @@ public function aggregate($value) * * @api */ - public function withField($value) + public function withField(string $value): static { $this->query[self::WITH_FIELD][$value] = $value; @@ -139,7 +139,7 @@ public function withField($value) * * @api */ - public function fields($fields) + public function fields(array|string $fields): static { foreach (ArrayUtils::build($fields) as $field) { $this->query[self::FIELDS][$field] = $field; @@ -155,7 +155,7 @@ public function fields($fields) * * @return $this */ - public function query($query) + public function query(array $query): static { $this->query = $query; @@ -165,21 +165,18 @@ public function query($query) /** * Returns the query as an array. * - * @return array * * @api */ - public function asArray() + public function asArray(): array { return ArrayUtils::mapAssoc( - static function ($key, $value) { - return in_array($key, self::KEYS_WITH_UNIQUE_VALUES) ? array_values($value) : $value; - }, + static fn($key, $value) => in_array($key, self::KEYS_WITH_UNIQUE_VALUES) ? array_values($value) : $value, array_filter( $this->query, static function ($value) { /** @noinspection TypeUnsafeComparisonInspection */ - return ((is_array($value) && ! empty($value)) || ($value != null)); + return is_array($value) && ! empty($value) || $value != null; } ) ); diff --git a/src/Api/Upload/ArchiveTrait.php b/src/Api/Upload/ArchiveTrait.php index d31aafac..3b5dabed 100644 --- a/src/Api/Upload/ArchiveTrait.php +++ b/src/Api/Upload/ArchiveTrait.php @@ -29,12 +29,10 @@ trait ArchiveTrait /** * Returns an array of parameters used to create an archive. * - * @param $options * - * @return array * @internal */ - public static function buildArchiveParams($options) + public static function buildArchiveParams($options): array { $simpleParams = [ 'allow_missing', @@ -84,14 +82,8 @@ public static function buildArchiveParams($options) /** * Creates a new archive in the server and returns information in JSON format. - * - * @param array $options - * @param string $targetFormat - * - * @return PromiseInterface - * */ - public function createArchiveAsync($options = [], $targetFormat = null) + public function createArchiveAsync(array $options = [], ?string $targetFormat = null): PromiseInterface { $params = self::buildArchiveParams($options); ArrayUtils::addNonEmpty($params, 'target_format', $targetFormat); @@ -102,38 +94,25 @@ public function createArchiveAsync($options = [], $targetFormat = null) /** * Creates a new archive in the server and returns information in JSON format. * - * @param array $options - * @param null $targetFormat - * - * @return ApiResponse - * + * @param null $targetFormat */ - public function createArchive($options = [], $targetFormat = null) + public function createArchive(array $options = [], $targetFormat = null): ApiResponse { return $this->createArchiveAsync($options, $targetFormat)->wait(); } /** * Creates a new zip archive in the server and returns information in JSON format. - * - * @param array $options - * - * @return PromiseInterface */ - public function createZipAsync($options = []) + public function createZipAsync(array $options = []): PromiseInterface { return $this->createArchiveAsync($options, 'zip'); } /** * Creates a new zip archive in the server and returns information in JSON format. - * - * @param array $options - * - * @return ApiResponse - * */ - public function createZip($options = []) + public function createZip(array $options = []): ApiResponse { return $this->createZipAsync($options)->wait(); } @@ -145,41 +124,41 @@ public function createZip($options = []) * * @return string The resulting archive URL. * @var string $resource_type The resource type of files to include in the archive. - * Must be one of image | video | raw. + * Must be one of image | video | raw. * @var string $type The specific file delivery type of resources: - * upload|private|authenticated. + * upload|private|authenticated. * @var string|array $tags (null) list of tags to include in the archive. * @var string|array $public_ids (null) list of public_ids to include in the archive. * @var string|array $prefixes (null) Optional list of prefixes of public IDs (e.g., folders). * @var string|array $transformations Optional list of transformations. The derived images of the given - * transformations are included in the archive. Using the string - * representation of multiple chained transformations as we use for the - * 'eager' upload parameter. + * transformations are included in the archive. Using the string + * representation of multiple chained transformations as we use for the + * 'eager' upload parameter. * @var string $mode (create) return the generated archive file or store it as a raw - * resource and return a JSON with URLs for accessing the archive. Possible - * values: download, create. + * resource and return a JSON with URLs for accessing the archive. + * Possible values: download, create. * @var string $target_format (zip) * @var string $target_public_id Optional public ID of the generated raw resource. - * Relevant only for the create mode. If not specified, a random public ID is - * generated. + * Relevant only for the create mode. If not specified, a random public + * ID is generated. * @var bool $flatten_folders (false) If true, flatten public IDs with folders to be in the root of - * the archive. Add numeric counter to the file name in case of a name - * conflict. + * the archive. Add numeric counter to the file name in case of a name + * conflict. * @var bool $flatten_transformations (false) If true, and multiple transformations are given, - * flatten the folder structure of derived images and store the - * transformation details on the file name instead. + * flatten the folder structure of derived images and store the + * transformation details on the file name instead. * @var bool $use_original_filename Use the original file name of included images (if available) instead - * of the public ID. + * of the public ID. * @var bool $async (false) If true, return immediately and perform the archive creation - * in the background. Relevant only for the create mode. + * in the background. Relevant only for the create mode. * @var string $notification_url Optional URL to send an HTTP post request (webhook) when the archive - * creation is completed. + * creation is completed. * @var string|array $target_tags Optional array. Allows assigning one or more tag to the - * generated archive file (for later housekeeping via the admin API). + * generated archive file (for later housekeeping via the admin API). * @var string $keep_derived (false) keep the derived images used for generating the archive. * */ - public function downloadArchiveUrl($options = []) + public function downloadArchiveUrl(array $options = []): string { $options['mode'] = self::MODE_DOWNLOAD; $params = self::buildArchiveParams($options); @@ -200,7 +179,7 @@ public function downloadArchiveUrl($options = []) * * @see ArchiveTrait::downloadArchiveUrl */ - public function downloadZipUrl($options = []) + public function downloadZipUrl(array $options = []): string { $options['target_format'] = 'zip'; @@ -214,16 +193,15 @@ public function downloadZipUrl($options = []) * @param string $format The format of the asset to download. * @param array $options Additional options. * - * @return string */ - public function privateDownloadUrl($publicId, $format, $options = []) + public function privateDownloadUrl(string $publicId, string $format, array $options = []): string { $params = ApiUtils::finalizeUploadApiParams([ - "public_id" => $publicId, - "format" => $format, - "type" => ArrayUtils::get($options, "type"), - "attachment" => ArrayUtils::get($options, "attachment"), - "expires_at" => ArrayUtils::get($options, "expires_at"), + 'public_id' => $publicId, + 'format' => $format, + 'type' => ArrayUtils::get($options, 'type'), + 'attachment' => ArrayUtils::get($options, 'attachment'), + 'expires_at' => ArrayUtils::get($options, 'expires_at'), ]); ApiUtils::signRequest($params, $this->getCloud()); @@ -241,7 +219,7 @@ public function privateDownloadUrl($publicId, $format, $options = []) * * @return string Url for downloading an archive of a folder. */ - public function downloadFolder($folderPath, $options = []) + public function downloadFolder(string $folderPath, array $options = []): string { $options['prefixes'] = $folderPath; $options[AssetType::KEY] = ArrayUtils::get($options, AssetType::KEY, AssetType::ALL); @@ -257,10 +235,9 @@ public function downloadFolder($folderPath, $options = []) * * @return string The signed URL for downloading backup version of the asset. */ - public function downloadBackedupAsset($assetId, $versionId) + public function downloadBackedupAsset(string $assetId, string $versionId): string { - $options['asset_id'] = $assetId; - $options['version_id'] = $versionId; + $options = ['asset_id' => $assetId, 'version_id' => $versionId]; $params = self::buildArchiveParams($options); diff --git a/src/Api/Upload/ContextCommand.php b/src/Api/Upload/ContextCommand.php index b5bf2eb1..e678867f 100644 --- a/src/Api/Upload/ContextCommand.php +++ b/src/Api/Upload/ContextCommand.php @@ -15,6 +15,6 @@ */ class ContextCommand { - const ADD = 'add'; - const REMOVE_ALL = 'remove_all'; + public const ADD = 'add'; + public const REMOVE_ALL = 'remove_all'; } diff --git a/src/Api/Upload/ContextTrait.php b/src/Api/Upload/ContextTrait.php index 8305c197..07e0a904 100644 --- a/src/Api/Upload/ContextTrait.php +++ b/src/Api/Upload/ContextTrait.php @@ -34,11 +34,13 @@ trait ContextTrait * @param array|string $publicIds The public IDs of the assets to add context metadata to. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * @see https://cloudinary.com/documentation/image_upload_api_reference#context_method */ - public function addContextAsync($context, $publicIds = [], $options = []) - { + public function addContextAsync( + array|string $context, + array|string $publicIds = [], + array $options = [] + ): PromiseInterface { return $this->callContextApiAsync(ContextCommand::ADD, $context, $publicIds, $options); } @@ -49,10 +51,9 @@ public function addContextAsync($context, $publicIds = [], $options = []) * @param array|string $publicIds The public IDs of the assets to add context metadata to. * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * @see https://cloudinary.com/documentation/image_upload_api_reference#context_method */ - public function addContext($context, $publicIds = [], $options = []) + public function addContext(array|string $context, array|string $publicIds = [], array $options = []): ApiResponse { return $this->addContextAsync($context, $publicIds, $options)->wait(); } @@ -65,10 +66,9 @@ public function addContext($context, $publicIds = [], $options = []) * @param array|string $publicIds The public IDs of the assets to remove context metadata from. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * @see https://cloudinary.com/documentation/image_upload_api_reference#context_method */ - public function removeAllContextAsync($publicIds = [], $options = []) + public function removeAllContextAsync(array|string $publicIds = [], array $options = []): PromiseInterface { return $this->callContextApiAsync(ContextCommand::REMOVE_ALL, null, $publicIds, $options); } @@ -76,13 +76,12 @@ public function removeAllContextAsync($publicIds = [], $options = []) /** * Removes all context metadata from the specified assets. * - * @param array $publicIds The public IDs of the assets to remove context metadata from. - * @param array $options The optional parameters. See the upload API documentation. + * @param array|string $publicIds The public IDs of the assets to remove context metadata from. + * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * @see https://cloudinary.com/documentation/image_upload_api_reference#context_method */ - public function removeAllContext($publicIds = [], $options = []) + public function removeAllContext(array|string $publicIds = [], array $options = []): ApiResponse { return $this->removeAllContextAsync($publicIds, $options)->wait(); } @@ -90,18 +89,21 @@ public function removeAllContext($publicIds = [], $options = []) /** * Internal call to the context API. * - * @param string $command The command to perform. See ContextCommand class for available commands. - * @param array|string $context The key-value pairs of context metadata. - * @param array|string $publicIds The public IDs of the assets to apply context to. - * @param array $options The optional parameters. + * @param string $command The command to perform. See ContextCommand class for available commands. + * @param array|string|null $context The key-value pairs of context metadata. + * @param array|string $publicIds The public IDs of the assets to apply context to. + * @param array $options The optional parameters. * - * @return PromiseInterface * @see ContextCommand * * @internal */ - protected function callContextApiAsync($command, $context, $publicIds = [], $options = []) - { + protected function callContextApiAsync( + string $command, + array|string|null $context, + array|string $publicIds = [], + array $options = [] + ): PromiseInterface { $params = [ 'context' => ApiUtils::serializeContext($context), 'public_ids' => ArrayUtils::build($publicIds), diff --git a/src/Api/Upload/CreativeTrait.php b/src/Api/Upload/CreativeTrait.php index cce86e6e..17d1a88c 100644 --- a/src/Api/Upload/CreativeTrait.php +++ b/src/Api/Upload/CreativeTrait.php @@ -37,15 +37,14 @@ trait CreativeTrait * * This is an asynchronous function. * - * @param string|array $tag A string specifying a tag that indicates which images to include or an array + * @param array|string $tag A string specifying a tag that indicates which images to include or an array * which include options and image URLs. * @param array $options The optional parameters. Should be omitted when $tag is an array. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/image_upload_api_reference#sprite_method */ - public function generateSpriteAsync($tag, $options = []) + public function generateSpriteAsync(array|string $tag, array $options = []): PromiseInterface { $params = self::buildSpriteAndMultiParams($tag, $options); @@ -59,15 +58,14 @@ public function generateSpriteAsync($tag, $options = []) * * A single sprite image file containing all the images. * * A CSS file that includes the style class names and the location of the individual images in the sprite. * - * @param string|array $tag A string specifying a tag that indicates which images to include or an array + * @param array|string $tag A string specifying a tag that indicates which images to include or an array * which include options and image URLs. * @param array $options The optional parameters. Should be omitted when $tag is an array. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/image_upload_api_reference#sprite_method */ - public function generateSprite($tag, $options = []) + public function generateSprite(array|string $tag, array $options = []): ApiResponse { return $this->generateSpriteAsync($tag, $options)->wait(); } @@ -76,15 +74,14 @@ public function generateSprite($tag, $options = []) * Generates an url to create a sprite from all images that have been assigned a specified tag or from a provided * array of URLs. * - * @param string|array $tag A string specifying a tag that indicates which images to include or an array + * @param array|string $tag A string specifying a tag that indicates which images to include or an array * which include options and image URLs. * @param array $options The optional parameters. Should be omitted when $tag is an array. * - * @return string * * @see https://cloudinary.com/documentation/image_upload_api_reference#sprite_method */ - public function downloadGeneratedSprite($tag, $options = []) + public function downloadGeneratedSprite(array|string $tag, array $options = []): string { $params = self::buildSpriteAndMultiParams($tag, $options); @@ -103,15 +100,14 @@ public function downloadGeneratedSprite($tag, $options = []) * * This is an asynchronous function. * - * @param string|array $tag A string specifying a tag that indicates which images to include or an array + * @param array|string $tag A string specifying a tag that indicates which images to include or an array * which include options and image URLs. * @param array $options The optional parameters. Should be omitted when $tag is an array. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/image_upload_api_reference#multi_method */ - public function multiAsync($tag, $options = []) + public function multiAsync(array|string $tag, array $options = []): PromiseInterface { $params = self::buildSpriteAndMultiParams($tag, $options); @@ -122,15 +118,14 @@ public function multiAsync($tag, $options = []) * Creates a single animated image, video or PDF from all image assets that have been assigned a specified tag or * from a provided array of URLs. * - * @param string|array $tag A string specifying a tag that indicates which images to include or an array + * @param array|string $tag A string specifying a tag that indicates which images to include or an array * which include options and image URLs. * @param array $options The optional parameters. Should be omitted when $tag is an array. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/image_upload_api_reference#multi_method */ - public function multi($tag, $options = []) + public function multi(array|string $tag, array $options = []): ApiResponse { return $this->multiAsync($tag, $options)->wait(); } @@ -139,15 +134,14 @@ public function multi($tag, $options = []) * Generates an url to create a single animated image, video or PDF from all image assets that have been assigned * a specified tag or from a provided array of URLs. * - * @param string|array $tag A string specifying a tag that indicates which images to include or an array + * @param array|string $tag A string specifying a tag that indicates which images to include or an array * which include options and image URLs. * @param array $options The optional parameters. Should be omitted when $tag is an array. * - * @return string * * @see https://cloudinary.com/documentation/image_upload_api_reference#sprite_method */ - public function downloadMulti($tag, $options = []) + public function downloadMulti(array|string $tag, array $options = []): string { $params = self::buildSpriteAndMultiParams($tag, $options); @@ -171,11 +165,10 @@ public function downloadMulti($tag, $options = []) * @param string $publicId The public ID of the multi-page file. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/image_upload_api_reference#explode_method */ - public function explodeAsync($publicId, $options = []) + public function explodeAsync(string $publicId, array $options = []): PromiseInterface { $options['transformation'] = ApiUtils::serializeAssetTransformations($options); @@ -197,11 +190,10 @@ public function explodeAsync($publicId, $options = []) * @param string $publicId The public ID of the multi-page file. * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/image_upload_api_reference#explode_method */ - public function explode($publicId, $options = []) + public function explode(string $publicId, array $options = []): ApiResponse { return $this->explodeAsync($publicId, $options)->wait(); } @@ -214,11 +206,10 @@ public function explode($publicId, $options = []) * @param string $text The text string to generate an image for. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/image_upload_api_reference#text_method */ - public function textAsync($text, $options = []) + public function textAsync(string $text, array $options = []): PromiseInterface { $params = ArrayUtils::whitelist( $options, @@ -246,11 +237,10 @@ public function textAsync($text, $options = []) * @param string $text The text string to generate an image for. * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/image_upload_api_reference#text_method */ - public function text($text, $options = []) + public function text(string $text, array $options = []): ApiResponse { return $this->textAsync($text, $options)->wait(); } @@ -258,13 +248,12 @@ public function text($text, $options = []) /** * Build params for multi, downloadMulti, generateSprite, and downloadGeneratedSprite methods. * - * @param string|array $tagOrOptions A string specifying a tag that indicates which images to include or an array + * @param array|string $tagOrOptions A string specifying a tag that indicates which images to include or an array * which include image URLs and options. * @param array $options The optional parameters. Should be omitted when $tagOrOptions is an array. * - * @return array */ - private static function buildSpriteAndMultiParams($tagOrOptions, $options) + private static function buildSpriteAndMultiParams(array|string $tagOrOptions, array $options): array { if (is_array($tagOrOptions)) { if (empty($options)) { @@ -299,11 +288,10 @@ private static function buildSpriteAndMultiParams($tagOrOptions, $options) * * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/video_slideshow_generation */ - public function createSlideshowAsync($options = []) + public function createSlideshowAsync(array $options = []): PromiseInterface { $params = ArrayUtils::whitelist( $options, @@ -342,11 +330,10 @@ public function createSlideshowAsync($options = []) * * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/video_slideshow_generation */ - public function createSlideshow($options = []) + public function createSlideshow(array $options = []): ApiResponse { return $this->createSlideshowAsync($options)->wait(); } diff --git a/src/Api/Upload/EditTrait.php b/src/Api/Upload/EditTrait.php index 2ecb1565..ef0487f6 100644 --- a/src/Api/Upload/EditTrait.php +++ b/src/Api/Upload/EditTrait.php @@ -37,11 +37,10 @@ trait EditTrait * @param string $publicId The public ID of the asset to delete. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/image_upload_api_reference#destroy_method */ - public function destroyAsync($publicId, $options = []) + public function destroyAsync(string $publicId, array $options = []): PromiseInterface { $params = ArrayUtils::whitelist($options, ['type', 'invalidate']); $params['public_id'] = $publicId; @@ -59,11 +58,10 @@ public function destroyAsync($publicId, $options = []) * @param string $publicId The public ID of the asset to delete. * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/image_upload_api_reference#destroy_method */ - public function destroy($publicId, $options = []) + public function destroy(string $publicId, array $options = []): ApiResponse { return $this->destroyAsync($publicId, $options)->wait(); } @@ -81,11 +79,10 @@ public function destroy($publicId, $options = []) * @param string $toPublicId The new public ID of the asset. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/image_upload_api_reference#rename_method */ - public function renameAsync($fromPublicId, $toPublicId, $options = []) + public function renameAsync(string $fromPublicId, string $toPublicId, array $options = []): PromiseInterface { $params = ArrayUtils::whitelist($options, [ 'type', @@ -112,11 +109,10 @@ public function renameAsync($fromPublicId, $toPublicId, $options = []) * @param string $toPublicId The new public ID of the asset. * @param array $options The optional parameters. See the upload API documentation. * - * @return mixed * * @see https://cloudinary.com/documentation/image_upload_api_reference#rename_method */ - public function rename($fromPublicId, $toPublicId, $options = []) + public function rename(string $fromPublicId, string $toPublicId, array $options = []): mixed { return $this->renameAsync($fromPublicId, $toPublicId, $options)->wait(); } @@ -129,11 +125,9 @@ public function rename($fromPublicId, $toPublicId, $options = []) * @param string $publicId The public ID of the asset to apply the actions to. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface - * * @see https://cloudinary.com/documentation/image_upload_api_reference#explicit_method */ - public function explicitAsync($publicId, $options = []) + public function explicitAsync(string $publicId, array $options = []): PromiseInterface { $options['public_id'] = $publicId; @@ -148,11 +142,9 @@ public function explicitAsync($publicId, $options = []) * @param string $publicId The public ID of the asset to apply the actions to. * @param array $options The optional parameters. See the upload API documentation. * - * @return mixed - * * @see https://cloudinary.com/documentation/image_upload_api_reference#explicit_method */ - public function explicit($publicId, $options = []) + public function explicit(string $publicId, array $options = []): mixed { return $this->explicitAsync($publicId, $options)->wait(); } @@ -174,7 +166,7 @@ public function explicit($publicId, $options = []) * * @see https://cloudinary.com/documentation/image_upload_api_reference#metadata_method */ - public function updateMetadataAsync(array $metadata, array $publicIds, array $options) + public function updateMetadataAsync(array $metadata, array $publicIds, array $options): PromiseInterface { $params = ArrayUtils::whitelist($options, ['type']); @@ -201,7 +193,7 @@ public function updateMetadataAsync(array $metadata, array $publicIds, array $op * * @see https://cloudinary.com/documentation/image_upload_api_reference#metadata_method */ - public function updateMetadata(array $metadata, array $publicIds, array $options = []) + public function updateMetadata(array $metadata, array $publicIds, array $options = []): mixed { return $this->updateMetadataAsync($metadata, $publicIds, $options)->wait(); } diff --git a/src/Api/Upload/TagCommand.php b/src/Api/Upload/TagCommand.php index bdd32580..08454f24 100644 --- a/src/Api/Upload/TagCommand.php +++ b/src/Api/Upload/TagCommand.php @@ -15,9 +15,9 @@ */ class TagCommand { - const ADD = 'add'; - const REMOVE = 'remove'; - const REPLACE = 'replace'; - const SET_EXCLUSIVE = 'set_exclusive'; - const REMOVE_ALL = 'remove_all'; + public const ADD = 'add'; + public const REMOVE = 'remove'; + public const REPLACE = 'replace'; + public const SET_EXCLUSIVE = 'set_exclusive'; + public const REMOVE_ALL = 'remove_all'; } diff --git a/src/Api/Upload/TagTrait.php b/src/Api/Upload/TagTrait.php index 5ad6c932..ac4fe233 100644 --- a/src/Api/Upload/TagTrait.php +++ b/src/Api/Upload/TagTrait.php @@ -33,11 +33,10 @@ trait TagTrait * @param array $publicIds The public IDs of the assets to add the tag to. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/image_upload_api_reference#tags_method */ - public function addTagAsync($tag, $publicIds = [], $options = []) + public function addTagAsync(string $tag, array $publicIds = [], array $options = []): PromiseInterface { return $this->callTagsApiAsync(TagCommand::ADD, $tag, $publicIds, $options); } @@ -49,11 +48,10 @@ public function addTagAsync($tag, $publicIds = [], $options = []) * @param array $publicIds The public IDs of the assets to add the tag to. * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/image_upload_api_reference#tags_method */ - public function addTag($tag, $publicIds = [], $options = []) + public function addTag(string $tag, array $publicIds = [], array $options = []): ApiResponse { return $this->addTagAsync($tag, $publicIds, $options)->wait(); } @@ -67,11 +65,10 @@ public function addTag($tag, $publicIds = [], $options = []) * @param array|string $publicIds The public IDs of the assets to remove the tags from. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/image_upload_api_reference#tags_method */ - public function removeTagAsync($tag, $publicIds = [], $options = []) + public function removeTagAsync(string $tag, array|string $publicIds = [], array $options = []): PromiseInterface { return $this->callTagsApiAsync(TagCommand::REMOVE, $tag, $publicIds, $options); } @@ -83,11 +80,10 @@ public function removeTagAsync($tag, $publicIds = [], $options = []) * @param array|string $publicIds The public IDs of the assets to remove the tags from. * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/image_upload_api_reference#tags_method */ - public function removeTag($tag, $publicIds = [], $options = []) + public function removeTag(string $tag, array|string $publicIds = [], array $options = []): ApiResponse { return $this->removeTagAsync($tag, $publicIds, $options)->wait(); } @@ -100,11 +96,10 @@ public function removeTag($tag, $publicIds = [], $options = []) * @param array $publicIds The public IDs of the assets to remove all tags from. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/image_upload_api_reference#tags_method */ - public function removeAllTagsAsync($publicIds = [], $options = []) + public function removeAllTagsAsync(array $publicIds = [], array $options = []): PromiseInterface { return $this->callTagsApiAsync(TagCommand::REMOVE_ALL, null, $publicIds, $options); } @@ -115,11 +110,10 @@ public function removeAllTagsAsync($publicIds = [], $options = []) * @param array $publicIds The public IDs of the assets to remove all tags from. * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/image_upload_api_reference#tags_method */ - public function removeAllTags($publicIds = [], $options = []) + public function removeAllTags(array $publicIds = [], array $options = []): ApiResponse { return $this->removeAllTagsAsync($publicIds, $options)->wait(); } @@ -133,11 +127,10 @@ public function removeAllTags($publicIds = [], $options = []) * @param array|string $publicIds The public IDs of the assets to replace the tags of. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * * @see https://cloudinary.com/documentation/image_upload_api_reference#tags_method */ - public function replaceTagAsync($tag, $publicIds = [], $options = []) + public function replaceTagAsync(string $tag, array|string $publicIds = [], array $options = []): PromiseInterface { return $this->callTagsApiAsync(TagCommand::REPLACE, $tag, $publicIds, $options); } @@ -149,11 +142,10 @@ public function replaceTagAsync($tag, $publicIds = [], $options = []) * @param array|string $publicIds The public IDs of the assets to replace the tags of. * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * * @see https://cloudinary.com/documentation/image_upload_api_reference#tags_method */ - public function replaceTag($tag, $publicIds = [], $options = []) + public function replaceTag(string $tag, array|string $publicIds = [], array $options = []): ApiResponse { return $this->replaceTagAsync($tag, $publicIds, $options)->wait(); } @@ -162,17 +154,20 @@ public function replaceTag($tag, $publicIds = [], $options = []) * Internal call to the tags API. * * @param string $command The command to perform. See TagCommand class for available commands. - * @param string $tag The tag. + * @param string|null $tag The tag. * @param array|string $publicIds The public IDs of the assets to apply tag to. * @param array $options The optional parameters. * - * @return PromiseInterface * @see TagCommand * * @internal */ - protected function callTagsApiAsync($command, $tag, $publicIds = [], $options = []) - { + protected function callTagsApiAsync( + string $command, + ?string $tag, + array|string $publicIds = [], + array $options = [] + ): PromiseInterface { $params = [ 'tag' => $tag, 'public_ids' => $publicIds, diff --git a/src/Api/Upload/UploadApi.php b/src/Api/Upload/UploadApi.php index fdbe1732..edadfcaf 100644 --- a/src/Api/Upload/UploadApi.php +++ b/src/Api/Upload/UploadApi.php @@ -34,7 +34,7 @@ class UploadApi use TagTrait; use UploadTrait; - const MODE_DOWNLOAD = 'download'; + public const MODE_DOWNLOAD = 'download'; /** * @var UploadApiClient $apiClient The HTTP API client instance. @@ -44,9 +44,9 @@ class UploadApi /** * Admin Api constructor. * - * @param mixed $configuration + * @param mixed|null $configuration */ - public function __construct($configuration = null) + public function __construct(mixed $configuration = null) { $this->apiClient = new UploadApiClient($configuration); } @@ -54,15 +54,14 @@ public function __construct($configuration = null) /** * Gets Upload API end point. * - * @param string $action The action to perform. + * @param string $action The action to perform. * * @param array $options Additional options. * - * @return string * * @internal */ - protected static function getUploadApiEndPoint($action, $options = []) + protected static function getUploadApiEndPoint(string $action, array $options = []): string { return ArrayUtils::implodeUrl([ArrayUtils::get($options, 'resource_type', AssetType::IMAGE), $action]); } @@ -70,14 +69,16 @@ protected static function getUploadApiEndPoint($action, $options = []) /** * Gets upload URL for the specified asset type and endpoint. * - * @param string $assetType The asset type. - * @param string $endPoint The endpoint name. - * @param array $params Additional query parameters. + * @param ?string $assetType The asset type. + * @param string $endPoint The endpoint name. + * @param array $params Additional query parameters. * - * @return string */ - public function getUploadUrl($assetType = AssetType::AUTO, $endPoint = UploadEndPoint::UPLOAD, $params = []) - { + public function getUploadUrl( + ?string $assetType = AssetType::AUTO, + string $endPoint = UploadEndPoint::UPLOAD, + array $params = [] + ): string { $baseUrl = $this->apiClient->getBaseUri(); $path = self::getUploadApiEndPoint($endPoint, ['resource_type' => $assetType]); @@ -88,11 +89,10 @@ public function getUploadUrl($assetType = AssetType::AUTO, $endPoint = UploadEnd /** * Gets cloud config of the current instance. * - * @return CloudConfig * * @internal */ - public function getCloud() + public function getCloud(): CloudConfig { return $this->apiClient->getCloud(); } @@ -104,12 +104,14 @@ public function getCloud() * @param array $params Parameters to pass to the endpoint. * @param array $options Additional options. * - * @return PromiseInterface * * @internal */ - protected function callUploadApiAsync($endPoint = UploadEndPoint::UPLOAD, $params = [], $options = []) - { + protected function callUploadApiAsync( + string $endPoint = UploadEndPoint::UPLOAD, + array $params = [], + array $options = [] + ): PromiseInterface { return $this->apiClient->postAndSignFormAsync( self::getUploadApiEndPoint($endPoint, $options), ApiUtils::finalizeUploadApiParams($params) @@ -123,12 +125,14 @@ protected function callUploadApiAsync($endPoint = UploadEndPoint::UPLOAD, $param * @param array $params Parameters to pass to the endpoint. * @param array $options Additional options. * - * @return PromiseInterface * * @internal */ - protected function callUploadApiJsonAsync($endPoint = UploadEndPoint::UPLOAD, $params = [], $options = []) - { + protected function callUploadApiJsonAsync( + string $endPoint = UploadEndPoint::UPLOAD, + array $params = [], + array $options = [] + ): PromiseInterface { return $this->apiClient->postAndSignJsonAsync( self::getUploadApiEndPoint($endPoint, $options), ApiUtils::finalizeUploadApiParams($params) diff --git a/src/Api/Upload/UploadEndPoint.php b/src/Api/Upload/UploadEndPoint.php index 27d82c82..ad807374 100644 --- a/src/Api/Upload/UploadEndPoint.php +++ b/src/Api/Upload/UploadEndPoint.php @@ -15,19 +15,19 @@ */ class UploadEndPoint { - const UPLOAD = 'upload'; - const DESTROY = 'destroy'; - const RENAME = 'rename'; - const EXPLICIT = 'explicit'; - const SPRITE = 'sprite'; - const MULTI = 'multi'; - const EXPLODE = 'explode'; - const TAGS = 'tags'; - const CONTEXT = 'context'; - const TEXT = 'text'; - const GENERATE_ARCHIVE = 'generate_archive'; - const CREATE_SLIDESHOW = 'create_slideshow'; - const METADATA = 'metadata'; - const DOWNLOAD = 'download'; - const DOWNLOAD_BACKUP = 'download_backup'; + public const UPLOAD = 'upload'; + public const DESTROY = 'destroy'; + public const RENAME = 'rename'; + public const EXPLICIT = 'explicit'; + public const SPRITE = 'sprite'; + public const MULTI = 'multi'; + public const EXPLODE = 'explode'; + public const TAGS = 'tags'; + public const CONTEXT = 'context'; + public const TEXT = 'text'; + public const GENERATE_ARCHIVE = 'generate_archive'; + public const CREATE_SLIDESHOW = 'create_slideshow'; + public const METADATA = 'metadata'; + public const DOWNLOAD = 'download'; + public const DOWNLOAD_BACKUP = 'download_backup'; } diff --git a/src/Api/Upload/UploadTrait.php b/src/Api/Upload/UploadTrait.php index fa421ca9..365ee3dc 100644 --- a/src/Api/Upload/UploadTrait.php +++ b/src/Api/Upload/UploadTrait.php @@ -32,11 +32,10 @@ trait UploadTrait * * @param array $options The optional parameters. See the upload API documentation. * - * @return array * * @see https://cloudinary.com/documentation/image_upload_api_reference#upload_method */ - public static function buildUploadParams($options) + public static function buildUploadParams(array $options): array { $simpleParams = [ 'accessibility_analysis', @@ -102,7 +101,7 @@ public static function buildUploadParams($options) 'responsive_breakpoints' => ApiUtils::serializeResponsiveBreakpoints( ArrayUtils::get($options, 'responsive_breakpoints') ), - 'tags' => ApiUtils::serializeSimpleApiParam((ArrayUtils::get($options, 'tags'))), + 'tags' => ApiUtils::serializeSimpleApiParam(ArrayUtils::get($options, 'tags')), 'transformation' => ApiUtils::serializeTransformation($options), ]; @@ -123,16 +122,15 @@ public static function buildUploadParams($options) * * This is an asynchronous function. * - * @param string $file The asset to upload. - * @param array $options The optional parameters. See the upload API documentation. + * @param mixed $file The asset to upload. + * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * * @throws ApiError * * @see https://cloudinary.com/documentation/image_upload_api_reference#upload_method */ - public function uploadAsync($file, $options = []) + public function uploadAsync(mixed $file, array $options = []): PromiseInterface { $params = UploadApi::buildUploadParams($options); $endPoint = self::getUploadApiEndPoint(UploadEndPoint::UPLOAD, $options); @@ -150,16 +148,15 @@ public function uploadAsync($file, $options = []) * * the remote FTP, HTTP or HTTPS URL address of an existing file * * a private storage bucket (S3 or Google Storage) URL of a whitelisted bucket * - * @param string $file The asset to upload. - * @param array $options The optional parameters. See the upload API documentation. + * @param mixed $file The asset to upload. + * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * * @throws ApiError * * @see https://cloudinary.com/documentation/image_upload_api_reference#upload_method */ - public function upload($file, $options = []) + public function upload(mixed $file, array $options = []): ApiResponse { return $this->uploadAsync($file, $options)->wait(); } @@ -175,13 +172,12 @@ public function upload($file, $options = []) * @param string $uploadPreset The name of an upload preset. * @param array $options The optional parameters. See the upload API documentation. * - * @return PromiseInterface * * @throws ApiError * * @see https://cloudinary.com/documentation/image_upload_api_reference#unsigned_upload_syntax */ - public function unsignedUploadAsync($file, $uploadPreset, $options = []) + public function unsignedUploadAsync(string $file, string $uploadPreset, array $options = []): PromiseInterface { $options = array_merge($options, ['unsigned' => true, 'upload_preset' => $uploadPreset]); @@ -197,13 +193,12 @@ public function unsignedUploadAsync($file, $uploadPreset, $options = []) * @param string $uploadPreset The name of an upload preset. * @param array $options The optional parameters. See the upload API documentation. * - * @return ApiResponse * * @throws ApiError * * @see https://cloudinary.com/documentation/image_upload_api_reference#unsigned_upload_syntax */ - public function unsignedUpload($file, $uploadPreset, $options = []) + public function unsignedUpload(string $file, string $uploadPreset, array $options = []): ApiResponse { return $this->unsignedUploadAsync($file, $uploadPreset, $options)->wait(); } diff --git a/src/Api/UploadApiClient.php b/src/Api/UploadApiClient.php index d6248bf3..659ce9cc 100644 --- a/src/Api/UploadApiClient.php +++ b/src/Api/UploadApiClient.php @@ -32,7 +32,7 @@ class UploadApiClient extends ApiClient * * @internal */ - protected static function validateAuthorization($cloudConfig, $options) + protected static function validateAuthorization(CloudConfig $cloudConfig, array $options): void { if (!ArrayUtils::get($options, 'unsigned')) { parent::validateAuthorization($cloudConfig, $options); diff --git a/src/Api/Utils/ApiUtils.php b/src/Api/Utils/ApiUtils.php index b7ffe85f..b8ebeb3f 100644 --- a/src/Api/Utils/ApiUtils.php +++ b/src/Api/Utils/ApiUtils.php @@ -24,15 +24,15 @@ */ class ApiUtils { - const HEADERS_OUTER_DELIMITER = "\n"; - const HEADERS_INNER_DELIMITER = ':'; - const API_PARAM_DELIMITER = ','; - const CONTEXT_OUTER_DELIMITER = '|'; - const CONTEXT_INNER_DELIMITER = '='; - const ARRAY_OF_ARRAYS_DELIMITER = '|'; - const ASSET_TRANSFORMATIONS_DELIMITER = '|'; - const QUERY_STRING_INNER_DELIMITER = '='; - const QUERY_STRING_OUTER_DELIMITER = '&'; + public const HEADERS_OUTER_DELIMITER = "\n"; + public const HEADERS_INNER_DELIMITER = ':'; + public const API_PARAM_DELIMITER = ','; + public const CONTEXT_OUTER_DELIMITER = '|'; + public const CONTEXT_INNER_DELIMITER = '='; + public const ARRAY_OF_ARRAYS_DELIMITER = '|'; + public const ASSET_TRANSFORMATIONS_DELIMITER = '|'; + public const QUERY_STRING_INNER_DELIMITER = '='; + public const QUERY_STRING_OUTER_DELIMITER = '&'; /** * Serializes a simple parameter, which can be a serializable object. @@ -41,13 +41,13 @@ class ApiUtils * * @param string|array|mixed $parameter The parameter to serialize. * - * @return string The resulting serialized parameter. + * @return string|null The resulting serialized parameter. * * @internal * * @see ApiUtils::API_PARAM_DELIMITER */ - public static function serializeSimpleApiParam($parameter) + public static function serializeSimpleApiParam(mixed $parameter): ?string { return self::serializeParameter($parameter, self::API_PARAM_DELIMITER); } @@ -55,13 +55,12 @@ public static function serializeSimpleApiParam($parameter) /** * Serializes 'headers' upload API parameter. * - * @param $headers * - * @return string The resulting serialized parameter. + * @return string|null The resulting serialized parameter. * * @internal */ - public static function serializeHeaders($headers) + public static function serializeHeaders($headers): ?string { return self::serializeParameter($headers, self::HEADERS_OUTER_DELIMITER, self::HEADERS_INNER_DELIMITER); } @@ -69,13 +68,11 @@ public static function serializeHeaders($headers) /** * Serializes 'context' and 'metadata' upload API parameters. * - * @param array $context - * - * @return string The resulting serialized parameter. + * @return ?string The resulting serialized parameter. * * @internal */ - public static function serializeContext($context) + public static function serializeContext(mixed $context): ?string { if (is_array($context)) { $context = array_map('\Cloudinary\Api\ApiUtils::serializeJson', $context); @@ -89,18 +86,18 @@ public static function serializeContext($context) * * @param mixed $jsonParam Json object * - * @return string The resulting serialized parameter. + * @return string|null The resulting serialized parameter. * * @internal */ - public static function serializeJson($jsonParam) + public static function serializeJson(mixed $jsonParam): ?string { if ($jsonParam === null) { return null; } // Avoid extra double quotes around strings. - if (is_string($jsonParam) || (is_object($jsonParam) && method_exists($jsonParam, '__toString'))) { + if (is_string($jsonParam) || is_object($jsonParam) && method_exists($jsonParam, '__toString')) { return $jsonParam; } @@ -110,16 +107,14 @@ public static function serializeJson($jsonParam) /** * Commonly used util for building Cloudinary API params. * - * @param $parameter - * @param $outerDelimiter + * @param null $outerDelimiter * @param null $innerDelimiter * - * @return string The resulting serialized parameter. + * @return string|null The resulting serialized parameter. * * @internal - * */ - public static function serializeParameter($parameter, $outerDelimiter = null, $innerDelimiter = null) + public static function serializeParameter($parameter, $outerDelimiter = null, $innerDelimiter = null): ?string { if (! is_array($parameter)) { return $parameter === null ? null : (string)$parameter; // can be a serializable object @@ -131,13 +126,13 @@ public static function serializeParameter($parameter, $outerDelimiter = null, $i /** * Serializes array of nested array parameters. * - * @param array $arrayOfArrays The input array. + * @param mixed $arrayOfArrays The input array. * - * @return string The resulting serialized parameter. + * @return ?string The resulting serialized parameter. * * @internal */ - public static function serializeArrayOfArrays($arrayOfArrays) + public static function serializeArrayOfArrays(mixed $arrayOfArrays): ?string { $array = ArrayUtils::build($arrayOfArrays); @@ -158,13 +153,12 @@ public static function serializeArrayOfArrays($arrayOfArrays) /** * Serializes asset transformations. * - * @param array|string $transformations * * @return string The resulting serialized parameter. * * @internal */ - public static function serializeAssetTransformations($transformations) + public static function serializeAssetTransformations(array|string|null $transformations): string { $serializedTransformations = []; @@ -181,13 +175,12 @@ public static function serializeAssetTransformations($transformations) /** * Serializes incoming transformation. * - * @param array|string $transformationParams * * @return string The resulting serialized parameter. * * @internal */ - public static function serializeTransformation($transformationParams) + public static function serializeTransformation(array|string $transformationParams): string { return (string)ClassUtils::forceInstance($transformationParams, Transformation::class); } @@ -204,7 +197,7 @@ public static function serializeTransformation($transformationParams) * @internal * */ - public static function finalizeUploadApiParams($params) + public static function finalizeUploadApiParams(array $params): array { $additionalParams = [ 'timestamp' => Utils::unixTimeNow(), @@ -220,13 +213,12 @@ public static function finalizeUploadApiParams($params) /** * Serializes responsive breakpoints. * - * @param array $breakpoints * * @return false|string|null * * @internal */ - public static function serializeResponsiveBreakpoints($breakpoints) + public static function serializeResponsiveBreakpoints(?array $breakpoints): bool|string|null { if (! $breakpoints) { return null; @@ -246,13 +238,11 @@ public static function serializeResponsiveBreakpoints($breakpoints) } /** - * @param array $parameters * - * @return string * * @internal */ - public static function serializeQueryParams($parameters = []) + public static function serializeQueryParams(array $parameters = []): string { return ArrayUtils::implodeAssoc( $parameters, @@ -272,8 +262,11 @@ public static function serializeQueryParams($parameters = []) * * @api */ - public static function signParameters($parameters, $secret, $signatureAlgorithm = Utils::ALGO_SHA1) - { + public static function signParameters( + array $parameters, + string $secret, + string $signatureAlgorithm = Utils::ALGO_SHA1 + ): string { $parameters = array_map(self::class . '::serializeSimpleApiParam', $parameters); ksort($parameters); @@ -286,12 +279,10 @@ public static function signParameters($parameters, $secret, $signatureAlgorithm /** * Adds signature and api_key to $parameters. * - * @param array|null $parameters - * @param CloudConfig $cloudConfig * * @internal */ - public static function signRequest(&$parameters, $cloudConfig) + public static function signRequest(?array &$parameters, CloudConfig $cloudConfig): void { $parameters['signature'] = self::signParameters( $parameters, diff --git a/src/Api/Utils/HttpMethod.php b/src/Api/Utils/HttpMethod.php index a7312ef8..3f6536bb 100644 --- a/src/Api/Utils/HttpMethod.php +++ b/src/Api/Utils/HttpMethod.php @@ -21,39 +21,39 @@ abstract class HttpMethod * @var string The GET method requests a representation of the specified resource. * Requests using GET should only retrieve data. */ - const GET = 'GET'; + public const GET = 'GET'; /** * @var string The HEAD method asks for a response identical to that of a GET request, * but without the response body. */ - const HEAD = 'HEAD'; + public const HEAD = 'HEAD'; /** * @var string The POST method is used to submit an entity to the specified resource, often causing a change in * state or side effects on the server. */ - const POST = 'POST'; + public const POST = 'POST'; /** * @var string The PUT method replaces all current representations of the target resource with the request payload. */ - const PUT = 'PUT'; + public const PUT = 'PUT'; /** * @var string The DELETE method deletes the specified resource. */ - const DELETE = 'DELETE'; + public const DELETE = 'DELETE'; /** * @var string The CONNECT method establishes a tunnel to the server identified by the target resource. */ - const CONNECT = 'CONNECT'; + public const CONNECT = 'CONNECT'; /** * @var string The OPTIONS method is used to describe the communication options for the target resource. */ - const OPTIONS = 'OPTIONS'; + public const OPTIONS = 'OPTIONS'; /** * @var string The TRACE method performs a message loop-back test along the path to the target resource. */ - const TRACE = 'TRACE'; + public const TRACE = 'TRACE'; /** * @var string The PATCH method is used to apply partial modifications to a resource. */ - const PATCH = 'PATCH'; + public const PATCH = 'PATCH'; } diff --git a/src/Api/Utils/HttpStatusCode.php b/src/Api/Utils/HttpStatusCode.php index ba37ad84..7e367745 100644 --- a/src/Api/Utils/HttpStatusCode.php +++ b/src/Api/Utils/HttpStatusCode.php @@ -16,7 +16,7 @@ class HttpStatusCode * * @var int */ - const OK = 200; + public const OK = 200; /** @@ -29,7 +29,7 @@ class HttpStatusCode * * @var int */ - const BAD_REQUEST = 400; + public const BAD_REQUEST = 400; /** * The 401 (Unauthorized) status code indicates that the request has not @@ -42,7 +42,7 @@ class HttpStatusCode * * @var int */ - const UNAUTHORIZED = 401; + public const UNAUTHORIZED = 401; /** * The 403 (Forbidden) status code indicates that the server understood the @@ -54,7 +54,7 @@ class HttpStatusCode * * @var int */ - const FORBIDDEN = 403; + public const FORBIDDEN = 403; /** * The 404 (Not Found) status code indicates that the origin server did not @@ -65,7 +65,7 @@ class HttpStatusCode * * @var int */ - const NOT_FOUND = 404; + public const NOT_FOUND = 404; /** * The 409 (Conflict) status code indicates that the request could not be @@ -79,7 +79,7 @@ class HttpStatusCode * * @var int */ - const CONFLICT = 409; + public const CONFLICT = 409; /** * Returned when you are being rate limited. @@ -88,7 +88,7 @@ class HttpStatusCode * * @var int */ - const ENHANCE_YOUR_CALM = 420; + public const ENHANCE_YOUR_CALM = 420; /** * The 500 (Internal Server Error) status code indicates that the server @@ -99,6 +99,6 @@ class HttpStatusCode * * @var int */ - const INTERNAL_SERVER_ERROR = 500; + public const INTERNAL_SERVER_ERROR = 500; } diff --git a/src/Asset/AccessControl/AccessControlRule.php b/src/Asset/AccessControl/AccessControlRule.php index e518d707..13caaf85 100644 --- a/src/Asset/AccessControl/AccessControlRule.php +++ b/src/Asset/AccessControl/AccessControlRule.php @@ -29,32 +29,32 @@ class AccessControlRule implements JsonSerializable * * @see AccessType for available types. */ - protected $accessType; + protected string $accessType; /** * The start time. * - * @var DateTime $start + * @var ?DateTime $start */ - protected $start; + protected ?DateTime $start; /** * The end time. * - * @var DateTime $end + * @var ?DateTime $end */ - protected $end; + protected ?DateTime $end; /** * AccessControlRule constructor. * - * @param string $accessType The type of the access. Use the constants defined in the AccessType class. - * @param DateTime $start The start time. - * @param DateTime $end The end time. + * @param string $accessType The type of the access. Use the constants defined in the AccessType class. + * @param DateTime|null $start The start time. + * @param DateTime|null $end The end time. * * @see AccessType for available types. */ - public function __construct($accessType, $start = null, $end = null) + public function __construct(string $accessType, ?DateTime $start = null, ?DateTime $end = null) { $this->accessType = $accessType; $this->start = $start; @@ -64,11 +64,8 @@ public function __construct($accessType, $start = null, $end = null) /** * Serializes to JSON - * - * @return array|mixed */ - #[\ReturnTypeWillChange] - public function jsonSerialize() + public function jsonSerialize(): array { return ArrayUtils::safeFilter( [ diff --git a/src/Asset/AccessControl/AccessType.php b/src/Asset/AccessControl/AccessType.php index 60ec6243..b4b9cd4e 100644 --- a/src/Asset/AccessControl/AccessType.php +++ b/src/Asset/AccessControl/AccessType.php @@ -17,6 +17,6 @@ */ class AccessType { - const ANONYMOUS = 'anonymous'; - const TOKEN = 'token'; + public const ANONYMOUS = 'anonymous'; + public const TOKEN = 'token'; } diff --git a/src/Asset/Analytics/Analytics.php b/src/Asset/Analytics/Analytics.php index e9890ded..0aad8312 100644 --- a/src/Asset/Analytics/Analytics.php +++ b/src/Asset/Analytics/Analytics.php @@ -21,27 +21,26 @@ */ class Analytics { - const QUERY_KEY = '_a'; - const ALGO_VERSION = 'B'; // The version of the algorithm - const SDK_CODE = 'A'; // Cloudinary PHP SDK + public const QUERY_KEY = '_a'; + protected const ALGO_VERSION = 'B'; // The version of the algorithm + protected const SDK_CODE = 'A'; // Cloudinary PHP SDK - protected static $product = 'A'; // Official SDK. Set to 'B' for integrations. - protected static $sdkCode = self::SDK_CODE; - protected static $sdkVersion = Cloudinary::VERSION; - protected static $techVersion = PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION; + protected static string $product = 'A'; // Official SDK. Set to 'B' for integrations. + protected static string $sdkCode = self::SDK_CODE; + protected static string $sdkVersion = Cloudinary::VERSION; + protected static string $techVersion = PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION; - const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - const BINARY_PAD_SIZE = 6; + protected const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + protected const BINARY_PAD_SIZE = 6; - protected static $charCodes = []; - protected static $signature; + protected static array $charCodes = []; + protected static ?string $signature; /** * Gets the SDK signature by encoding the SDK version and tech version. * - * @return string */ - public static function sdkAnalyticsSignature() + public static function sdkAnalyticsSignature(): string { if (empty(static::$signature)) { // Lazily create $signature @@ -64,11 +63,10 @@ public static function sdkAnalyticsSignature() * * @param string $product The product code to set. 'A' is for the official SDK. 'B' for integrations. * - * @return void * * @internal */ - public static function product($product) + public static function product(string $product): void { static::$product = $product; } @@ -80,11 +78,10 @@ public static function product($product) * * @param string $sdkCode The SDK code to set. * - * @return void * * @internal */ - public static function sdkCode($sdkCode) + public static function sdkCode(string $sdkCode): void { static::$sdkCode = $sdkCode; } @@ -96,11 +93,10 @@ public static function sdkCode($sdkCode) * * @param string $sdkVersion The SDK version to set (MAJOR.MINOR.PATCH), for example: "1.0.0". * - * @return void * * @internal */ - public static function sdkVersion($sdkVersion) + public static function sdkVersion(string $sdkVersion): void { static::$sdkVersion = $sdkVersion; } @@ -112,11 +108,10 @@ public static function sdkVersion($sdkVersion) * * @param string $techVersion The tech version to set (MAJOR.MINOR), for example: "1.0". * - * @return void * * @internal */ - public static function techVersion($techVersion) + public static function techVersion(string $techVersion): void { static::$techVersion = join('.', array_slice(explode('.', $techVersion), 0, 2)); } @@ -143,14 +138,13 @@ public static function techVersion($techVersion) * * @throws OutOfRangeException when version is larger than 43.21.26 */ - protected static function encodeVersion($version) + protected static function encodeVersion(string $version): string { $parts = explode('.', $version); $paddedParts = array_map( - static function ($part) { - return str_pad((int)$part, 2, "0", STR_PAD_LEFT); // this also zeros non-numeric values - }, + // this also zeros non-numeric values + static fn($part) => str_pad((int)$part, 2, '0', STR_PAD_LEFT), $parts ); @@ -162,9 +156,7 @@ static function ($part) { } $encodedChars = array_map( - static function ($part) { - return self::getKey($part); - }, + static fn($part) => self::getKey($part), str_split($paddedBinary, self::BINARY_PAD_SIZE) ); @@ -179,7 +171,7 @@ static function ($part) { * * @return array|mixed */ - protected static function getKey($binaryValue) + protected static function getKey(string $binaryValue): mixed { if (empty(self::$charCodes)) { // let's lazily populate $charCodes @@ -197,10 +189,9 @@ protected static function getKey($binaryValue) * @param int $integer The input. * @param int $padNum The num of padding chars. * - * @return string */ - protected static function intToPaddedBin($integer, $padNum) + protected static function intToPaddedBin(int $integer, int $padNum): string { - return str_pad(decbin($integer), $padNum, "0", STR_PAD_LEFT); + return str_pad(decbin($integer), $padNum, '0', STR_PAD_LEFT); } } diff --git a/src/Asset/AssetFinalizerTrait.php b/src/Asset/AssetFinalizerTrait.php index 1150ad08..069c2f9e 100644 --- a/src/Asset/AssetFinalizerTrait.php +++ b/src/Asset/AssetFinalizerTrait.php @@ -36,8 +36,6 @@ trait AssetFinalizerTrait * * @param null $subDomainPrefix * @param null $subDomainSuffix - * @param string $subDomain - * @param string $domain * * @return string Resulting host name * @internal @@ -45,9 +43,9 @@ trait AssetFinalizerTrait private static function buildHostName( $subDomainPrefix = null, $subDomainSuffix = null, - $subDomain = UrlConfig::DEFAULT_SUB_DOMAIN, - $domain = UrlConfig::DEFAULT_DOMAIN - ) { + ?string $subDomain = UrlConfig::DEFAULT_SUB_DOMAIN, + ?string $domain = UrlConfig::DEFAULT_DOMAIN + ): string { return implode( '.', array_filter( @@ -66,9 +64,9 @@ private static function buildHostName( * * @return int between 1 and 5 */ - private static function domainShard($source) + private static function domainShard(string $source): int { - return (((crc32($source) % 5) + 5) % 5 + 1); + return (crc32($source) % 5 + 5) % 5 + 1; } /** @@ -85,9 +83,8 @@ private static function domainShard($source) * If cdn_domain is true uses a[1-5].cname for http. * For https, uses the same naming scheme as 1 for shared distribution and as 2 for private distribution. * - * @return mixed */ - protected function finalizeDistribution() + protected function finalizeDistribution(): string { $useSharedHost = ! $this->urlConfig->privateCdn; @@ -150,10 +147,9 @@ protected function finalizeDistribution() * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#seo_friendly_media_asset_urls * - * @return mixed * @throws UnexpectedValueException */ - protected function finalizeAssetType() + protected function finalizeAssetType(): mixed { if (! empty($this->asset->suffix)) { $suffixSupportedDeliveryTypes = static::getSuffixSupportedDeliveryTypes(); @@ -185,9 +181,8 @@ protected function finalizeAssetType() /** * Finalizes asset source. * - * @return mixed */ - protected function finalizeSource() + protected function finalizeSource(): string { $source = $this->asset->publicId(true); @@ -210,15 +205,14 @@ protected function finalizeSource() /** * Finalizes version part of the asset URL. * - * @return mixed */ - protected function finalizeVersion() + protected function finalizeVersion(): ?string { $version = $this->asset->version; if (empty($version) && $this->urlConfig->forceVersion && ! empty($this->asset->location) - && ! preg_match("/^https?:\//", $this->asset->publicId()) + && ! preg_match('/^https?:\//', $this->asset->publicId()) && ! preg_match('/^v\d+/', $this->asset->publicId()) ) { $version = '1'; @@ -232,10 +226,9 @@ protected function finalizeVersion() * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#generating_delivery_url_signatures * - * @return string * @throws ConfigurationException */ - protected function finalizeSimpleSignature() + protected function finalizeSimpleSignature(): string { if (! $this->urlConfig->signUrl || $this->authToken->isEnabled()) { return ''; @@ -264,9 +257,8 @@ protected function finalizeSimpleSignature() /** * Check if passed signatureAlgorithm is supported otherwise return SHA1. * - * @return string */ - protected function getSignatureAlgorithm() + protected function getSignatureAlgorithm(): string { if ($this->urlConfig->longUrlSignature) { return Utils::ALGO_SHA256; @@ -284,9 +276,9 @@ protected function getSignatureAlgorithm() * * @param string $urlStr The URL to finalize. * - * @return string|UriInterface The resulting URL. + * @return UriInterface The resulting URL. */ - protected function finalizeUrl($urlStr) + protected function finalizeUrl(string $urlStr): UriInterface { $urlParts = parse_url($urlStr); @@ -303,7 +295,7 @@ protected function finalizeUrl($urlStr) * * @return array resulting URL parts */ - protected function finalizeUrlWithAuthToken($urlParts) + protected function finalizeUrlWithAuthToken(array $urlParts): array { if (! $this->urlConfig->signUrl || ! $this->authToken->isEnabled()) { return $urlParts; @@ -329,14 +321,14 @@ protected function finalizeUrlWithAuthToken($urlParts) * * @return array resulting URL */ - protected function finalizeUrlWithAnalytics($urlParts) + protected function finalizeUrlWithAnalytics(array $urlParts): array { if (! $this->urlConfig->analytics) { return $urlParts; } // Disable analytics for public IDs containing query params. - if (! empty($urlParts['query']) || StringUtils::contains($this->asset->publicId(), "?")) { + if (! empty($urlParts['query']) || StringUtils::contains($this->asset->publicId(), '?')) { return $urlParts; } diff --git a/src/Asset/AssetInterface.php b/src/Asset/AssetInterface.php index a00f2623..d1895c31 100644 --- a/src/Asset/AssetInterface.php +++ b/src/Asset/AssetInterface.php @@ -22,18 +22,16 @@ interface AssetInterface extends JsonSerializable * * @param string $string The asset string (URL). * - * @return mixed */ - public static function fromString($string); + public static function fromString(string $string): mixed; /** * Creates a new asset from the provided JSON. * - * @param string|array $json The asset json. Can be an array or a JSON string. + * @param array|string $json The asset json. Can be an array or a JSON string. * - * @return mixed */ - public static function fromJson($json); + public static function fromJson(array|string $json): mixed; /** * Creates a new asset from the provided source and an array of (legacy) parameters. @@ -41,27 +39,24 @@ public static function fromJson($json); * @param string $source The public ID of the asset. * @param array $params The asset parameters. * - * @return mixed */ - public static function fromParams($source, $params); + public static function fromParams(string $source, array $params): mixed; /** * Imports data from the provided string (URL). * * @param string $string The asset string (URL). * - * @return mixed */ - public function importString($string); + public function importString(string $string): mixed; /** * Imports data from the provided JSON. * - * @param string|array $json The asset json. Can be an array or a JSON string. + * @param array|string $json The asset json. Can be an array or a JSON string. * - * @return mixed */ - public function importJson($json); + public function importJson(array|string $json): mixed; /** * Serializes to string. @@ -73,8 +68,6 @@ public function __toString(); /** * Serializes to json. * - * @return mixed */ - #[\ReturnTypeWillChange] - public function jsonSerialize(); + public function jsonSerialize(): array; } diff --git a/src/Asset/AssetQualifiers.php b/src/Asset/AssetQualifiers.php index 40f64657..5e069869 100644 --- a/src/Asset/AssetQualifiers.php +++ b/src/Asset/AssetQualifiers.php @@ -22,30 +22,31 @@ abstract class AssetQualifiers * * @internal */ - const ASSET_KEYS = [ - 'api_secret', - 'auth_token', - 'cdn_subdomain', - 'cloud_name', - 'cname', - 'format', - 'long_url_signature', - 'private_cdn', - 'resource_type', - 'secure', - 'secure_cdn_subdomain', - 'secure_distribution', // deprecated, still consume for backwards compatibility - 'secure_cname', - 'shorten', - 'sign_url', - 'ssl_detected', - 'type', - 'url_suffix', - 'use_root_path', - 'version', - 'responsive', - 'responsive_width', - 'hidpi', - 'client_hints' - ]; + public const ASSET_KEYS + = [ + 'api_secret', + 'auth_token', + 'cdn_subdomain', + 'cloud_name', + 'cname', + 'format', + 'long_url_signature', + 'private_cdn', + 'resource_type', + 'secure', + 'secure_cdn_subdomain', + 'secure_distribution', // deprecated, still consume for backwards compatibility + 'secure_cname', + 'shorten', + 'sign_url', + 'ssl_detected', + 'type', + 'url_suffix', + 'use_root_path', + 'version', + 'responsive', + 'responsive_width', + 'hidpi', + 'client_hints', + ]; } diff --git a/src/Asset/AuthToken.php b/src/Asset/AuthToken.php index 537c047d..7115b82e 100644 --- a/src/Asset/AuthToken.php +++ b/src/Asset/AuthToken.php @@ -30,24 +30,24 @@ */ class AuthToken { - const UNSAFE = '/([ "#%&\'\/:;<=>?@\[\]^`{\|}~\\\])/'; + public const AUTH_TOKEN_NAME = '__cld_token__'; - const AUTH_TOKEN_NAME = '__cld_token__'; - const TOKEN_SEPARATOR = '~'; - const TOKEN_INNER_SEPARATOR = '='; - const TOKEN_ACL_SEPARATOR = '!'; + protected const UNSAFE = '/([ "#%&\'\/:;<=>?@\[\]^`{\|}~\\\])/'; + protected const TOKEN_SEPARATOR = '~'; + protected const TOKEN_INNER_SEPARATOR = '='; + protected const TOKEN_ACL_SEPARATOR = '!'; /** * @var AuthTokenConfig $config The configuration of the authentication token. */ - public $config; + public AuthTokenConfig $config; /** * AuthToken constructor. * - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. */ - public function __construct($configuration = null) + public function __construct(Configuration|array|string|null $configuration = null) { if ($configuration === null) { $configuration = Configuration::instance(); // get global instance @@ -59,11 +59,10 @@ public function __construct($configuration = null) /** * AuthToken named constructor. * - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return AuthToken */ - public static function fromJson($configuration = null) + public static function fromJson(Configuration|array|string|null $configuration = null): AuthToken { return new self($configuration); } @@ -72,9 +71,8 @@ public static function fromJson($configuration = null) /** * Indicates whether according to the current configuration, AuthToken is enabled or not * - * @return bool */ - public function isEnabled() + public function isEnabled(): bool { return ! empty($this->config->key); } @@ -84,9 +82,8 @@ public function isEnabled() * * @param mixed $configuration The configuration to set. * - * @return static */ - public function configuration($configuration) + public function configuration(mixed $configuration): static { $tempConfiguration = new Configuration($configuration, false); // TODO: improve performance here @@ -100,9 +97,8 @@ public function configuration($configuration) * * @param string $message The input to sign. * - * @return string */ - private function digest($message) + private function digest(string $message): string { return hash_hmac('sha256', $message, pack('H*', $this->config->key)); } @@ -117,13 +113,13 @@ private function digest($message) * string acl - the ACL for the token. * string url - the URL to authentication in case of a URL token. * - * @param null|string $path url path to sign. Ignored if acl is set. + * @param string|null $path url path to sign. Ignored if acl is set. * - * @return string The authorization token. + * @return ?string The authorization token. * * @throws UnexpectedValueException if neither expiration nor duration nor one of acl or url were provided. */ - public function generate($path = null) + public function generate(?string $path = null): ?string { if (! $this->isEnabled()) { return null; @@ -168,20 +164,20 @@ public function generate($path = null) * * @return array including start time and expiration */ - private function handleLifetime() + private function handleLifetime(): array { $start = $this->config->startTime; $expiration = $this->config->expiration; $duration = $this->config->duration; - if (! strcasecmp((string) $start, 'now')) { + if (! strcasecmp((string)$start, 'now')) { $start = Utils::unixTimeNow(); } elseif (is_numeric($start)) { $start = (int)$start; } if (! isset($expiration)) { if (isset($duration)) { - $expiration = (isset($start) ? $start : Utils::unixTimeNow()) + $duration; + $expiration = ($start ?? Utils::unixTimeNow()) + $duration; } else { throw new InvalidArgumentException('Must provide \'expiration\' or \'duration\'.'); } @@ -193,11 +189,11 @@ private function handleLifetime() /** * Escapes a url using lowercase hex characters * - * @param string $url The URL to escape + * @param ?string $url The URL to escape * * @return string|string[]|null escaped URL */ - private static function escapeToLower($url) + private static function escapeToLower(?string $url): array|string|null { if (empty($url)) { return $url; @@ -205,9 +201,7 @@ private static function escapeToLower($url) return preg_replace_callback( self::UNSAFE, - static function ($match) { - return '%' . bin2hex($match[1]); - }, + static fn($match) => '%' . bin2hex($match[1]), $url ); } diff --git a/src/Asset/BaseAsset.php b/src/Asset/BaseAsset.php index 4d0e95a4..bfd6ac64 100644 --- a/src/Asset/BaseAsset.php +++ b/src/Asset/BaseAsset.php @@ -10,6 +10,7 @@ namespace Cloudinary\Asset; +use BadMethodCallException; use Cloudinary\ArrayUtils; use Cloudinary\ClassUtils; use Cloudinary\Configuration\AssetConfigTrait; @@ -21,6 +22,7 @@ use Cloudinary\JsonUtils; use Cloudinary\Log\LoggerTrait; use Cloudinary\StringUtils; +use Psr\Http\Message\UriInterface; /** * Class BaseAsset @@ -32,7 +34,7 @@ abstract class BaseAsset implements AssetInterface /** * @var string $assetType The type of the asset. */ - protected static $assetType; + protected static string $assetType; use AssetDescriptorTrait; use AssetConfigTrait; @@ -46,12 +48,12 @@ abstract class BaseAsset implements AssetInterface /** * @var CloudConfig $cloud The configuration of the cloud. */ - public $cloud; + public CloudConfig $cloud; /** * @var UrlConfig $urlConfig The configuration of the URL. */ - public $urlConfig; + public UrlConfig $urlConfig; /** * @var AssetDescriptor $asset The asset descriptor. @@ -66,15 +68,15 @@ abstract class BaseAsset implements AssetInterface /** * @var array A list of the delivery types that support SEO suffix. */ - protected static $suffixSupportedDeliveryTypes = []; + protected static array $suffixSupportedDeliveryTypes = []; /** * BaseAsset constructor. * - * @param $source - * @param mixed $configuration + * @param mixed $source The asset source. + * @param mixed|null $configuration Configuration. */ - public function __construct($source, $configuration = null) + public function __construct(mixed $source, mixed $configuration = null) { if ($source instanceof $this) { // copy constructor $this->deepCopy($source); @@ -113,13 +115,11 @@ public function __construct($source, $configuration = null) /** * Internal method that returns the asset type of the current object. * - * @param self|string $class The instance of the object. - * - * @return string + * @param string|self $class The instance of the object. * * @internal */ - protected static function getAssetType($class) + protected static function getAssetType(BaseAsset|string $class): string { if (isset(static::$assetType)) { return static::$assetType; @@ -135,11 +135,10 @@ protected static function getAssetType($class) /** * Internal getter for a list of the delivery types that support SEO suffix. * - * @return array * * @internal */ - public static function getSuffixSupportedDeliveryTypes() + public static function getSuffixSupportedDeliveryTypes(): array { return static::$suffixSupportedDeliveryTypes; } @@ -151,7 +150,7 @@ public static function getSuffixSupportedDeliveryTypes() * * @internal */ - public function deepCopy($other) + public function deepCopy(BaseAsset $other): void { $this->cloud = clone $other->cloud; $this->urlConfig = clone $other->urlConfig; @@ -165,25 +164,24 @@ public function deepCopy($other) * Creates a new asset from the provided string (URL). * * @param string $string The asset string (URL). - * - * @return mixed */ - public static function fromString($string) + public static function fromString(string $string): static { //TODO: Parse URL and populate the asset + throw new BadMethodCallException('Not Implemented'); } /** * Creates a new asset from the provided JSON. * - * @param string|array $json The asset json. Can be an array or a JSON string. + * @param array|string $json The asset json. Can be an array or a JSON string. * - * @return mixed */ - public static function fromJson($json) + public static function fromJson(array|string $json): static { - //TODO: implement me + //TODO: Parse URL and populate the asset + throw new BadMethodCallException('Not Implemented'); } @@ -193,16 +191,15 @@ public static function fromJson($json) * @param string $source The public ID of the asset. * @param array $params The asset parameters. * - * @return mixed */ - public static function fromParams($source, $params = []) + public static function fromParams(string $source, array $params): static { ArrayUtils::setDefaultValue($params, 'resource_type', static::getAssetType(static::class)); $params['public_id'] = $source; $asset = AssetDescriptor::fromParams($source, $params); - $configuration = (new Configuration(Configuration::instance())); + $configuration = new Configuration(Configuration::instance()); # set v1 defaults if (! $configuration->url->isExplicitlySet('secure')) { @@ -222,29 +219,26 @@ public static function fromParams($source, $params = []) * Imports data from the provided string (URL). * * @param string $string The asset string (URL). - * - * @return mixed */ - public function importString($string) + public function importString(string $string): static { - //TODO: implement me + throw new BadMethodCallException('Import string is not implemented'); } /** * Imports data from the provided JSON. * - * @param string|array $json The asset json. Can be an array or a JSON string. + * @param array|string $json The asset json. Can be an array or a JSON string. * - * @return mixed */ - public function importJson($json) + public function importJson(array|string $json): static { try { $json = JsonUtils::decode($json); - $this->cloud = CloudConfig::fromJson($json, true); - $this->urlConfig = UrlConfig::fromJson($json, false); + $this->cloud = CloudConfig::fromJson($json); + $this->urlConfig = UrlConfig::fromJson($json); $this->asset = AssetDescriptor::fromJson($json); $this->authToken = AuthToken::fromJson($json); $this->logging = LoggingConfig::fromJson($json); @@ -269,9 +263,8 @@ public function importJson($json) * * @param array|Configuration $configuration The configuration source. * - * @return static */ - public function configuration($configuration) + public function configuration(Configuration|array $configuration): static { $tempConfiguration = new Configuration($configuration, true); // TODO: improve performance here $this->cloud = $tempConfiguration->cloud; @@ -286,9 +279,8 @@ public function configuration($configuration) * * @param array|Configuration $configuration The configuration source. * - * @return static */ - public function importConfiguration($configuration) + public function importConfiguration(Configuration|array $configuration): static { $this->cloud->importJson($configuration->cloud->jsonSerialize()); $this->urlConfig->importJson($configuration->url->jsonSerialize()); @@ -303,9 +295,8 @@ public function importConfiguration($configuration) * * @param bool $omitExtension Indicates whether to exclude the file extension. * - * @return string */ - public function getPublicId($omitExtension = false) + public function getPublicId(bool $omitExtension = false): string { return $this->asset->publicId($omitExtension); } @@ -315,9 +306,8 @@ public function getPublicId($omitExtension = false) * * @param string $publicId The public ID. * - * @return static */ - public function setPublicId($publicId) + public function setPublicId(string $publicId): static { $this->asset->setPublicId($publicId); @@ -327,11 +317,10 @@ public function setPublicId($publicId) /** * Internal pre-serialization helper. * - * @return array * * @internal */ - protected function prepareUrlParts() + protected function prepareUrlParts(): array { return [ 'distribution' => $this->finalizeDistribution(), @@ -345,10 +334,9 @@ protected function prepareUrlParts() /** * Serializes to URL string. * - * @return string * @throws ConfigurationException */ - public function toUrl() + public function toUrl(): UriInterface { return $this->finalizeUrl(ArrayUtils::implodeUrl($this->prepareUrlParts())); } @@ -374,10 +362,8 @@ public function __toString() * @param bool $includeEmptyKeys Whether to include empty keys. * @param bool $includeEmptySections Whether to include empty sections. * - * @return mixed */ - #[\ReturnTypeWillChange] - public function jsonSerialize($includeEmptyKeys = false, $includeEmptySections = false) + public function jsonSerialize(bool $includeEmptyKeys = false, bool $includeEmptySections = false): array { $json = $this->asset->jsonSerialize($includeEmptyKeys); @@ -402,7 +388,7 @@ public function jsonSerialize($includeEmptyKeys = false, $includeEmptySections = * * @internal */ - public function setAssetProperty($propertyName, $propertyValue) + public function setAssetProperty(string $propertyName, mixed $propertyValue): static { try { $this->asset->setAssetProperty($propertyName, $propertyValue); @@ -432,7 +418,7 @@ public function setAssetProperty($propertyName, $propertyValue) * * @internal */ - public function setCloudConfig($configKey, $configValue) + public function setCloudConfig(string $configKey, mixed $configValue): static { $this->cloud->setCloudConfig($configKey, $configValue); @@ -449,7 +435,7 @@ public function setCloudConfig($configKey, $configValue) * * @internal */ - public function setUrlConfig($configKey, $configValue) + public function setUrlConfig(string $configKey, mixed $configValue): static { $this->urlConfig->setUrlConfig($configKey, $configValue); diff --git a/src/Asset/BaseMediaAsset.php b/src/Asset/BaseMediaAsset.php index 854e8db7..128d9388 100644 --- a/src/Asset/BaseMediaAsset.php +++ b/src/Asset/BaseMediaAsset.php @@ -34,17 +34,17 @@ abstract class BaseMediaAsset extends BaseAsset implements CommonTransformationI use MediaAssetFinalizerTrait; /** - * @var ImageTransformation|VideoTransformation|Transformation $transformation The transformation. + * @var ImageTransformation|VideoTransformation|CommonTransformation $transformation The transformation. */ public $transformation; /** * BaseMediaAsset constructor. * - * @param $source + * @param mixed $source The source. * @param Configuration|string|array|null $configuration The Configuration source. */ - public function __construct($source, $configuration = null) + public function __construct(mixed $source, Configuration|string|array|null $configuration = null) { parent::__construct($source, $configuration); @@ -65,9 +65,8 @@ public function __construct($source, $configuration = null) * @param string $source The public ID of the asset. * @param array $params The media asset parameters. * - * @return static */ - public static function fromParams($source, $params = []) + public static function fromParams(string $source, array $params): static { $params = self::setFormatParameter($params); @@ -84,9 +83,8 @@ public static function fromParams($source, $params = []) * * @param CommonTransformation $transformation The transformation * - * @return static */ - public function setTransformation(CommonTransformation $transformation) + public function setTransformation(CommonTransformation $transformation): static { $this->transformation = $transformation; @@ -96,12 +94,15 @@ public function setTransformation(CommonTransformation $transformation) /** * Gets the asset transformation. * - * @return ImageTransformation|VideoTransformation|Transformation */ - abstract public function getTransformation(); + abstract public function getTransformation(): CommonTransformation; /** - * Adds (appends) a transformation in URL syntax to the current chain. A transformation is a set of instructions for adjusting images or videos—such as resizing, cropping, applying filters, adding overlays, or optimizing formats. For a detailed listing of all transformations, see the [Transformation Reference](https://cloudinary.com/documentation/transformation_reference) or the [PHP reference](https://cloudinary.com/documentation/sdks/php/php-transformation-builder/index.html). + * Adds (appends) a transformation in URL syntax to the current chain. A transformation is a set of instructions + * for adjusting images or videos—such as resizing, cropping, applying filters, adding overlays, or optimizing + * formats. For a detailed listing of all transformations, see the [Transformation + * Reference](https://cloudinary.com/documentation/transformation_reference) or the [PHP + * reference](https://cloudinary.com/documentation/sdks/php/php-transformation-builder/index.html). * * Appended transformation is nested. * @@ -109,7 +110,7 @@ abstract public function getTransformation(); * * @return $this */ - public function addTransformation($transformation) + public function addTransformation($transformation): static { $this->getTransformation()->addTransformation($transformation); @@ -122,9 +123,8 @@ public function addTransformation($transformation) * @param BaseAction|BaseQualifier|mixed $action The transformation action to add. * If BaseQualifier is provided, it is wrapped with action. * - * @return static */ - public function addAction($action) + public function addAction($action): static { $this->getTransformation()->addAction($action); @@ -138,11 +138,9 @@ public function addAction($action) * For remotely fetched assets sets the 'f_' transformation parameter. * * @param string $format The format to set. - * @param bool $useFetchFormat Whether to force fetch format behavior. - * - * @return static + * @param ?bool $useFetchFormat Whether to force fetch format behavior. */ - public function setFormat($format, $useFetchFormat = false) + public function setFormat(string $format, ?bool $useFetchFormat = false): static { if ($useFetchFormat || $this->asset->deliveryType == DeliveryType::FETCH) { $this->addTransformation(Delivery::format($format)); @@ -156,13 +154,14 @@ public function setFormat($format, $useFetchFormat = false) /** * Internal pre-serialization helper. * - * @param CommonTransformation|string $withTransformation Optional transformation that can be appended/used instead. - * @param bool $append Whether to append or use the provided transformation. + * @param mixed $withTransformation Optional transformation that can be appended/used instead. + * @param bool $append Whether to append or use the provided transformation. * - * @return array */ - protected function prepareUrlParts($withTransformation = null, $append = true) - { + protected function prepareUrlParts( + mixed $withTransformation = null, + bool $append = true + ): array { $urlParts = parent::prepareUrlParts(); $urlParts = ArrayUtils::insertAt( $urlParts, @@ -180,14 +179,17 @@ protected function prepareUrlParts($withTransformation = null, $append = true) /** * Serializes to the URL string. * - * @param CommonTransformation|string $withTransformation Optional transformation that can be appended/used instead. - * @param bool $append Whether to append or use the provided transformation. + * @param string|CommonTransformation|array|null $withTransformation Optional transformation that can be + * appended/used instead. + * @param bool $append Whether to append or use the provided + * transformation. * - * @return string|UriInterface * @throws ConfigurationException */ - public function toUrl($withTransformation = null, $append = true) - { + public function toUrl( + CommonTransformation|string|array|null $withTransformation = null, + bool $append = true + ): UriInterface { return $this->finalizeUrl( ArrayUtils::implodeUrl($this->prepareUrlParts($withTransformation, $append)) ); @@ -203,7 +205,7 @@ public function toUrl($withTransformation = null, $append = true) * * @return array the resulting parameters. */ - private static function setFormatParameter($params) + private static function setFormatParameter(array $params): array { if (ArrayUtils::get($params, DeliveryType::KEY) !== DeliveryType::FETCH && ! ArrayUtils::get($params, TagConfig::USE_FETCH_FORMAT, false) diff --git a/src/Asset/DeliveryTypeTrait.php b/src/Asset/DeliveryTypeTrait.php index 5bb695ad..ea70659e 100644 --- a/src/Asset/DeliveryTypeTrait.php +++ b/src/Asset/DeliveryTypeTrait.php @@ -21,11 +21,10 @@ trait DeliveryTypeTrait * Static builder for uploaded asset (actually a default constructor, put it here as an alias for consistency). * * @param string $publicId The public ID of the asset. - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function upload($publicId, $configuration = null) + public static function upload(string $publicId, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder($publicId, $configuration, DeliveryType::UPLOAD); } @@ -34,11 +33,10 @@ public static function upload($publicId, $configuration = null) * Static builder for private asset * * @param string $publicId The public ID of the asset. - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function private_($publicId, $configuration = null) + public static function private_(string $publicId, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder($publicId, $configuration, DeliveryType::PRIVATE_DELIVERY); } @@ -47,12 +45,13 @@ public static function private_($publicId, $configuration = null) * Static builder for authenticated asset * * @param string $publicId The public ID of the asset. - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function authenticated($publicId, $configuration = null) - { + public static function authenticated( + string $publicId, + Configuration|array|string|null $configuration = null + ): static { return self::deliveryTypeBuilder($publicId, $configuration, DeliveryType::AUTHENTICATED); } @@ -60,11 +59,10 @@ public static function authenticated($publicId, $configuration = null) * Static builder for fetch asset (from URL) * * @param string $url The URL of the remote asset. - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function fetch($url, $configuration = null) + public static function fetch(string $url, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder($url, $configuration, DeliveryType::FETCH); } @@ -73,11 +71,10 @@ public static function fetch($url, $configuration = null) * Static builder for facebook profile picture * * @param string $facebookId Facebook user ID - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function facebook($facebookId, $configuration = null) + public static function facebook(string $facebookId, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder($facebookId, $configuration, DeliveryType::FACEBOOK); } @@ -86,11 +83,10 @@ public static function facebook($facebookId, $configuration = null) * Static builder for gravatar profile picture * * @param string $email The email of the gravatar user - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function gravatar($email, $configuration = null) + public static function gravatar(string $email, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder(md5(strtolower(trim($email))), $configuration, DeliveryType::GRAVATAR); } @@ -99,11 +95,10 @@ public static function gravatar($email, $configuration = null) * Static builder for twitter profile picture by user ID * * @param string $userId the User ID - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function twitter($userId, $configuration = null) + public static function twitter(string $userId, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder($userId, $configuration, DeliveryType::TWITTER); } @@ -112,11 +107,10 @@ public static function twitter($userId, $configuration = null) * Static builder for twitter profile picture by username * * @param string $username The username. - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function twitterName($username, $configuration = null) + public static function twitterName(string $username, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder($username, $configuration, DeliveryType::TWITTER_NAME); } @@ -125,11 +119,10 @@ public static function twitterName($username, $configuration = null) * Static builder for YouTube video thumbnail * * @param string $videoId The video ID - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function youTube($videoId, $configuration = null) + public static function youTube(string $videoId, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder($videoId, $configuration, DeliveryType::YOUTUBE); } @@ -138,11 +131,10 @@ public static function youTube($videoId, $configuration = null) * Static builder for hulu video thumbnail * * @param string $videoId The video ID - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function hulu($videoId, $configuration = null) + public static function hulu(string $videoId, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder($videoId, $configuration, DeliveryType::HULU); } @@ -151,11 +143,10 @@ public static function hulu($videoId, $configuration = null) * Static builder for vimeo video thumbnail * * @param string $videoId The video ID - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function vimeo($videoId, $configuration = null) + public static function vimeo(string $videoId, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder($videoId, $configuration, DeliveryType::VIMEO); } @@ -164,11 +155,10 @@ public static function vimeo($videoId, $configuration = null) * Static builder for animoto video thumbnail * * @param string $videoId The video ID - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function animoto($videoId, $configuration = null) + public static function animoto(string $videoId, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder($videoId, $configuration, DeliveryType::ANIMOTO); } @@ -177,12 +167,13 @@ public static function animoto($videoId, $configuration = null) * Static builder for worldStarHipHop video thumbnail * * @param string $videoId The video ID - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function worldStarHipHop($videoId, $configuration = null) - { + public static function worldStarHipHop( + string $videoId, + Configuration|array|string|null $configuration = null + ): static { return self::deliveryTypeBuilder($videoId, $configuration, DeliveryType::WORLDSTARHIPHOP); } @@ -190,11 +181,10 @@ public static function worldStarHipHop($videoId, $configuration = null) * Static builder for dailyMotion video thumbnail * * @param string $videoId The video ID - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function dailyMotion($videoId, $configuration = null) + public static function dailyMotion(string $videoId, Configuration|array|string|null $configuration = null): static { return self::deliveryTypeBuilder($videoId, $configuration, DeliveryType::DAILYMOTION); } @@ -203,11 +193,10 @@ public static function dailyMotion($videoId, $configuration = null) * Static builder for sprite asset. * * @param string $tag The tag of the assets - * @param Configuration|string|array|null $configuration Configuration source. + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static */ - public static function sprite($tag, $configuration = null) + public static function sprite(string $tag, Configuration|array|string|null $configuration = null): static { $image = self::deliveryTypeBuilder($tag, $configuration, DeliveryType::SPRITE); @@ -219,16 +208,16 @@ public static function sprite($tag, $configuration = null) /** * The actual constructor. * - * @param $source - * @param Configuration|string|array|null $configuration Configuration source. - * @param $deliveryType + * @param array|string|Configuration|null $configuration Configuration source. * - * @return static * * @internal */ - protected static function deliveryTypeBuilder($source, $configuration, $deliveryType) - { + protected static function deliveryTypeBuilder( + $source, + Configuration|array|string|null $configuration, + $deliveryType + ): static { $asset = new static($source, $configuration); $asset->deliveryType($deliveryType); diff --git a/src/Asset/Descriptor/AssetDescriptor.php b/src/Asset/Descriptor/AssetDescriptor.php index dcba07fd..b048bb8f 100644 --- a/src/Asset/Descriptor/AssetDescriptor.php +++ b/src/Asset/Descriptor/AssetDescriptor.php @@ -17,7 +17,7 @@ /** * Class AssetDescriptor * - * @property string suffix SEO URL suffix + * @property string $suffix SEO URL suffix. * * @api */ @@ -28,34 +28,34 @@ class AssetDescriptor implements AssetInterface * Use the constants defined in the AssetType class. * @see AssetType */ - public $assetType = AssetType::IMAGE; + public string $assetType = AssetType::IMAGE; /** * @var string $deliveryType The delivery type of the asset, A.K.A type. * Use the constants defined in the DeliveryType class. * @see DeliveryType */ - public $deliveryType = DeliveryType::UPLOAD; // A.K.A type + public string $deliveryType = DeliveryType::UPLOAD; // A.K.A type /** - * @var int|string $version Asset version, typically set to unix timestamp. + * @var int|string|null $version Asset version, typically set to unix timestamp. */ - public $version; + public string|int|null $version = null; /** - * @var string $location Can be directory, URL(including path, excluding filename), etc. + * @var ?string $location Can be directory, URL(including path, excluding filename), etc. */ - public $location; + public ?string $location = null; /** - * @var string $filename Basename without extension. + * @var ?string $filename Basename without extension. */ - public $filename; + public ?string $filename = null; /** - * @var string $extension A.K.A format. + * @var ?string $extension A.K.A format. */ - public $extension; + public ?string $extension = null; /** - * @var string $suffix SEO URL suffix. + * @var ?string $suffix SEO URL suffix. */ - private $suffix; + private ?string $suffix = null; /** * AssetDescriptor constructor. @@ -63,7 +63,7 @@ class AssetDescriptor implements AssetInterface * @param string $publicId The public ID of the asset. * @param string $assetType The type of the asset. */ - public function __construct($publicId, $assetType = AssetType::IMAGE) + public function __construct(string $publicId, string $assetType = AssetType::IMAGE) { $this->setPublicId($publicId); $this->assetType = $assetType; @@ -74,15 +74,15 @@ public function __construct($publicId, $assetType = AssetType::IMAGE) * * @param string $name The name of the property. * - * @return mixed|null + * @return string|null */ - public function __get($name) + public function __get(string $name) { if ($name === 'suffix') { return $this->suffix; } - trigger_error('Undefined property: ' . static::class . '::$' . $name, E_USER_NOTICE); + trigger_error('Undefined property: ' . static::class . '::$' . $name); return null; } @@ -94,7 +94,7 @@ public function __get($name) * * @return bool */ - public function __isset($key) + public function __isset(string $key) { try { if (null === $this->__get($key)) { @@ -113,7 +113,7 @@ public function __isset($key) * @param string $name The class property name. * @param mixed $value The class property value. */ - public function __set($name, $value) + public function __set(string $name, mixed $value) { $this->setAssetProperty($name, $value); } @@ -125,7 +125,7 @@ public function __set($name, $value) * * @return $this */ - public function setPublicId($publicId) + public function setPublicId(string $publicId): static { list($this->location, $this->filename, $this->extension) = FileUtils::splitPathFilenameExtension($publicId); @@ -137,9 +137,8 @@ public function setPublicId($publicId) * * @param bool $noExtension When true, omits file extension. * - * @return string */ - public function publicId($noExtension = false) + public function publicId(bool $noExtension = false): string { return ArrayUtils::implodeFiltered( '.', @@ -153,11 +152,11 @@ public function publicId($noExtension = false) /** * Sets the URL SEO suffix of the asset. * - * @param string $suffix The SEO suffix. + * @param ?string $suffix The SEO suffix. * * @return $this */ - public function setSuffix($suffix) + public function setSuffix(?string $suffix): static { if (is_null($suffix)) { return $this; @@ -177,9 +176,8 @@ public function setSuffix($suffix) * * @param string $string The asset string (URL). * - * @return mixed */ - public static function fromString($string) + public static function fromString(string $string): mixed { throw new \BadMethodCallException('Not Implemented'); } @@ -187,11 +185,10 @@ public static function fromString($string) /** * Creates a new asset from the provided JSON. * - * @param string|array $json The asset json. Can be an array or a JSON string. + * @param array|string $json The asset json. Can be an array or a JSON string. * - * @return mixed */ - public static function fromJson($json) + public static function fromJson(array|string $json): AssetDescriptor { $new = new self(''); @@ -206,9 +203,8 @@ public static function fromJson($json) * @param string $source The public ID of the asset. * @param array $params The asset parameters. * - * @return mixed */ - public static function fromParams($source, $params = []) + public static function fromParams(string $source, array $params): AssetDescriptor { $assetJson = [ 'asset_type' => ArrayUtils::get($params, 'resource_type', AssetType::IMAGE), @@ -239,9 +235,8 @@ public static function fromParams($source, $params = []) * * @param string $string The asset string (URL). * - * @return mixed */ - public function importString($string) + public function importString(string $string): mixed { throw new \BadMethodCallException('Not Implemented'); } @@ -250,11 +245,10 @@ public function importString($string) /** * Imports data from the provided JSON. * - * @param string|array $json The asset json. Can be an array or a JSON string. + * @param array|string $json The asset json. Can be an array or a JSON string. * - * @return AssetDescriptor */ - public function importJson($json) + public function importJson(array|string $json): static { $json = JsonUtils::decode($json); @@ -292,10 +286,8 @@ public function __toString() * * @param bool $includeEmptyKeys Whether to include empty keys. * - * @return mixed */ - #[\ReturnTypeWillChange] - public function jsonSerialize($includeEmptyKeys = false) + public function jsonSerialize(bool $includeEmptyKeys = false): array { $dataArr = [ 'asset_type' => $this->assetType, @@ -324,7 +316,7 @@ public function jsonSerialize($includeEmptyKeys = false) * * @internal */ - public function setAssetProperty($propertyName, $propertyValue) + public function setAssetProperty(string $propertyName, mixed $propertyValue): static { /** @noinspection DegradedSwitchInspection */ switch ($propertyName) { diff --git a/src/Asset/Descriptor/AssetDescriptorTrait.php b/src/Asset/Descriptor/AssetDescriptorTrait.php index c276fb66..c2ba0ca7 100644 --- a/src/Asset/Descriptor/AssetDescriptorTrait.php +++ b/src/Asset/Descriptor/AssetDescriptorTrait.php @@ -26,7 +26,7 @@ trait AssetDescriptorTrait * * @see AssetType */ - public function assetType($assetType) + public function assetType(string $assetType): static { return $this->setAssetProperty('assetType', $assetType); } @@ -41,7 +41,7 @@ public function assetType($assetType) * * @see DeliveryType */ - public function deliveryType($deliveryType) + public function deliveryType(string $deliveryType): static { return $this->setAssetProperty('deliveryType', $deliveryType); } @@ -53,7 +53,7 @@ public function deliveryType($deliveryType) * * @return $this */ - public function version($version) + public function version(int|string $version): static { return $this->setAssetProperty('version', $version); } @@ -65,7 +65,7 @@ public function version($version) * * @return $this */ - public function location($location) + public function location(string $location): static { return $this->setAssetProperty('location', $location); } @@ -77,7 +77,7 @@ public function location($location) * * @return $this */ - public function filename($filename) + public function filename(string $filename): static { return $this->setAssetProperty('filename', $filename); } @@ -89,7 +89,7 @@ public function filename($filename) * * @return $this */ - public function extension($extension) + public function extension(string $extension): static { return $this->setAssetProperty('extension', $extension); } @@ -101,7 +101,7 @@ public function extension($extension) * * @return $this */ - public function suffix($suffix) + public function suffix(string $suffix): static { return $this->setAssetProperty('suffix', $suffix); } @@ -116,5 +116,5 @@ public function suffix($suffix) * * @internal */ - abstract public function setAssetProperty($propertyName, $propertyValue); + abstract public function setAssetProperty(string $propertyName, mixed $propertyValue): static; } diff --git a/src/Asset/Descriptor/AssetTransformation.php b/src/Asset/Descriptor/AssetTransformation.php index 160ad9d2..3a260a8c 100644 --- a/src/Asset/Descriptor/AssetTransformation.php +++ b/src/Asset/Descriptor/AssetTransformation.php @@ -33,25 +33,27 @@ class AssetTransformation implements ComponentInterface { use TransformationTrait; - const DELIMITER = '/'; # delimiter between transformation and extension + protected const DELIMITER = '/'; # delimiter between transformation and extension /** * @var Transformation $transformation The asset transformation. */ - protected $transformation; + protected mixed $transformation; /** * @var mixed|string|null The file extension, A.K.A format */ - protected $extension; + protected mixed $extension; /** * AssetTransformation constructor. * - * @param Transformation|array $transformation The asset transformation. - * @param string $extension The file extension. + * @param CommonTransformation|array|string|null $transformation The asset transformation. + * @param string|null $extension The file extension. */ - public function __construct($transformation = null, $extension = null) - { + public function __construct( + CommonTransformation|array|string|null $transformation = null, + ?string $extension = null + ) { $this->transformation = ClassUtils::forceInstance($transformation, Transformation::class); if ($extension === null && is_array($transformation)) { @@ -64,11 +66,11 @@ public function __construct($transformation = null, $extension = null) /** * Sets the file extension. * - * @param string $extension The file extension. + * @param ?string $extension The file extension. * * @return $this */ - public function extension($extension) + public function extension(?string $extension): static { $this->extension = $extension; @@ -80,9 +82,8 @@ public function extension($extension) * * @param string $string The asset string (URL). * - * @return mixed */ - public static function fromString($string) + public static function fromString(string $string): mixed { throw new BadMethodCallException('Not Implemented'); } @@ -91,11 +92,10 @@ public static function fromString($string) /** * Creates a new asset from the provided JSON. * - * @param string|array $json The asset json. Can be an array or a JSON string. + * @param array|string $json The asset json. Can be an array or a JSON string. * - * @return mixed */ - public static function fromJson($json) + public static function fromJson(array|string $json): AssetTransformation { $new = new self(''); @@ -112,7 +112,7 @@ public static function fromJson($json) * * @return static */ - public static function fromParams($params) + public static function fromParams(array $params): self { return new self(Transformation::fromParams($params), ArrayUtils::get($params, 'format')); } @@ -123,9 +123,8 @@ public static function fromParams($params) * * @param string $string The asset string (URL). * - * @return mixed */ - public function importString($string) + public function importString(string $string): mixed { throw new BadMethodCallException('Not Implemented'); } @@ -134,16 +133,15 @@ public function importString($string) /** * Imports data from the provided JSON. * - * @param string|array $json The asset json. Can be an array or a JSON string. + * @param array|string $json The asset json. Can be an array or a JSON string. * - * @return mixed */ - public function importJson($json) + public function importJson(array|string $json): static { $json = JsonUtils::decode($json); - if (! array_key_exists('asset_transformation', $json) || - ! array_key_exists('transformation', $json['asset_transformation']) + if (! array_key_exists('asset_transformation', $json) + || ! array_key_exists('transformation', $json['asset_transformation']) ) { throw new InvalidArgumentException('Invalid asset transformation JSON'); } @@ -157,15 +155,18 @@ public function importJson($json) } /** - * Adds (appends) a transformation in URL syntax to the current chain. A transformation is a set of instructions for adjusting images or videos—such as resizing, cropping, applying filters, adding overlays, or optimizing formats. For a detailed listing of all transformations, see the [Transformation Reference](https://cloudinary.com/documentation/transformation_reference) or the [PHP reference](https://cloudinary.com/documentation/sdks/php/php-transformation-builder/index.html). + * Adds (appends) a transformation in URL syntax to the current chain. A transformation is a set of instructions + * for adjusting images or videos—such as resizing, cropping, applying filters, adding overlays, or optimizing + * formats. For a detailed listing of all transformations, see the [Transformation + * Reference](https://cloudinary.com/documentation/transformation_reference) or the [PHP + * reference](https://cloudinary.com/documentation/sdks/php/php-transformation-builder/index.html). * * Appended transformation is nested. * * @param CommonTransformation $transformation The transformation to add. * - * @return static */ - public function addTransformation($transformation) + public function addTransformation(CommonTransformation $transformation): static { $this->transformation->addTransformation($transformation); @@ -178,9 +179,8 @@ public function addTransformation($transformation) * @param BaseAction|BaseQualifier|mixed $action The transformation action to add. * If BaseQualifier is provided, it is wrapped with action. * - * @return static */ - public function addAction($action) + public function addAction(mixed $action): static { $this->transformation->addAction($action); @@ -209,10 +209,8 @@ static function ($s) { * * @param bool $includeEmptyKeys Whether to include empty keys. * - * @return mixed */ - #[\ReturnTypeWillChange] - public function jsonSerialize($includeEmptyKeys = false) + public function jsonSerialize(bool $includeEmptyKeys = false): array { $dataArr = [ 'transformation' => $this->transformation ? (string)$this->transformation : null, // FIXME: serialization diff --git a/src/Asset/Descriptor/AssetType.php b/src/Asset/Descriptor/AssetType.php index 8fa74862..75b41ee7 100644 --- a/src/Asset/Descriptor/AssetType.php +++ b/src/Asset/Descriptor/AssetType.php @@ -17,11 +17,11 @@ */ abstract class AssetType { - const KEY = 'resource_type'; + public const KEY = 'resource_type'; - const IMAGE = 'image'; - const VIDEO = 'video'; - const RAW = 'raw'; - const AUTO = 'auto'; - const ALL = 'all'; + public const IMAGE = 'image'; + public const VIDEO = 'video'; + public const RAW = 'raw'; + public const AUTO = 'auto'; + public const ALL = 'all'; } diff --git a/src/Asset/Descriptor/DeliveryType.php b/src/Asset/Descriptor/DeliveryType.php index 39d7059a..3a97b718 100644 --- a/src/Asset/Descriptor/DeliveryType.php +++ b/src/Asset/Descriptor/DeliveryType.php @@ -17,52 +17,52 @@ */ class DeliveryType { - const KEY = 'type'; + public const KEY = 'type'; /** * Uploaded public asset. * * @const string UPLOAD */ - const UPLOAD = 'upload'; + public const UPLOAD = 'upload'; /** * Private asset. * * @const string PRIVATE_DELIVERY */ - const PRIVATE_DELIVERY = 'private'; + public const PRIVATE_DELIVERY = 'private'; /** * Public asset. * * @const string PUBLIC_DELIVERY */ - const PUBLIC_DELIVERY = 'public'; + public const PUBLIC_DELIVERY = 'public'; /** * Authenticated asset. * * @const string AUTHENTICATED */ - const AUTHENTICATED = 'authenticated'; + public const AUTHENTICATED = 'authenticated'; /** * Fetch remote asset from URL(ftp/http[s]/s3/gs). * * @const string FETCH */ - const FETCH = 'fetch'; - const SPRITE = 'sprite'; - const TEXT = 'text'; - const MULTI = 'multi'; - const FACEBOOK = 'facebook'; - const TWITTER = 'twitter'; - const TWITTER_NAME = 'twitter_name'; - const GRAVATAR = 'gravatar'; - const YOUTUBE = 'youtube'; - const HULU = 'hulu'; - const VIMEO = 'vimeo'; - const ANIMOTO = 'animoto'; - const WORLDSTARHIPHOP = 'worldstarhiphop'; - const DAILYMOTION = 'dailymotion'; + public const FETCH = 'fetch'; + public const SPRITE = 'sprite'; + public const TEXT = 'text'; + public const MULTI = 'multi'; + public const FACEBOOK = 'facebook'; + public const TWITTER = 'twitter'; + public const TWITTER_NAME = 'twitter_name'; + public const GRAVATAR = 'gravatar'; + public const YOUTUBE = 'youtube'; + public const HULU = 'hulu'; + public const VIMEO = 'vimeo'; + public const ANIMOTO = 'animoto'; + public const WORLDSTARHIPHOP = 'worldstarhiphop'; + public const DAILYMOTION = 'dailymotion'; } diff --git a/src/Asset/File.php b/src/Asset/File.php index 148de47b..f22827d8 100644 --- a/src/Asset/File.php +++ b/src/Asset/File.php @@ -20,12 +20,12 @@ class File extends BaseAsset /** * @var string $assetType The type of the asset. */ - protected static $assetType = 'raw'; + protected static string $assetType = 'raw'; /** * @var array A list of the delivery types that support SEO suffix. */ - protected static $suffixSupportedDeliveryTypes = [ + protected static array $suffixSupportedDeliveryTypes = [ AssetType::RAW => [DeliveryType::UPLOAD => 'files'], ]; } diff --git a/src/Asset/Image.php b/src/Asset/Image.php index 4f7d8975..e06e9368 100644 --- a/src/Asset/Image.php +++ b/src/Asset/Image.php @@ -24,12 +24,12 @@ class Image extends BaseMediaAsset implements ImageTransformationInterface { use ImageTransformationTrait; - const SHORTEN_ASSET_TYPE = 'iu'; + protected const SHORTEN_ASSET_TYPE = 'iu'; /** * @var array A list of the delivery types that support SEO suffix. */ - protected static $suffixSupportedDeliveryTypes = [ + protected static array $suffixSupportedDeliveryTypes = [ AssetType::IMAGE => [ DeliveryType::UPLOAD => 'images', DeliveryType::PRIVATE_DELIVERY => 'private_images', @@ -40,9 +40,8 @@ class Image extends BaseMediaAsset implements ImageTransformationInterface /** * Gets the transformation. * - * @return CommonTransformation */ - public function getTransformation() + public function getTransformation(): CommonTransformation { if (! isset($this->transformation)) { $this->transformation = new ImageTransformation(); @@ -54,9 +53,8 @@ public function getTransformation() /** * Finalizes the asset type. * - * @return mixed */ - protected function finalizeAssetType() + protected function finalizeAssetType(): ?string { return $this->finalizeShorten(parent::finalizeAssetType()); } diff --git a/src/Asset/Media.php b/src/Asset/Media.php index 76a8161e..a660d1ab 100644 --- a/src/Asset/Media.php +++ b/src/Asset/Media.php @@ -11,6 +11,7 @@ namespace Cloudinary\Asset; use Cloudinary\ArrayUtils; +use Cloudinary\Transformation\CommonTransformation; use Cloudinary\Transformation\Transformation; use Cloudinary\Transformation\TransformationTrait; @@ -26,13 +27,12 @@ class Media extends BaseMediaAsset /** * Internal method that returns the asset type of the current object. * - * @param self $class The instance of the object. + * @param string|BaseAsset $class The instance of the object. * - * @return string * * @internal */ - protected static function getAssetType($class) + protected static function getAssetType(BaseAsset|string $class): string { if (isset(static::$assetType)) { return static::$assetType; @@ -45,9 +45,8 @@ protected static function getAssetType($class) /** * Gets the transformation. * - * @return Transformation */ - public function getTransformation() + public function getTransformation(): Transformation|CommonTransformation { if (! isset($this->transformation)) { $this->transformation = new Transformation(); @@ -59,11 +58,10 @@ public function getTransformation() /** * Internal getter for a list of the delivery types that support SEO suffix. * - * @return array * * @internal */ - public static function getSuffixSupportedDeliveryTypes() + public static function getSuffixSupportedDeliveryTypes(): array { if (empty(self::$suffixSupportedDeliveryTypes)) { self::$suffixSupportedDeliveryTypes = ArrayUtils::mergeNonEmpty( @@ -79,9 +77,8 @@ public static function getSuffixSupportedDeliveryTypes() /** * Finalizes the asset type. * - * @return mixed */ - protected function finalizeAssetType() + protected function finalizeAssetType(): ?string { return $this->finalizeShorten(parent::finalizeAssetType()); } diff --git a/src/Asset/MediaAssetFinalizerTrait.php b/src/Asset/MediaAssetFinalizerTrait.php index a4b9acf8..5a90147a 100644 --- a/src/Asset/MediaAssetFinalizerTrait.php +++ b/src/Asset/MediaAssetFinalizerTrait.php @@ -28,13 +28,11 @@ trait MediaAssetFinalizerTrait /** * Finalizes asset transformation. * - * @param string|CommonTransformation $withTransformation Additional transformation - * @param bool $append Whether to append transformation or set in instead of the - * asset transformation + * @param mixed $withTransformation Additional transformation + * @param bool $append Whether to append transformation or set in instead of the asset transformation. * - * @return string */ - protected function finalizeTransformation($withTransformation = null, $append = true) + protected function finalizeTransformation(mixed $withTransformation = null, bool $append = true): string { if ($withTransformation === null && ! $this->urlConfig->responsiveWidth) { return (string)$this->transformation; @@ -58,10 +56,9 @@ protected function finalizeTransformation($withTransformation = null, $append = /** * Sign both transformation and asset parts of the URL. * - * @return string * @throws ConfigurationException */ - protected function finalizeSimpleSignature() + protected function finalizeSimpleSignature(): string { if (! $this->urlConfig->signUrl || $this->authToken->isEnabled()) { return ''; @@ -92,15 +89,16 @@ protected function finalizeSimpleSignature() * * Currently only image/upload is supported. * - * @param null|string $assetType The asset type to finalize. + * @param string|null $assetType The asset type to finalize. * * @return null|string The finalized asset type. */ - protected function finalizeShorten($assetType) + protected function finalizeShorten(?string $assetType): ?string { if ($this->urlConfig->shorten && $this->asset->deliveryType === DeliveryType::UPLOAD - && $this->asset->assetType === AssetType::IMAGE) { + && $this->asset->assetType === AssetType::IMAGE + ) { $assetType = Image::SHORTEN_ASSET_TYPE; } diff --git a/src/Asset/Moderation/ModerationStatus.php b/src/Asset/Moderation/ModerationStatus.php index 9377af96..3b5b6e33 100644 --- a/src/Asset/Moderation/ModerationStatus.php +++ b/src/Asset/Moderation/ModerationStatus.php @@ -24,26 +24,26 @@ abstract class ModerationStatus * * @var string */ - const KEY = 'moderation_status'; + public const KEY = 'moderation_status'; /** * Asset is pending moderation. * * @var string */ - const PENDING = 'pending'; + public const PENDING = 'pending'; /** * Asset has passed moderation and been approved. * * @var string */ - const APPROVED = 'approved'; + public const APPROVED = 'approved'; /** * Asset has passed moderation and been rejected. * * @var string */ - const REJECTED = 'rejected'; + public const REJECTED = 'rejected'; } diff --git a/src/Asset/Moderation/ModerationType.php b/src/Asset/Moderation/ModerationType.php index 809f95be..e4b130eb 100644 --- a/src/Asset/Moderation/ModerationType.php +++ b/src/Asset/Moderation/ModerationType.php @@ -24,7 +24,7 @@ abstract class ModerationType * * @var string */ - const KEY = 'moderation'; + public const KEY = 'moderation'; /** * Automatically moderate an uploaded image using the Amazon Rekognition AI Moderation add-on. @@ -37,7 +37,7 @@ abstract class ModerationType * * @see https://cloudinary.com/documentation/aws_rekognition_ai_moderation_addon */ - const AWS_REKOGNITION = 'aws_rek'; + public const AWS_REKOGNITION = 'aws_rek'; /** * Automatically moderate an uploaded asset of any type using the MetaDefender Anti-Malware Protection add-on. @@ -52,7 +52,7 @@ abstract class ModerationType * * @see https://cloudinary.com/documentation/metadefender_anti_malware_protection_addon */ - const METASCAN = 'metascan'; + public const METASCAN = 'metascan'; /** * Automatically moderate an uploaded image using the WebPurify Image Moderation add-on. @@ -65,7 +65,7 @@ abstract class ModerationType * * @see https://cloudinary.com/documentation/webpurify_image_moderation_addon */ - const WEBPURIFY = 'webpurify'; + public const WEBPURIFY = 'webpurify'; /** * Add an uploaded asset of any type to a queue of pending assets that can be moderated using the @@ -73,5 +73,5 @@ abstract class ModerationType * * @var string */ - const MANUAL = 'manual'; + public const MANUAL = 'manual'; } diff --git a/src/Asset/SearchAsset.php b/src/Asset/SearchAsset.php index 92a7835d..7dd5a40a 100644 --- a/src/Asset/SearchAsset.php +++ b/src/Asset/SearchAsset.php @@ -16,6 +16,7 @@ use Cloudinary\Exception\ConfigurationException; use Cloudinary\StringUtils; use Cloudinary\Utils; +use Psr\Http\Message\UriInterface; /** * Class SearchAsset @@ -30,14 +31,14 @@ class SearchAsset extends BaseAsset implements SearchQueryInterface /** * @var string $assetType The type of the asset. */ - protected static $assetType = 'search'; + protected static string $assetType = 'search'; /** * SearchAsset constructor. * - * @param mixed $configuration + * @param mixed|null $configuration */ - public function __construct($configuration = null) + public function __construct(mixed $configuration = null) { parent::__construct('', $configuration); } @@ -45,14 +46,14 @@ public function __construct($configuration = null) /** * Creates a signed Search URL that can be used on the client side. * - * @param int $ttl The time to live in seconds. - * @param string $nextCursor Starting position. + * @param int|null $ttl The time to live in seconds. + * @param string|null $nextCursor Starting position. * - * @return string The resulting search URL. + * @return UriInterface The resulting search URL. * * @throws ConfigurationException */ - public function toUrl($ttl = null, $nextCursor = null) + public function toUrl(?int $ttl = null, ?string $nextCursor = null): UriInterface { return $this->finalizeUrl(ArrayUtils::implodeUrl($this->prepareSearchUrlParts($ttl, $nextCursor))); } @@ -60,11 +61,14 @@ public function toUrl($ttl = null, $nextCursor = null) /** * Internal pre-serialization helper. * - * @return array + * @param int|null $ttl The time to live in seconds. + * @param string|null $nextCursor Starting position. + * + * @return array URL parts. * * @internal */ - protected function prepareSearchUrlParts($ttl, $nextCursor) + protected function prepareSearchUrlParts(?int $ttl = null, ?string $nextCursor = null): array { if ($ttl == null) { $ttl = $this->ttl; @@ -95,10 +99,11 @@ protected function prepareSearchUrlParts($ttl, $nextCursor) * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#generating_delivery_url_signatures * - * @return string - * @throws ConfigurationException + * @param string $toSign Payload to sign. + * + * @return string the signature. */ - private function finalizeSearchSignature($toSign) + private function finalizeSearchSignature(string $toSign): string { if (empty($this->cloud->apiSecret)) { throw new ConfigurationException('Must supply apiSecret'); diff --git a/src/Asset/SearchAssetTrait.php b/src/Asset/SearchAssetTrait.php index b4f91cc5..e26a5e0a 100644 --- a/src/Asset/SearchAssetTrait.php +++ b/src/Asset/SearchAssetTrait.php @@ -7,7 +7,7 @@ */ trait SearchAssetTrait { - private $ttl = 300; + private int $ttl = 300; /** * Sets the time to live of the search URL. @@ -18,7 +18,7 @@ trait SearchAssetTrait * * @api */ - public function ttl($ttl) + public function ttl(int $ttl): static { $this->ttl = $ttl; diff --git a/src/Asset/Video.php b/src/Asset/Video.php index 57ac64fb..5b7f6368 100644 --- a/src/Asset/Video.php +++ b/src/Asset/Video.php @@ -10,6 +10,7 @@ namespace Cloudinary\Asset; +use Cloudinary\Transformation\CommonTransformation; use Cloudinary\Transformation\VideoTransformation; use Cloudinary\Transformation\VideoTransformationInterface; use Cloudinary\Transformation\VideoTransformationTrait; @@ -26,16 +27,15 @@ class Video extends BaseMediaAsset implements VideoTransformationInterface /** * @var array A list of the delivery types that support SEO suffix. */ - protected static $suffixSupportedDeliveryTypes = [ + protected static array $suffixSupportedDeliveryTypes = [ AssetType::VIDEO => [DeliveryType::UPLOAD => 'videos'], ]; /** * Gets the transformation. * - * @return VideoTransformation */ - public function getTransformation() + public function getTransformation(): CommonTransformation|VideoTransformation { if (! isset($this->transformation)) { $this->transformation = new VideoTransformation(); diff --git a/src/Cloudinary.php b/src/Cloudinary.php index b8f32beb..c8391902 100644 --- a/src/Cloudinary.php +++ b/src/Cloudinary.php @@ -34,26 +34,26 @@ class Cloudinary * * @var string VERSION */ - const VERSION = '3.0.0'; + public const VERSION = '3.0.0'; /** * Defines the Cloudinary cloud details and other global configuration options. * * @var Configuration $configuration */ - public $configuration; + public Configuration $configuration; /** * @var TagBuilder $tagBuilder The TagBuilder object that includes builders for all tags. */ - protected $tagBuilder; + protected TagBuilder $tagBuilder; /** * Cloudinary constructor. * - * @param Configuration|string|array|null $config The Configuration source. + * @param array|string|Configuration|null $config The Configuration source. */ - public function __construct($config = null) + public function __construct(Configuration|array|string|null $config = null) { $this->configuration = new Configuration($config); $this->configuration->validate(); @@ -66,9 +66,8 @@ public function __construct($config = null) * * @param string $publicId The public ID of the image. * - * @return Image */ - public function image($publicId) + public function image(string $publicId): Image { return $this->createWithConfiguration($publicId, Image::class); } @@ -78,9 +77,8 @@ public function image($publicId) * * @param string|mixed $publicId The public ID of the video. * - * @return Video */ - public function video($publicId) + public function video(mixed $publicId): Video { return $this->createWithConfiguration($publicId, Video::class); } @@ -90,9 +88,8 @@ public function video($publicId) * * @param string|mixed $publicId The public ID of the file. * - * @return File */ - public function raw($publicId) + public function raw(mixed $publicId): File { return $this->createWithConfiguration($publicId, File::class); } @@ -100,9 +97,8 @@ public function raw($publicId) /** * Returns an instance of the TagBuilder class that includes builders for all tags. * - * @return TagBuilder */ - public function tag() + public function tag(): TagBuilder { return $this->tagBuilder; } @@ -112,9 +108,8 @@ public function tag() * * @param string|mixed $publicId The public ID of the image. * - * @return ImageTag */ - public function imageTag($publicId) + public function imageTag(mixed $publicId): ImageTag { return $this->createWithConfiguration($publicId, ImageTag::class); } @@ -125,9 +120,8 @@ public function imageTag($publicId) * @param string|mixed $publicId The public ID of the video. * @param array|null $sources The tag src definition. * - * @return VideoTag */ - public function videoTag($publicId, $sources = null) + public function videoTag(mixed $publicId, ?array $sources = null): VideoTag { $videoTag = ClassUtils::forceInstance($publicId, VideoTag::class, null, $sources, $this->configuration); $videoTag->importConfiguration($this->configuration); @@ -138,9 +132,8 @@ public function videoTag($publicId, $sources = null) /** * Creates a new AdminApi instance using the current configuration instance. * - * @return AdminApi */ - public function adminApi() + public function adminApi(): AdminApi { return new AdminApi($this->configuration); } @@ -148,9 +141,8 @@ public function adminApi() /** * Creates a new UploadApi instance using the current configuration instance. * - * @return UploadApi */ - public function uploadApi() + public function uploadApi(): UploadApi { return new UploadApi($this->configuration); } @@ -158,9 +150,8 @@ public function uploadApi() /** * Creates a new SearchApi instance using the current configuration instance. * - * @return SearchApi */ - public function searchApi() + public function searchApi(): SearchApi { return new SearchApi($this->configuration); } @@ -168,9 +159,8 @@ public function searchApi() /** * Creates a new SearchFoldersApi instance using the current configuration instance. * - * @return SearchFoldersApi */ - public function searchFoldersApi() + public function searchFoldersApi(): SearchFoldersApi { return new SearchFoldersApi($this->configuration); } @@ -182,11 +172,10 @@ public function searchFoldersApi() * @param string $className The class name of the object to create. * @param mixed ...$args Additional constructor arguments. * - * @return mixed * * @internal */ - protected function createWithConfiguration($publicId, $className, ...$args) + protected function createWithConfiguration(mixed $publicId, string $className, ...$args): mixed { $instance = ClassUtils::forceInstance($publicId, $className, null, $this->configuration, ...$args); // this covers the case when an instance of the asset is provided and the line above is a no op. diff --git a/src/Configuration/ApiConfig.php b/src/Configuration/ApiConfig.php index 95f4974a..44e318b9 100644 --- a/src/Configuration/ApiConfig.php +++ b/src/Configuration/ApiConfig.php @@ -25,51 +25,51 @@ */ class ApiConfig extends BaseConfigSection { - const CONFIG_NAME = 'api'; + public const CONFIG_NAME = 'api'; - const DEFAULT_UPLOAD_PREFIX = 'https://api.cloudinary.com'; - const DEFAULT_API_VERSION = '1.1'; - const DEFAULT_CHUNK_SIZE = 20000000; // bytes - const DEFAULT_TIMEOUT = 60; // seconds + public const DEFAULT_UPLOAD_PREFIX = 'https://api.cloudinary.com'; + public const DEFAULT_API_VERSION = '1.1'; + public const DEFAULT_CHUNK_SIZE = 20000000; // bytes + public const DEFAULT_TIMEOUT = 60; // seconds // Supported parameters - const UPLOAD_PREFIX = 'upload_prefix'; // FIXME: rename it! (it is actually prefix for all API calls) - const API_VERSION = 'api_version'; - const API_PROXY = 'api_proxy'; - const CONNECTION_TIMEOUT = 'connection_timeout'; - const TIMEOUT = 'timeout'; - const UPLOAD_TIMEOUT = 'upload_timeout'; - const CHUNK_SIZE = 'chunk_size'; - const CALLBACK_URL = 'callback_url'; + public const UPLOAD_PREFIX = 'upload_prefix'; // FIXME: rename it! (it is actually prefix for all API calls) + public const API_VERSION = 'api_version'; + public const API_PROXY = 'api_proxy'; + public const CONNECTION_TIMEOUT = 'connection_timeout'; + public const TIMEOUT = 'timeout'; + public const UPLOAD_TIMEOUT = 'upload_timeout'; + public const CHUNK_SIZE = 'chunk_size'; + public const CALLBACK_URL = 'callback_url'; /** * Used for changing default API host. * * @var string */ - protected $uploadPrefix; + protected string $uploadPrefix; /** * Used for changing default API version. * * @var string */ - protected $apiVersion; + protected string $apiVersion; /** * Optional. Specifies a proxy through which to make calls to the Cloudinary API. Format: http://hostname:port. * - * @var int $apiProxy + * @var ?string $apiProxy */ - public $apiProxy; + public ?string $apiProxy = null; /** * Describing the number of seconds to wait while trying to connect to a server. * Use 0 to wait indefinitely (the default behavior). * - * @var int|float + * @var int|float|null */ - public $connectionTimeout; + public int|float|null $connectionTimeout = null; /** * Describing the timeout of the request in seconds. @@ -77,7 +77,7 @@ class ApiConfig extends BaseConfigSection * * @var int|float */ - protected $timeout; + protected int|float $timeout; /** * Describing the timeout of the upload request in seconds. @@ -85,19 +85,19 @@ class ApiConfig extends BaseConfigSection * * @var int|float */ - protected $uploadTimeout; + protected int|float $uploadTimeout; /** * Size of a single chunk when uploading large files. * * @var int */ - protected $chunkSize; + protected int $chunkSize; /** * A public URL of your web application that has the cloudinary_cors.html file. * * @var string */ - public $callbackUrl; + public string $callbackUrl; } diff --git a/src/Configuration/AuthTokenConfig.php b/src/Configuration/AuthTokenConfig.php index 8f95577b..128df0fe 100644 --- a/src/Configuration/AuthTokenConfig.php +++ b/src/Configuration/AuthTokenConfig.php @@ -18,29 +18,29 @@ */ class AuthTokenConfig extends BaseConfigSection { - const CONFIG_NAME = 'auth_token'; + public const CONFIG_NAME = 'auth_token'; // Supported parameters - const KEY = 'key'; - const IP = 'ip'; - const ACL = 'acl'; - const START_TIME = 'start_time'; - const EXPIRATION = 'expiration'; - const DURATION = 'duration'; + public const KEY = 'key'; + public const IP = 'ip'; + public const ACL = 'acl'; + public const START_TIME = 'start_time'; + public const EXPIRATION = 'expiration'; + public const DURATION = 'duration'; /** * (Required) – the token must be signed with the encryption key received from Cloudinary. * - * @var string + * @var ?string */ - public $key; + public ?string $key = null; /** * (Optional) – only this IP address can access the resource. * - * @var string + * @var ?string */ - public $ip; + public ?string $ip = null; /** * (Optional) – an Access Control List for limiting the allowed URL path to a specified pattern (e.g., @@ -52,28 +52,28 @@ class AuthTokenConfig extends BaseConfigSection * that can be added to a number of different URLs that share a common transformation. Without this parameter, * the pattern defaults to the full URL path of the requested asset. * - * @var string|array + * @var string|array|null */ - public $acl; + public string|array|null $acl = null; /** * (Optional) – timestamp of the UNIX time when the URL becomes valid. Default value: the current time. * - * @var int + * @var ?int */ - public $startTime; + public ?int $startTime = null; /** * (Optional) – timestamp of the UNIX time when the URL expires. * - * @var int + * @var ?int */ - public $expiration; + public ?int $expiration = null; /** * (Optional) – the duration that the URL is valid in seconds (counted from start_time). * - * @var int + * @var ?int */ - public $duration; + public ?int $duration = null; } diff --git a/src/Configuration/BaseConfigSection.php b/src/Configuration/BaseConfigSection.php index 37e07e97..1c05f340 100644 --- a/src/Configuration/BaseConfigSection.php +++ b/src/Configuration/BaseConfigSection.php @@ -26,31 +26,29 @@ abstract class BaseConfigSection implements ConfigurableInterface /** * @var string Placeholder for configuration name, must de defined in each derived class. */ - const CONFIG_NAME = 'BASE_CONFIG'; + protected const CONFIG_NAME = 'BASE_CONFIG'; /** * @var array of configuration keys that contain sensitive data that should not be exported (for example api key). */ - protected static $sensitiveDataKeys = []; + protected static array $sensitiveDataKeys = []; /** * @var array of configuration key aliases (usually used for deprecated keys backwards compatibility). */ - protected static $aliases = []; + protected static array $aliases = []; /** * @var array of configuration keys that were explicitly set by user. Used to distinguish from default values. */ - protected $explicitlySetKeys = []; + protected array $explicitlySetKeys = []; /** * BaseConfig constructor. * - * @param $parameters - * @param bool $includeSensitive */ - public function __construct($parameters = null, $includeSensitive = true) + public function __construct($parameters = null, bool $includeSensitive = true) { $this->importParams($parameters, $includeSensitive); } @@ -64,10 +62,10 @@ public function __construct($parameters = null, $includeSensitive = true) * * @return mixed|null Property value. */ - public function __get($property) + public function __get(string $property) { if (! property_exists($this, $property)) { - trigger_error('Undefined property: ' . static::class . '::$' . $property, E_USER_NOTICE); + trigger_error('Undefined property: ' . static::class . '::$' . $property); return null; } @@ -79,7 +77,7 @@ public function __get($property) } } - return $this->{$property}; + return isset($this->{$property}) ? $this->{$property} : null; } /** @@ -88,7 +86,7 @@ public function __get($property) * @param string $name Property name. * @param mixed $value Property value. */ - public function __set($name, $value) + public function __set(string $name, mixed $value) { $this->$name = $value; @@ -105,7 +103,7 @@ public function __set($name, $value) * * @internal */ - public function setConfig($name, $value) + public function setConfig(string $name, mixed $value): static { $this->__set(StringUtils::snakeCaseToCamelCase($name), $value); @@ -117,11 +115,10 @@ public function setConfig($name, $value) * * @param string $name Property name. * - * @return bool * * @internal */ - public function isExplicitlySet($name) + public function isExplicitlySet(string $name): bool { return ArrayUtils::get($this->explicitlySetKeys, StringUtils::snakeCaseToCamelCase($name), false); } @@ -133,7 +130,7 @@ public function isExplicitlySet($name) * * @return bool */ - public function __isset($name) + public function __isset(string $name) { $getter = 'get' . ucfirst($name); if (method_exists($this, $getter)) { @@ -146,12 +143,11 @@ public function __isset($name) /** * Imports configuration properties from an array of parameters. * - * @param array $parameters Configuration section parameters. - * @param bool $includeSensitive Whether to include sensitive keys. + * @param ?array $parameters Configuration section parameters. + * @param bool $includeSensitive Whether to include sensitive keys. * - * @return static */ - public function importParams($parameters, $includeSensitive = true) + public function importParams(?array $parameters, bool $includeSensitive = true): static { $validKeys = self::importableKeys(self::exportableKeys($includeSensitive)); @@ -181,7 +177,7 @@ public function importParams($parameters, $includeSensitive = true) * * @throws InvalidArgumentException In case not all keys are set. */ - public function assertNotEmpty(array $keys) + public function assertNotEmpty(array $keys): void { foreach ($keys as $key) { if (empty($this->$key)) { @@ -197,7 +193,7 @@ public function assertNotEmpty(array $keys) * * @return array of keys */ - protected static function exportableKeys($includeSensitive = true) + protected static function exportableKeys(bool $includeSensitive = true): array { $blacklisted = [static::CONFIG_NAME]; if (! $includeSensitive) { @@ -206,9 +202,7 @@ protected static function exportableKeys($includeSensitive = true) return array_filter( ClassUtils::getConstants(static::class, $blacklisted), - static function ($key) { - return ! empty($key) && is_string($key); - } + static fn($key) => ! empty($key) && is_string($key) ); } @@ -219,7 +213,7 @@ static function ($key) { * * @return array of keys */ - protected static function importableKeys($exportableKeys) + protected static function importableKeys(array $exportableKeys): array { return array_merge($exportableKeys, array_keys(static::$aliases)); } @@ -228,12 +222,11 @@ protected static function importableKeys($exportableKeys) /** * Instantiates a new config section using json array as a source. * - * @param array $json Configuration source. - * @param bool $includeSensitive Whether to include sensitive keys. + * @param array|string $json Configuration source. * - * @return static brand new instance of the configuration section. + * @return static brand-new instance of the configuration section. */ - public static function fromJson($json, $includeSensitive = true) + public static function fromJson(array|string $json): static { $json = JsonUtils::decode($json); @@ -242,33 +235,30 @@ public static function fromJson($json, $includeSensitive = true) $json = $json[static::CONFIG_NAME]; } - return new static($json, $includeSensitive); + return new static($json); } /** * Instantiates a new config section using Cloudinary url as a source. * - * @param string $cloudinaryUrl The Cloudinary url. - * @param bool $includeSensitive Whether to include sensitive keys. + * @param string $cloudinaryUrl The Cloudinary url. * - * @return static */ - public static function fromCloudinaryUrl($cloudinaryUrl, $includeSensitive = true) + public static function fromCloudinaryUrl(string $cloudinaryUrl): static { $config = ConfigUtils::parseCloudinaryUrl($cloudinaryUrl); - return static::fromJson($config, $includeSensitive); + return static::fromJson($config); } /** * Imports configuration from a json string or an array as a source. * - * @param string|array $json Configuration json. + * @param array|string $json Configuration json. * - * @return static */ - public function importJson($json) + public function importJson(array|string $json): static { $json = JsonUtils::decode($json); @@ -286,9 +276,8 @@ public function importJson($json) * * @param string $cloudinaryUrl The Cloudinary url. * - * @return static */ - public function importCloudinaryUrl($cloudinaryUrl) + public function importCloudinaryUrl(string $cloudinaryUrl): static { $config = ConfigUtils::parseCloudinaryUrl($cloudinaryUrl); @@ -298,13 +287,12 @@ public function importCloudinaryUrl($cloudinaryUrl) /** * Serialises configuration section to a string representation. * - * @param array $excludedKeys The keys to exclude from export to string. + * @param array $excludedKeys The keys to exclude from export to string. * - * @return string */ - public function toString($excludedKeys = []) + public function toString(array $excludedKeys = []): string { - $sectionJson = $this->jsonSerialize(); + $sectionJson = $this->jsonSerialize(); if (empty($sectionJson)) { return ''; @@ -335,17 +323,19 @@ public function __toString() * * @param bool $includeEmptySections Whether to include sections without keys with non-empty values. * - * @return mixed data which can be serialized by json_encode. + * @return array data which can be serialized by json_encode. */ - #[\ReturnTypeWillChange] - public function jsonSerialize($includeSensitive = true, $includeEmptyKeys = false, $includeEmptySections = false) - { + public function jsonSerialize( + bool $includeSensitive = true, + bool $includeEmptyKeys = false, + bool $includeEmptySections = false + ): array { $keys = []; // set class properties foreach (self::exportableKeys($includeSensitive) as $key) { $propertyName = StringUtils::snakeCaseToCamelCase($key); if (property_exists(static::class, $propertyName) - && ($includeEmptyKeys || $this->$propertyName !== null) + && ($includeEmptyKeys || isset($this->$propertyName)) ) { $keys[$key] = $this->$propertyName; } diff --git a/src/Configuration/CloudConfig.php b/src/Configuration/CloudConfig.php index 300620a1..19b80698 100644 --- a/src/Configuration/CloudConfig.php +++ b/src/Configuration/CloudConfig.php @@ -18,7 +18,7 @@ * href="https://cloudinary.com/documentation/how_to_integrate_cloudinary#get_familiar_with_the_cloudinary_console" * target="_blank">Get account details from the Cloudinary Console. * - * @property string signatureAlgorithm By default, set to self::DEFAULT_SIGNATURE_ALGORITHM. + * @property ?string $signatureAlgorithm By default, set to self::DEFAULT_SIGNATURE_ALGORITHM. * * @api */ @@ -26,58 +26,48 @@ class CloudConfig extends BaseConfigSection { use CloudConfigTrait; - const CONFIG_NAME = 'cloud'; + public const CONFIG_NAME = 'cloud'; - const DEFAULT_SIGNATURE_ALGORITHM = Utils::ALGO_SHA1; + public const DEFAULT_SIGNATURE_ALGORITHM = Utils::ALGO_SHA1; // Supported parameters - const CLOUD_NAME = 'cloud_name'; - const API_KEY = 'api_key'; - const API_SECRET = 'api_secret'; - const OAUTH_TOKEN = 'oauth_token'; - const SIGNATURE_ALGORITHM = 'signature_algorithm'; + public const CLOUD_NAME = 'cloud_name'; + public const API_KEY = 'api_key'; + public const API_SECRET = 'api_secret'; + public const OAUTH_TOKEN = 'oauth_token'; + public const SIGNATURE_ALGORITHM = 'signature_algorithm'; /** * @var array of configuration keys that contain sensitive data that should not be exported (for example api key) */ - protected static $sensitiveDataKeys = [self::API_KEY, self::API_SECRET, self::OAUTH_TOKEN]; + protected static array $sensitiveDataKeys = [self::API_KEY, self::API_SECRET, self::OAUTH_TOKEN]; /** * Mandatory. The name of your Cloudinary cloud. Used to build the public URL for all your media assets. - * - * @var string */ - public $cloudName; + public ?string $cloudName = null; /** * Mandatory for server-side operations. Used together with the API secret to communicate with the Cloudinary API * and sign requests. - * - * @var string */ - public $apiKey; + public ?string $apiKey = null; /** * Mandatory for server-side operations. Used together with the API key to communicate with the Cloudinary API and * sign requests. - * - * @var string */ - public $apiSecret; + public ?string $apiSecret = null; /** * Optional for sever-side operations. Can be passed instead of passing API key and API secret. - * - * @var string */ - public $oauthToken; + public ?string $oauthToken = null; /** * Sets a signature algorithm (SHA1 by default). - * - * @var string */ - protected $signatureAlgorithm; + protected ?string $signatureAlgorithm = null; /** * Serialises configuration section to a string representation. @@ -100,7 +90,7 @@ public function __toString() * * @internal */ - public function setCloudConfig($configKey, $configValue) + public function setCloudConfig(string $configKey, mixed $configValue): static { return $this->setConfig($configKey, $configValue); } diff --git a/src/Configuration/CloudConfigTrait.php b/src/Configuration/CloudConfigTrait.php index 8eb7c09a..b24d0e8f 100644 --- a/src/Configuration/CloudConfigTrait.php +++ b/src/Configuration/CloudConfigTrait.php @@ -26,7 +26,7 @@ trait CloudConfigTrait * * @api */ - public function cloudName($cloudName) + public function cloudName(string $cloudName): static { return $this->setCloudConfig(CloudConfig::CLOUD_NAME, $cloudName); } @@ -34,13 +34,13 @@ public function cloudName($cloudName) /** * Sets the OAuth2.0 token. * - * @param string $oauthToken Used instead of API key and API secret + * @param ?string $oauthToken Used instead of API key and API secret * * @return $this * * @api */ - public function oauthToken($oauthToken) + public function oauthToken(?string $oauthToken): static { return $this->setCloudConfig(CloudConfig::OAUTH_TOKEN, $oauthToken); } @@ -54,7 +54,7 @@ public function oauthToken($oauthToken) * * @api */ - public function signatureAlgorithm($signatureAlgorithm) + public function signatureAlgorithm(string $signatureAlgorithm): static { return $this->setCloudConfig(CloudConfig::SIGNATURE_ALGORITHM, $signatureAlgorithm); } @@ -69,5 +69,5 @@ public function signatureAlgorithm($signatureAlgorithm) * * @internal */ - abstract public function setCloudConfig($configKey, $configValue); + abstract public function setCloudConfig(string $configKey, mixed $configValue): static; } diff --git a/src/Configuration/ConfigUtils.php b/src/Configuration/ConfigUtils.php index 552845b6..32e22126 100644 --- a/src/Configuration/ConfigUtils.php +++ b/src/Configuration/ConfigUtils.php @@ -14,6 +14,7 @@ use Cloudinary\StringUtils; use Cloudinary\Utils; use InvalidArgumentException; +use Psr\Http\Message\UriInterface; use UnexpectedValueException; /** @@ -23,29 +24,30 @@ */ class ConfigUtils { - const CLOUDINARY_URL_SCHEME = 'cloudinary'; + public const CLOUDINARY_URL_SCHEME = 'cloudinary'; /** * Checks whether the supplied string is a valid cloudinary url * - * @param string $cloudinaryUrl Cloudinary url candidate + * @param mixed $cloudinaryUrl Cloudinary url candidate * - * @return bool */ - public static function isCloudinaryUrl($cloudinaryUrl) + public static function isCloudinaryUrl(mixed $cloudinaryUrl): bool { - return Utils::tryParseUrl(self::normalizeCloudinaryUrl($cloudinaryUrl), [self::CLOUDINARY_URL_SCHEME]) ? true - : false; + if (! $cloudinaryUrl instanceof UriInterface && ! is_string($cloudinaryUrl)) { + return false; + } + + return (bool)Utils::tryParseUrl(self::normalizeCloudinaryUrl($cloudinaryUrl), [self::CLOUDINARY_URL_SCHEME]); } /** * Parses cloudinary url and fills in array that can be consumed by Configuration. * - * @param string $cloudinaryUrl The Cloudinary Url + * @param ?string $cloudinaryUrl The Cloudinary Url * - * @return array */ - public static function parseCloudinaryUrl($cloudinaryUrl) + public static function parseCloudinaryUrl(?string $cloudinaryUrl): array { if (empty($cloudinaryUrl)) { throw new InvalidArgumentException( @@ -80,7 +82,7 @@ public static function parseCloudinaryUrl($cloudinaryUrl) [ UrlConfig::CONFIG_NAME => [ UrlConfig::SECURE_CNAME => substr($uri->getPath(), 1), - UrlConfig::PRIVATE_CDN => $isPrivateCdn, + UrlConfig::PRIVATE_CDN => true, ], ] ); @@ -92,11 +94,10 @@ public static function parseCloudinaryUrl($cloudinaryUrl) /** * Tries to normalize the supplied cloudinary url string. * - * @param string $cloudinaryUrl Cloudinary url candidate. + * @param mixed $cloudinaryUrl Cloudinary url candidate. * - * @return string */ - public static function normalizeCloudinaryUrl($cloudinaryUrl) + public static function normalizeCloudinaryUrl(mixed $cloudinaryUrl): mixed { if (! is_string($cloudinaryUrl)) { return $cloudinaryUrl; @@ -112,7 +113,7 @@ public static function normalizeCloudinaryUrl($cloudinaryUrl) * * @return string Resulting Cloudinary Url */ - public static function buildCloudinaryUrl($config) + public static function buildCloudinaryUrl(array $config): string { $res = self::CLOUDINARY_URL_SCHEME . '://'; @@ -123,11 +124,9 @@ public static function buildCloudinaryUrl($config) $res .= ArrayUtils::get($config, [CloudConfig::CONFIG_NAME, CloudConfig::CLOUD_NAME]); - $res = ArrayUtils::implodeFiltered( + return ArrayUtils::implodeFiltered( '/', [$res, ArrayUtils::get($config, [UrlConfig::CONFIG_NAME, UrlConfig::SECURE_CNAME])] ); - - return $res; } } diff --git a/src/Configuration/ConfigurableInterface.php b/src/Configuration/ConfigurableInterface.php index 4f0871e6..05c53aca 100644 --- a/src/Configuration/ConfigurableInterface.php +++ b/src/Configuration/ConfigurableInterface.php @@ -20,45 +20,40 @@ interface ConfigurableInterface extends JsonSerializable /** * Creates a new instance using json string or an array as a source. * - * @param string|array $json Configuration json + * @param array|string $json Configuration json * - * @return static */ - public static function fromJson($json); + public static function fromJson(array|string $json): static; /** * Creates a new instance using Cloudinary url as a source. * * @param string $cloudinaryUrl The Cloudinary url. * - * @return static */ - public static function fromCloudinaryUrl($cloudinaryUrl); + public static function fromCloudinaryUrl(string $cloudinaryUrl): static; /** * Imports configuration from a json string or an array as a source. * - * @param string|array $json Configuration json + * @param array|string $json Configuration json * - * @return static */ - public function importJson($json); + public function importJson(array|string $json): static; /** * Imports configuration from a Cloudinary url as a source. * * @param string $cloudinaryUrl The Cloudinary url. * - * @return static */ - public function importCloudinaryUrl($cloudinaryUrl); + public function importCloudinaryUrl(string $cloudinaryUrl): static; /** * Serialises to a string representation. * - * @return string */ - public function toString(); + public function toString(): string; /** * Serialises to a string representation. @@ -74,8 +69,11 @@ public function __toString(); * @param bool $includeEmptyKeys Whether to include keys without values. * @param bool $includeEmptySections Whether to include sections without keys with non-empty values. * - * @return mixed data which can be serialized by json_encode. + * @return array data which can be serialized by json_encode. */ - #[\ReturnTypeWillChange] - public function jsonSerialize($includeSensitive = true, $includeEmptyKeys = false, $includeEmptySections = false); + public function jsonSerialize( + bool $includeSensitive = true, + bool $includeEmptyKeys = false, + bool $includeEmptySections = false + ): array; } diff --git a/src/Configuration/Configuration.php b/src/Configuration/Configuration.php index 8fbe14e4..56895c8f 100644 --- a/src/Configuration/Configuration.php +++ b/src/Configuration/Configuration.php @@ -13,7 +13,6 @@ use Cloudinary\Exception\ConfigurationException; use Cloudinary\JsonUtils; use Cloudinary\StringUtils; -use Psr\Http\Message\UriInterface; /** * Defines the available global configurations. @@ -22,21 +21,21 @@ */ class Configuration implements ConfigurableInterface { - const CLOUDINARY_URL_ENV_VAR = 'CLOUDINARY_URL'; + public const CLOUDINARY_URL_ENV_VAR = 'CLOUDINARY_URL'; /** * The version of the configuration scheme * * @var int */ - const VERSION = 1; + public const VERSION = 1; /** * Main configuration sections * * @var array */ - protected $sections + protected array $sections = [ CloudConfig::CONFIG_NAME, ApiConfig::CONFIG_NAME, @@ -50,71 +49,71 @@ class Configuration implements ConfigurableInterface /** * @var bool Indicates whether to include sensitive keys during serialisation to string/json. */ - protected $includeSensitive; + protected bool $includeSensitive; /** * @var static Singleton instance for the Configuration. */ - private static $instance; + private static Configuration $instance; /** * The configuration of the cloud. * * @var CloudConfig $cloud */ - public $cloud; + public CloudConfig $cloud; /** * The configuration of the API. * * @var ApiConfig $api */ - public $api; + public ApiConfig $api; /** * The configuration of the URL. * * @var UrlConfig $url */ - public $url; + public UrlConfig $url; /** * The configuration of tags. * * @var TagConfig $tag */ - public $tag; + public TagConfig $tag; /** * The configuration of the responsive breakpoints cache. * * @var ResponsiveBreakpointsConfig $responsiveBreakpoints */ - public $responsiveBreakpoints; + public ResponsiveBreakpointsConfig $responsiveBreakpoints; /** * The authentication token. * * @var AuthTokenConfig $authToken */ - public $authToken; + public AuthTokenConfig $authToken; /** * The configuration of the logging. * * @var LoggingConfig $logging */ - public $logging; + public LoggingConfig $logging; /** * Configuration constructor. * - * @param Configuration|string|array|null $config Configuration source. Can be Cloudinary url, json, + * @param array|string|Configuration|null $config Configuration source. Can be Cloudinary url, json, * array, another instance of the configuration. * @param bool $includeSensitive Indicates whether to include sensitive keys during * serialisation to string/json. */ - public function __construct($config = null, $includeSensitive = true) + public function __construct(Configuration|array|string|null $config = null, bool $includeSensitive = true) { $this->init($config, $includeSensitive); } @@ -124,12 +123,12 @@ public function __construct($config = null, $includeSensitive = true) * * Used for initialising and resetting config * - * @param Configuration|string|array|null $config Configuration source. Can be Cloudinary url, json, + * @param array|string|Configuration|null $config Configuration source. Can be Cloudinary url, json, * array, another instance of the configuration. * @param bool $includeSensitive Indicates whether to include sensitive keys during * serialisation to string/json. */ - public function init($config = null, $includeSensitive = true) + public function init(Configuration|array|string|null $config = null, bool $includeSensitive = true): void { $this->includeSensitive = $includeSensitive; @@ -141,7 +140,7 @@ public function init($config = null, $includeSensitive = true) /** * Initializes configuration sections. */ - protected function initSections() + protected function initSections(): void { $this->cloud = new CloudConfig(); $this->api = new ApiConfig(); @@ -155,10 +154,10 @@ protected function initSections() /** * Imports configuration. * - * @param Configuration|string|array|null $config Configuration source. Can be Cloudinary url, json, array, another + * @param array|string|Configuration|null $config Configuration source. Can be Cloudinary url, json, array, another * instance of the configuration. */ - public function import($config = null) + public function import(Configuration|array|string|null $config = null): void { if ($config === null) { if (! getenv(self::CLOUDINARY_URL_ENV_VAR)) { @@ -185,14 +184,13 @@ public function import($config = null) * * Instance can be optionally initialised with the provided $config (used only on the first call). * - * @param Configuration|string|array|null $config Configuration source. Can be Cloudinary url, json, + * @param array|string|Configuration|null $config Configuration source. Can be Cloudinary url, json, * array, another instance of the configuration. * - * @return Configuration */ - public static function instance($config = null) + public static function instance(Configuration|array|string|null $config = null): static { - if (self::$instance !== null) { + if (isset(self::$instance)) { return self::$instance; } @@ -204,11 +202,9 @@ public static function instance($config = null) /** * Creates Configuration using json string or array as a source. * - * @param string|array $json Configuration json. - * - * @return static + * @param array|string $json Configuration json. */ - public static function fromJson($json) + public static function fromJson(array|string $json): static { return new self($json); } @@ -218,9 +214,8 @@ public static function fromJson($json) * * @param array $params Configuration parameters. * - * @return static */ - public static function fromParams($params) + public static function fromParams(array $params): static { return new self($params); } @@ -229,22 +224,16 @@ public static function fromParams($params) * Creates Configuration using Cloudinary url as a source. * * @param string $cloudinaryUrl The Cloudinary url. - * - * @return static */ - public static function fromCloudinaryUrl($cloudinaryUrl) + public static function fromCloudinaryUrl(string $cloudinaryUrl): static { return new self($cloudinaryUrl); } /** * This is the actual constructor. - * - * @param $json - * - * @return Configuration */ - public function importJson($json) + public function importJson(array|string $json): static { $json = JsonUtils::decode($json); @@ -262,11 +251,10 @@ public function importJson($json) /** * Imports configuration from a cloudinary URL. * - * @param string|UriInterface $cloudinaryUrl The cloudinary URL. + * @param string $cloudinaryUrl The cloudinary URL. * - * @return Configuration */ - public function importCloudinaryUrl($cloudinaryUrl) + public function importCloudinaryUrl(string $cloudinaryUrl): static { $this->importJson(ConfigUtils::parseCloudinaryUrl($cloudinaryUrl)); @@ -278,16 +266,15 @@ public function importCloudinaryUrl($cloudinaryUrl) * * @param Configuration $otherConfig The source of the configuration. * - * @return Configuration */ - public function importConfig($otherConfig) + public function importConfig(Configuration $otherConfig): static { $this->importJson($otherConfig->jsonSerialize()); return $this; } - public function validate() + public function validate(): void { if (empty($this->cloud->cloudName)) { throw new ConfigurationException('Invalid configuration, please set up your environment'); @@ -299,19 +286,17 @@ public function validate() * * @return string Resulting Cloudinary url */ - public function toString() + public function toString(): string { $url = ConfigUtils::buildCloudinaryUrl($this->jsonSerialize()); $sections = []; foreach ($this->sections as $section) { $section = StringUtils::snakeCaseToCamelCase($section); - $sections [] = (string)($this->$section); + $sections [] = (string)$this->$section; } - $url = implode('?', array_filter([$url, implode('&', array_filter($sections))])); - - return $url; + return implode('?', array_filter([$url, implode('&', array_filter($sections))])); } /** @@ -331,11 +316,13 @@ public function __toString() * @param bool $includeEmptyKeys Whether to include keys without values. * @param bool $includeEmptySections Whether to include sections without keys with non-empty values. * - * @return mixed data which can be serialized by json_encode. + * @return array data which can be serialized by json_encode. */ - #[\ReturnTypeWillChange] - public function jsonSerialize($includeSensitive = true, $includeEmptyKeys = false, $includeEmptySections = false) - { + public function jsonSerialize( + bool $includeSensitive = true, + bool $includeEmptyKeys = false, + bool $includeEmptySections = false + ): array { $json = ['version' => self::VERSION]; foreach ($this->sections as $section) { diff --git a/src/Configuration/LoggingConfig.php b/src/Configuration/LoggingConfig.php index f902e4c1..e56e22ed 100644 --- a/src/Configuration/LoggingConfig.php +++ b/src/Configuration/LoggingConfig.php @@ -13,29 +13,29 @@ /** * Defines the global configuration for logging messages when using the SDK. * - * @property array $file Settings for logging messages to a file. - * @property array $errorLog Settings for logging messages to PHP error_log() handler. - * @property array $test Settings for logging messages for testing purposes. - * @property string $level Settings for default logging level. - * @property bool $enabled Settings for globally disabling all logging. + * @property ?array $file Settings for logging messages to a file. + * @property array|bool|null $errorLog Settings for logging messages to PHP error_log() handler. + * @property ?array $test Settings for logging messages for testing purposes. + * @property ?string $level Settings for default logging level. + * @property ?bool $enabled Settings for globally disabling all logging. * * @api */ class LoggingConfig extends BaseConfigSection { - const CONFIG_NAME = 'logging'; + public const CONFIG_NAME = 'logging'; // Supported parameters - const FILE = 'file'; - const ERROR_LOG = 'error_log'; - const TEST = 'test'; - const LEVEL = 'level'; - const ENABLED = 'enabled'; + public const FILE = 'file'; + public const ERROR_LOG = 'error_log'; + public const TEST = 'test'; + public const LEVEL = 'level'; + public const ENABLED = 'enabled'; // Public properties available to users, should FULLY correspond constant values! - public $file; - public $errorLog; - public $test; - public $level; - public $enabled; + public ?array $file = null; + public array|bool|null $errorLog = null; + public ?array $test = null; + public ?string $level = null; + public ?bool $enabled = null; } diff --git a/src/Configuration/Provisioning/ProvisioningAccountConfig.php b/src/Configuration/Provisioning/ProvisioningAccountConfig.php index c42c50a9..c75b067f 100644 --- a/src/Configuration/Provisioning/ProvisioningAccountConfig.php +++ b/src/Configuration/Provisioning/ProvisioningAccountConfig.php @@ -19,31 +19,31 @@ */ class ProvisioningAccountConfig extends BaseConfigSection { - const CONFIG_NAME = 'provisioning_account'; + public const CONFIG_NAME = 'provisioning_account'; // Supported parameters - const ACCOUNT_ID = 'account_id'; - const PROVISIONING_API_KEY = 'provisioning_api_key'; - const PROVISIONING_API_SECRET = 'provisioning_api_secret'; + public const ACCOUNT_ID = 'account_id'; + public const PROVISIONING_API_KEY = 'provisioning_api_key'; + public const PROVISIONING_API_SECRET = 'provisioning_api_secret'; /** * The account id of your Cloudinary account. Mandatory for provisioning API operations. * * @var string */ - public $accountId; + public string $accountId; /** * The provisioning API key. Mandatory for provisioning API operations. * * @var string */ - public $provisioningApiKey; + public string $provisioningApiKey; /** * The provisioning API secret. Mandatory for provisioning API operations. * * @var string */ - public $provisioningApiSecret; + public string $provisioningApiSecret; } diff --git a/src/Configuration/Provisioning/ProvisioningConfigUtils.php b/src/Configuration/Provisioning/ProvisioningConfigUtils.php index 4fdacb65..826a8b17 100644 --- a/src/Configuration/Provisioning/ProvisioningConfigUtils.php +++ b/src/Configuration/Provisioning/ProvisioningConfigUtils.php @@ -13,6 +13,7 @@ use Cloudinary\ArrayUtils; use Cloudinary\Utils; use InvalidArgumentException; +use Psr\Http\Message\UriInterface; use UnexpectedValueException; /** @@ -22,18 +23,21 @@ */ class ProvisioningConfigUtils { - const ACCOUNT_URL_SCHEME = 'account'; + public const ACCOUNT_URL_SCHEME = 'account'; /** * Checks whether the supplied string is a valid account url * - * @param string $accountUrl Account url candidate + * @param mixed $accountUrl Account url candidate * - * @return bool */ - public static function isAccountUrl($accountUrl) + public static function isAccountUrl(mixed $accountUrl): bool { - return Utils::tryParseUrl($accountUrl, [self::ACCOUNT_URL_SCHEME]) ? true : false; + if (! $accountUrl instanceof UriInterface && ! is_string($accountUrl)) { + return false; + } + + return (bool)Utils::tryParseUrl($accountUrl, [self::ACCOUNT_URL_SCHEME]); } /** @@ -41,9 +45,8 @@ public static function isAccountUrl($accountUrl) * * @param string $accountUrl The Cloudinary Account Url * - * @return array */ - public static function parseAccountUrl($accountUrl) + public static function parseAccountUrl(string $accountUrl): array { if (empty($accountUrl)) { throw new InvalidArgumentException( diff --git a/src/Configuration/Provisioning/ProvisioningConfiguration.php b/src/Configuration/Provisioning/ProvisioningConfiguration.php index 11a62229..2c0df216 100644 --- a/src/Configuration/Provisioning/ProvisioningConfiguration.php +++ b/src/Configuration/Provisioning/ProvisioningConfiguration.php @@ -26,43 +26,37 @@ */ class ProvisioningConfiguration { - const CLOUDINARY_ACCOUNT_URL_ENV_VAR = 'CLOUDINARY_ACCOUNT_URL'; + public const CLOUDINARY_ACCOUNT_URL_ENV_VAR = 'CLOUDINARY_ACCOUNT_URL'; /** - * @var static Singleton instance for the ConfigurationAccount + * @var ?static Singleton instance for the ConfigurationAccount */ - private static $instance; + private static ?ProvisioningConfiguration $instance = null; - /** - * @var ProvisioningAccountConfig $provisioningAccount - */ - public $provisioningAccount; + public ?ProvisioningAccountConfig $provisioningAccount = null; /** * @var ApiConfig $api The configuration of the API. */ - public $api; + public ApiConfig $api; - /** - * @var LoggingConfig $logging - */ - public $logging; + public LoggingConfig $logging; /** * @var array Main configuration sections */ - protected $sections = [ - ProvisioningAccountConfig::CONFIG_NAME, - ApiConfig::CONFIG_NAME, - LoggingConfig::CONFIG_NAME, - ]; + protected array $sections + = [ + ProvisioningAccountConfig::CONFIG_NAME, + ApiConfig::CONFIG_NAME, + LoggingConfig::CONFIG_NAME, + ]; /** * ConfigurationAccount constructor. * - * @param ProvisioningConfiguration|string|array|null $config */ - public function __construct($config = null) + public function __construct(array|string|ProvisioningConfiguration|null $config = null) { $this->init($config); } @@ -70,9 +64,8 @@ public function __construct($config = null) /** * ConfigurationAccount initializer * - * @param ProvisioningConfiguration|string|array|null $config */ - public function init($config = null) + public function init(array|string|ProvisioningConfiguration|null $config = null): void { $this->initSections(); @@ -96,9 +89,8 @@ public function init($config = null) * * @param string|UriInterface $accountUrl The account URL. * - * @return ProvisioningConfiguration */ - public function importAccountUrl($accountUrl) + public function importAccountUrl(UriInterface|string $accountUrl): static { $this->importJson(ProvisioningConfigUtils::parseAccountUrl($accountUrl)); @@ -108,11 +100,9 @@ public function importAccountUrl($accountUrl) /** * This is the actual constructor. * - * @param $json * - * @return ProvisioningConfiguration */ - public function importJson($json) + public function importJson($json): static { $json = JsonUtils::decode($json); @@ -128,9 +118,8 @@ public function importJson($json) * * @param ProvisioningConfiguration $otherConfig The source of the configuration. * - * @return ProvisioningConfiguration */ - public function importConfig($otherConfig) + public function importConfig(ProvisioningConfiguration $otherConfig): static { $this->importJson($otherConfig->jsonSerialize()); @@ -144,10 +133,13 @@ public function importConfig($otherConfig) * @param bool $includeEmptyKeys Whether to include keys without values. * @param bool $includeEmptySections Whether to include sections without keys with non-empty values. * - * @return mixed data which can be serialized by json_encode. + * @return array data which can be serialized by json_encode. */ - public function jsonSerialize($includeSensitive = true, $includeEmptyKeys = false, $includeEmptySections = false) - { + public function jsonSerialize( + bool $includeSensitive = true, + bool $includeEmptyKeys = false, + bool $includeEmptySections = false + ): array { $json = []; foreach ($this->sections as $section) { @@ -167,12 +159,11 @@ public function jsonSerialize($includeSensitive = true, $includeEmptyKeys = fals * * Instance can be optionally initialized with the provided $config (used only on the first call) * - * @param ProvisioningConfiguration|string|array|null $config * - * @return ProvisioningConfiguration + * @return ProvisioningConfiguration Provisioning Configuration */ - public static function instance($config = null) - { + public static function instance(array|string|ProvisioningConfiguration|null $config = null + ): ProvisioningConfiguration { if (self::$instance !== null) { return self::$instance; } @@ -185,7 +176,7 @@ public static function instance($config = null) /** * Initializes configuration sections. */ - protected function initSections() + protected function initSections(): void { $this->provisioningAccount = new ProvisioningAccountConfig(); $this->api = new ApiConfig(); diff --git a/src/Configuration/ResponsiveBreakpointsConfig.php b/src/Configuration/ResponsiveBreakpointsConfig.php index 58054b4c..b3f2c3c0 100644 --- a/src/Configuration/ResponsiveBreakpointsConfig.php +++ b/src/Configuration/ResponsiveBreakpointsConfig.php @@ -15,62 +15,62 @@ * **Learn more**: * Responsive breakpoints * - * @property int $minWidth The minimum width needed for the image. Default: 375. - * @property int $maxWidth The maximum width needed for the image. Default 3840. - * @property int $maxImages The maximal number of breakpoints. + * @property ?int $minWidth The minimum width needed for the image. Default: 375. + * @property ?int $maxWidth The maximum width needed for the image. Default 3840. + * @property ?int $maxImages The maximal number of breakpoints. * * @api */ class ResponsiveBreakpointsConfig extends BaseConfigSection { - const CONFIG_NAME = 'responsive_breakpoints'; + public const CONFIG_NAME = 'responsive_breakpoints'; - const DEFAULT_MIN_WIDTH = 375; - const DEFAULT_MAX_WIDTH = 3840; - const DEFAULT_MAX_IMAGES = 5; + public const DEFAULT_MIN_WIDTH = 375; + public const DEFAULT_MAX_WIDTH = 3840; + public const DEFAULT_MAX_IMAGES = 5; // Supported parameters - const BREAKPOINTS = 'breakpoints'; + public const BREAKPOINTS = 'breakpoints'; - const MIN_WIDTH = 'min_width'; - const MAX_WIDTH = 'max_width'; - const MAX_IMAGES = 'max_images'; + public const MIN_WIDTH = 'min_width'; + public const MAX_WIDTH = 'max_width'; + public const MAX_IMAGES = 'max_images'; - const AUTO_OPTIMAL_BREAKPOINTS = 'auto_optimal_breakpoints'; + public const AUTO_OPTIMAL_BREAKPOINTS = 'auto_optimal_breakpoints'; /** * An array of static breakpoints to use (overrides Cloudinary-optimized breakpoints). * - * @var array + * @var array|null */ - public $breakpoints; + public ?array $breakpoints = null; /** * The minimum width needed for the image. Default: 375. * - * @var int + * @var ?int */ - protected $minWidth; + protected ?int $minWidth; /** * The maximum width needed for the image. If specifying a width bigger than the original image, * the width of the original image is used instead. Default: 3840. * - * @var int + * @var ?int */ - protected $maxWidth; + protected ?int $maxWidth; /** * The number of breakpoints. Default: 5. * - * @var int + * @var ?int */ - protected $maxImages; + protected ?int $maxImages; /** * Defines whether to use auto optimal breakpoints. * - * @var bool + * @var ?bool */ - public $autoOptimalBreakpoints; + public ?bool $autoOptimalBreakpoints = null; } diff --git a/src/Configuration/TagConfig.php b/src/Configuration/TagConfig.php index 315050c1..8d3fb6aa 100644 --- a/src/Configuration/TagConfig.php +++ b/src/Configuration/TagConfig.php @@ -28,50 +28,50 @@ class TagConfig extends BaseConfigSection { use TagConfigTrait; - const CONFIG_NAME = 'tag'; + public const CONFIG_NAME = 'tag'; - const DEFAULT_VIDEO_POSTER_FORMAT = Format::JPG; - const DEFAULT_QUOTES_TYPE = BaseTag::DOUBLE_QUOTES; - const DEFAULT_CONTENT_DELIMITER = "\n"; - const DEFAULT_RELATIVE_WIDTH = 1.0; + public const DEFAULT_VIDEO_POSTER_FORMAT = Format::JPG; + public const DEFAULT_QUOTES_TYPE = BaseTag::DOUBLE_QUOTES; + public const DEFAULT_CONTENT_DELIMITER = "\n"; + public const DEFAULT_RELATIVE_WIDTH = 1.0; // Supported parameters - const RESPONSIVE = 'responsive'; - const RESPONSIVE_CLASS = 'responsive_class'; - const RESPONSIVE_PLACEHOLDER = 'responsive_placeholder'; - const SIZES = 'sizes'; - const RELATIVE_WIDTH = 'relative_width'; - const HIDPI = 'hidpi'; - const CLIENT_HINTS = 'client_hints'; - const UNSIGNED_UPLOAD = 'unsigned_upload'; - const VIDEO_POSTER_FORMAT = 'video_poster_format'; - const USE_FETCH_FORMAT = 'use_fetch_format'; - const QUOTES_TYPE = 'quotes_type'; - const VOID_CLOSING_SLASH = 'void_closing_slash'; - const SORT_ATTRIBUTES = 'sort_attributes'; - const PREPEND_SRC_ATTRIBUTE = 'prepend_src_attribute'; - const CONTENT_DELIMITER = 'content_delimiter'; + public const RESPONSIVE = 'responsive'; + public const RESPONSIVE_CLASS = 'responsive_class'; + public const RESPONSIVE_PLACEHOLDER = 'responsive_placeholder'; + public const SIZES = 'sizes'; + public const RELATIVE_WIDTH = 'relative_width'; + public const HIDPI = 'hidpi'; + public const CLIENT_HINTS = 'client_hints'; + public const UNSIGNED_UPLOAD = 'unsigned_upload'; + public const VIDEO_POSTER_FORMAT = 'video_poster_format'; + public const USE_FETCH_FORMAT = 'use_fetch_format'; + public const QUOTES_TYPE = 'quotes_type'; + public const VOID_CLOSING_SLASH = 'void_closing_slash'; + public const SORT_ATTRIBUTES = 'sort_attributes'; + public const PREPEND_SRC_ATTRIBUTE = 'prepend_src_attribute'; + public const CONTENT_DELIMITER = 'content_delimiter'; /** * Whether to generate responsive image tags. * - * @var bool $responsive + * @var ?bool $responsive */ - public $responsive; + public ?bool $responsive = null; /** * The class of the responsive tag. * - * @var string $responsiveClass + * @var ?string $responsiveClass */ - public $responsiveClass; + public ?string $responsiveClass = null; /** * The value of the 'src' attribute. * - * @var string $responsivePlaceholder + * @var ?string $responsivePlaceholder */ - public $responsivePlaceholder; + public ?string $responsivePlaceholder = null; /** * Whether to automatically generate "sizes" attribute if not provided. @@ -79,31 +79,31 @@ class TagConfig extends BaseConfigSection * @var bool|int|string $sizes * */ - public $sizes; + public string|int|bool|null $sizes = null; /** * The percentage of the screen that the image occupies. * * Used for responsive breakpoints optimization. * - * @var float $relativeWidth Specify a percentage of the screen width (Range: 0.0 to 1.0) + * @var ?float $relativeWidth Specify a percentage of the screen width (Range: 0.0 to 1.0) * */ - protected $relativeWidth; + protected ?float $relativeWidth = null; /** * Whether to use hi dpi. * - * @var bool $hidpi + * @var ?bool $hidpi */ - public $hidpi; + public ?bool $hidpi = null; /** * Whether to use client hints. * * @var bool $clientHints */ - public $clientHints; + public ?bool $clientHints = null; /** * Whether to perform unsigned upload in the UploadTag. @@ -112,21 +112,21 @@ class TagConfig extends BaseConfigSection * * @see UploadTag */ - public $unsignedUpload; + public ?bool $unsignedUpload = null; /** * Image format of the video poster. * - * @var string $videoPosterFormat + * @var ?string $videoPosterFormat */ - protected $videoPosterFormat; + protected ?string $videoPosterFormat; /** * Whether to use fetch format transformation ("f_") instead of file extension. * - * @var string $useFetchFormat + * @var ?string $useFetchFormat */ - public $useFetchFormat; + public ?string $useFetchFormat = null; /** * Sets the type of the quotes to use (single or double). Default: BaseTag::DOUBLE_QUOTES. @@ -135,35 +135,35 @@ class TagConfig extends BaseConfigSection * * @see BaseTag::DOUBLE_QUOTES */ - protected $quotesType; + protected string $quotesType; /** * Defines whether to add slash to the void tag ending, e.g. "/>" or simply ">". * - * @var bool $voidClosingSlash + * @var ?bool $voidClosingSlash */ - public $voidClosingSlash; + public ?bool $voidClosingSlash = null; /** * Defines whether to sort attributes by keys alphabetically. * * @var bool $sortAttributes */ - public $sortAttributes; + public ?bool $sortAttributes = null; /** * Defines whether to set "src" attribute first. * - * @var bool $prependSrcAttribute + * @var ?bool $prependSrcAttribute */ - public $prependSrcAttribute; + public ?bool $prependSrcAttribute = null; /** * The delimiter between content items. * - * @var string $contentDelimiter + * @var ?string $contentDelimiter */ - protected $contentDelimiter; + protected ?string $contentDelimiter = null; /** * Sets the Tag configuration key with the specified value. @@ -175,7 +175,7 @@ class TagConfig extends BaseConfigSection * * @internal */ - public function setTagConfig($configKey, $configValue) + public function setTagConfig($configKey, $configValue): static { return $this->setConfig($configKey, $configValue); } diff --git a/src/Configuration/TagConfigTrait.php b/src/Configuration/TagConfigTrait.php index c35b513e..d85c4f65 100644 --- a/src/Configuration/TagConfigTrait.php +++ b/src/Configuration/TagConfigTrait.php @@ -25,7 +25,7 @@ trait TagConfigTrait * * @return $this */ - public function videoPosterFormat($format) + public function videoPosterFormat($format): static { return $this->setTagConfig(TagConfig::VIDEO_POSTER_FORMAT, $format); } @@ -38,7 +38,7 @@ public function videoPosterFormat($format) * * @return $this */ - public function useFetchFormat($useFetchFormat = true) + public function useFetchFormat($useFetchFormat = true): static { return $this->setTagConfig(TagConfig::USE_FETCH_FORMAT, $useFetchFormat); } @@ -53,5 +53,5 @@ public function useFetchFormat($useFetchFormat = true) * * @internal */ - abstract public function setTagConfig($configKey, $configValue); + abstract public function setTagConfig($configKey, $configValue): static; } diff --git a/src/Configuration/UrlConfig.php b/src/Configuration/UrlConfig.php index fc6e8b63..8a42985a 100644 --- a/src/Configuration/UrlConfig.php +++ b/src/Configuration/UrlConfig.php @@ -13,10 +13,10 @@ /** * Defines the global configuration applied when generating Cloudinary URLs. * - * @property bool $secure Force HTTPS URLs for resources even if they are embedded in - * non-secure HTTP pages. - * @property bool $forceVersion By default set to self::DEFAULT_FORCE_VERSION. - * @property string $responsiveWidthTransformation The transformation to use with responsive width. + * @property bool $secure Force HTTPS URLs for resources even if they are embedded in + * non-secure HTTP pages. + * @property bool $forceVersion By default, set to self::DEFAULT_FORCE_VERSION. + * @property mixed $responsiveWidthTransformation The transformation to use with responsive width. * * @api */ @@ -24,111 +24,111 @@ class UrlConfig extends BaseConfigSection { use UrlConfigTrait; - protected static $aliases = ['secure_distribution' => self::SECURE_CNAME]; + protected static array $aliases = ['secure_distribution' => self::SECURE_CNAME]; /** * @internal */ - const CONFIG_NAME = 'url'; + public const CONFIG_NAME = 'url'; /** * @internal */ - const DEFAULT_DOMAIN = 'cloudinary.com'; + public const DEFAULT_DOMAIN = 'cloudinary.com'; /** * @internal */ - const DEFAULT_SUB_DOMAIN = 'res'; + public const DEFAULT_SUB_DOMAIN = 'res'; /** * @internal */ - const DEFAULT_SHARED_HOST = self::DEFAULT_SUB_DOMAIN . '.' . self::DEFAULT_DOMAIN; + public const DEFAULT_SHARED_HOST = self::DEFAULT_SUB_DOMAIN . '.' . self::DEFAULT_DOMAIN; - const PROTOCOL_HTTP = 'http'; - const PROTOCOL_HTTPS = 'https'; + public const PROTOCOL_HTTP = 'http'; + public const PROTOCOL_HTTPS = 'https'; /** * Default value for secure (distribution). */ - const DEFAULT_SECURE = true; + public const DEFAULT_SECURE = true; /** * Default value for forcing version. */ - const DEFAULT_FORCE_VERSION = true; + public const DEFAULT_FORCE_VERSION = true; /** * Default value for analytics. */ - const DEFAULT_ANALYTICS = true; + public const DEFAULT_ANALYTICS = true; /** * Default responsive width transformation. */ - const DEFAULT_RESPONSIVE_WIDTH_TRANSFORMATION = 'c_limit,w_auto'; + public const DEFAULT_RESPONSIVE_WIDTH_TRANSFORMATION = 'c_limit,w_auto'; // Supported parameters - const CDN_SUBDOMAIN = 'cdn_subdomain'; - const SECURE_CDN_SUBDOMAIN = 'secure_cdn_subdomain'; - const CNAME = 'cname'; - const SECURE = 'secure'; - const SECURE_CNAME = 'secure_cname'; - const PRIVATE_CDN = 'private_cdn'; + public const CDN_SUBDOMAIN = 'cdn_subdomain'; + public const SECURE_CDN_SUBDOMAIN = 'secure_cdn_subdomain'; + public const CNAME = 'cname'; + public const SECURE = 'secure'; + public const SECURE_CNAME = 'secure_cname'; + public const PRIVATE_CDN = 'private_cdn'; - const SIGN_URL = 'sign_url'; - const LONG_URL_SIGNATURE = 'long_url_signature'; - const SHORTEN = 'shorten'; - const USE_ROOT_PATH = 'use_root_path'; - const FORCE_VERSION = 'force_version'; - const ANALYTICS = 'analytics'; + public const SIGN_URL = 'sign_url'; + public const LONG_URL_SIGNATURE = 'long_url_signature'; + public const SHORTEN = 'shorten'; + public const USE_ROOT_PATH = 'use_root_path'; + public const FORCE_VERSION = 'force_version'; + public const ANALYTICS = 'analytics'; - const RESPONSIVE_WIDTH = 'responsive_width'; - const RESPONSIVE_WIDTH_TRANSFORMATION = 'responsive_width_transformation'; + public const RESPONSIVE_WIDTH = 'responsive_width'; + public const RESPONSIVE_WIDTH_TRANSFORMATION = 'responsive_width_transformation'; /** * Whether to automatically build URLs with multiple CDN sub-domains. * - * @var bool + * @var ?bool * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#multiple_sub_domains */ - public $cdnSubdomain; + public ?bool $cdnSubdomain = null; /** * Secure CDN sub-domain. * - * @var bool + * @var ?bool */ - public $secureCdnSubdomain; + public ?bool $secureCdnSubdomain = null; /** * The custom domain name to use for building HTTP URLs. Relevant only for Advanced plan users that have a private * CDN distribution and a custom CNAME * - * @var string + * @var ?string * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#private_cdns_and_cnames */ - public $cname; + public ?string $cname = null; /** * Force HTTPS URLs for resources even if they are embedded in non-secure HTTP pages. * * @var bool */ - protected $secure; + protected bool $secure; /** * The domain name of the CDN distribution to use for building HTTPS URLs. Relevant only for Advanced plan users * that have a private CDN distribution. * - * @var string + * @var string|null * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#private_cdns_and_cnames */ - public $secureCname; + public ?string $secureCname = null; /** * Set this parameter to true if you are an Advanced plan user with a private CDN distribution. @@ -137,7 +137,7 @@ class UrlConfig extends BaseConfigSection * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#private_cdns_and_cnames */ - public $privateCdn; + public ?bool $privateCdn = null; /** * Set to true to create a Cloudinary URL signed with the first 8 characters of a SHA-1 hash. @@ -146,7 +146,7 @@ class UrlConfig extends BaseConfigSection * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#generating_delivery_url_signatures */ - public $signUrl; + public ?bool $signUrl = null; /** * Setting both this and signUrl to true will sign the URL using the first 32 characters of a SHA-256 hash. @@ -155,14 +155,14 @@ class UrlConfig extends BaseConfigSection * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#generating_delivery_url_signatures */ - public $longUrlSignature; + public ?bool $longUrlSignature = null; /** * Set to true to use shorten asset type. * * @var bool */ - public $shorten; + public ?bool $shorten = null; /** * Set to true to omit type and resource_type in the URL. @@ -171,35 +171,35 @@ class UrlConfig extends BaseConfigSection * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#root_path_urls */ - public $useRootPath; + public ?bool $useRootPath = null; /** - * Set to false to omit default version string for assets in folders in the delivery URL. + * Set to false in order to omit default version string for assets in folders in the delivery URL. * * @var bool */ - protected $forceVersion; + protected ?bool $forceVersion = null; /** - * Set to false to omit analytics data. + * Set to false in order to omit analytics data. * * @var bool */ - protected $analytics; + protected bool $analytics; /** * Whether to use responsive width. * * @var bool $responsiveWidth */ - public $responsiveWidth; + public ?bool $responsiveWidth = null; /** * The transformation to use with responsive width. * - * @var string $responsiveWidthTransformation + * @var mixed $responsiveWidthTransformation */ - protected $responsiveWidthTransformation; + protected mixed $responsiveWidthTransformation = null; /** * Serialises configuration section to a string representation. @@ -222,7 +222,7 @@ public function __toString() * * @internal */ - public function setUrlConfig($configKey, $configValue) + public function setUrlConfig(string $configKey, mixed $configValue): static { return $this->setConfig($configKey, $configValue); } diff --git a/src/Configuration/UrlConfigTrait.php b/src/Configuration/UrlConfigTrait.php index c27bfc38..3c190dfb 100644 --- a/src/Configuration/UrlConfigTrait.php +++ b/src/Configuration/UrlConfigTrait.php @@ -20,13 +20,12 @@ trait UrlConfigTrait /** * Whether to automatically build URLs with multiple CDN sub-domains. * - * @param bool $cdnSubdomain * * @return $this * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#multiple_sub_domains */ - public function cdnSubdomain($cdnSubdomain = true) + public function cdnSubdomain(bool $cdnSubdomain = true): static { return $this->setUrlConfig(UrlConfig::CDN_SUBDOMAIN, $cdnSubdomain); } @@ -34,11 +33,10 @@ public function cdnSubdomain($cdnSubdomain = true) /** * Whether to use secure CDN sub-domain. * - * @param bool $secureCdnSubdomain * * @return $this */ - public function secureCdnSubdomain($secureCdnSubdomain = true) + public function secureCdnSubdomain(bool $secureCdnSubdomain = true): static { return $this->setUrlConfig(UrlConfig::SECURE_CDN_SUBDOMAIN, $secureCdnSubdomain); } @@ -48,13 +46,12 @@ public function secureCdnSubdomain($secureCdnSubdomain = true) * * Relevant only for Advanced plan users that have a private CDN distribution and a custom CNAME. * - * @param string $cname * * @return $this * @see https://cloudinary.com/documentation/advanced_url_delivery_options#private_cdns_and_cnames * */ - public function cname($cname) + public function cname(string $cname): static { return $this->setUrlConfig(UrlConfig::CNAME, $cname); } @@ -62,11 +59,10 @@ public function cname($cname) /** * Force HTTPS URLs for resources even if they are embedded in non-secure HTTP pages. * - * @param bool $secure * * @return $this */ - public function secure($secure = true) + public function secure(bool $secure = true): static { return $this->setUrlConfig(UrlConfig::SECURE, $secure); } @@ -82,7 +78,7 @@ public function secure($secure = true) * @see https://cloudinary.com/documentation/advanced_url_delivery_options#private_cdns_and_cnames * */ - public function secureCname($secureCname) + public function secureCname(string $secureCname): static { return $this->setUrlConfig(UrlConfig::SECURE_CNAME, $secureCname); } @@ -90,14 +86,13 @@ public function secureCname($secureCname) /** * Set this parameter to true if you are an Advanced plan user with a private CDN distribution. * - * @param bool $privateCdn * * @return $this * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#private_cdns_and_cnames * */ - public function privateCdn($privateCdn = true) + public function privateCdn(bool $privateCdn = true): static { return $this->setUrlConfig(UrlConfig::PRIVATE_CDN, $privateCdn); } @@ -105,11 +100,10 @@ public function privateCdn($privateCdn = true) /** * Set to true to create a signed Cloudinary URL. * - * @param bool $signUrl * * @return $this */ - public function signUrl($signUrl = true) + public function signUrl(?bool $signUrl = true): static { return $this->setUrlConfig(UrlConfig::SIGN_URL, $signUrl); } @@ -117,13 +111,12 @@ public function signUrl($signUrl = true) /** * Setting both this and signUrl to true will sign the URL using the first 32 characters of a SHA-256 hash. * - * @param bool $longUrlSignature * * @return $this * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#generating_delivery_url_signatures */ - public function longUrlSignature($longUrlSignature = true) + public function longUrlSignature(bool $longUrlSignature = true): static { return $this->setUrlConfig(UrlConfig::LONG_URL_SIGNATURE, $longUrlSignature); } @@ -131,11 +124,10 @@ public function longUrlSignature($longUrlSignature = true) /** * Set to true to use shorten asset type. * - * @param bool $shorten * * @return $this */ - public function shorten($shorten = true) + public function shorten(bool $shorten = true): static { return $this->setUrlConfig(UrlConfig::SHORTEN, $shorten); } @@ -143,14 +135,13 @@ public function shorten($shorten = true) /** * Set to true to omit type and resource_type in the URL. * - * @param bool $useRootPath * * @return $this * * @see https://cloudinary.com/documentation/advanced_url_delivery_options#root_path_urls * */ - public function useRootPath($useRootPath = true) + public function useRootPath(bool $useRootPath = true): static { return $this->setUrlConfig(UrlConfig::USE_ROOT_PATH, $useRootPath); } @@ -158,11 +149,10 @@ public function useRootPath($useRootPath = true) /** * Set to false to omit default version string for assets in folders in the delivery URL. * - * @param bool $forceVersion * * @return $this */ - public function forceVersion($forceVersion = true) + public function forceVersion(bool $forceVersion = true): static { return $this->setUrlConfig(UrlConfig::FORCE_VERSION, $forceVersion); } @@ -174,7 +164,7 @@ public function forceVersion($forceVersion = true) * * @return $this */ - public function analytics($analytics = true) + public function analytics(bool $analytics = true): static { return $this->setUrlConfig(UrlConfig::ANALYTICS, $analytics); } @@ -189,5 +179,5 @@ public function analytics($analytics = true) * * @internal */ - abstract public function setUrlConfig($configKey, $configValue); + abstract public function setUrlConfig(string $configKey, mixed $configValue): static; } diff --git a/src/HttpClient/HttpClient.php b/src/HttpClient/HttpClient.php index d16858cd..cbb55f71 100644 --- a/src/HttpClient/HttpClient.php +++ b/src/HttpClient/HttpClient.php @@ -29,13 +29,14 @@ class HttpClient /** * @var Client $httpClient The HTTP client instance. */ - protected $httpClient; + protected Client $httpClient; /** * HttpClient constructor. - * @param Configuration|null $configuration + * + * @param Configuration|null $configuration Configuration source. */ - public function __construct($configuration = null) + public function __construct(?Configuration $configuration = null) { $this->httpClient = new Client(); @@ -51,12 +52,11 @@ public function __construct($configuration = null) * * @param string $url The url * - * @return mixed * * @throws Error * @throws \GuzzleHttp\Exception\GuzzleException */ - public function getJson($url) + public function getJson(string $url): mixed { try { return self::parseJsonResponse($this->httpClient->get($url)); @@ -78,14 +78,13 @@ public function getJson($url) * * @param ResponseInterface $response Response from HTTP request to Cloudinary server * - * @return mixed * * @throws Error */ - private static function parseJsonResponse($response) + private static function parseJsonResponse(ResponseInterface $response): mixed { try { - $responseJson = JsonUtils::decode($response->getBody(), true); + $responseJson = JsonUtils::decode($response->getBody()); } catch (InvalidArgumentException $iae) { $message = sprintf( 'Error parsing server response (%s) - %s. Got - %s', diff --git a/src/Log/Logger.php b/src/Log/Logger.php index 35b05df9..523024df 100644 --- a/src/Log/Logger.php +++ b/src/Log/Logger.php @@ -27,42 +27,39 @@ */ class Logger { - const LOGGER_NAME = 'cloudinary'; + public const LOGGER_NAME = 'cloudinary'; - /** - * @var Monolog $entity - */ - private $entity; + private Monolog $entity; /** * @var int $defaultLogLevel The default log level. Is set during initialization. */ - private $defaultLogLevel; + private int $defaultLogLevel; /** * @var array Map of PHP error levels to PSR-3 log levels */ - private $errorLevelMap = [ - E_ERROR => Monolog::CRITICAL, - E_WARNING => Monolog::WARNING, - E_PARSE => Monolog::ALERT, - E_NOTICE => Monolog::NOTICE, - E_CORE_ERROR => Monolog::CRITICAL, - E_CORE_WARNING => Monolog::WARNING, - E_COMPILE_ERROR => Monolog::ALERT, - E_COMPILE_WARNING => Monolog::WARNING, - E_USER_ERROR => Monolog::ERROR, - E_USER_WARNING => Monolog::WARNING, - E_USER_NOTICE => Monolog::NOTICE, - E_RECOVERABLE_ERROR => Monolog::ERROR, - E_DEPRECATED => Monolog::NOTICE, - E_USER_DEPRECATED => Monolog::NOTICE, - ]; + private array $errorLevelMap + = [ + E_ERROR => Monolog::CRITICAL, + E_WARNING => Monolog::WARNING, + E_PARSE => Monolog::ALERT, + E_NOTICE => Monolog::NOTICE, + E_CORE_ERROR => Monolog::CRITICAL, + E_CORE_WARNING => Monolog::WARNING, + E_COMPILE_ERROR => Monolog::ALERT, + E_COMPILE_WARNING => Monolog::WARNING, + E_USER_ERROR => Monolog::ERROR, + E_USER_WARNING => Monolog::WARNING, + E_USER_NOTICE => Monolog::NOTICE, + E_RECOVERABLE_ERROR => Monolog::ERROR, + E_DEPRECATED => Monolog::NOTICE, + E_USER_DEPRECATED => Monolog::NOTICE, + ]; /** * Logger constructor. * - * @param LoggingConfig $config */ public function __construct(LoggingConfig $config) { @@ -70,12 +67,7 @@ public function __construct(LoggingConfig $config) $this->init($config); } - /** - * @param LoggingConfig $config - * - * @return null|Logger - */ - private function init(LoggingConfig $config) + private function init(LoggingConfig $config): ?Logger { if ($config->enabled === false) { return null; @@ -129,16 +121,10 @@ private function init(LoggingConfig $config) return $this; } - /** - * @param HandlerInterface $handler - * - * @return Monolog - */ - private function addHandler(HandlerInterface $handler) + private function addHandler(HandlerInterface $handler): Monolog { foreach ($this->entity->getHandlers() as $entityHandler) { - if ($entityHandler instanceof HandlerInterface - && $entityHandler->getLevel() === $handler->getLevel() + if ($entityHandler instanceof HandlerInterface && $entityHandler->getLevel() === $handler->getLevel() ) { return $this->entity; } @@ -150,7 +136,7 @@ private function addHandler(HandlerInterface $handler) /** * @return HandlerInterface[] */ - public function getHandlers() + public function getHandlers(): array { return $this->entity->getHandlers(); } @@ -158,9 +144,8 @@ public function getHandlers() /** * Gets TestHandler * - * @return null|TestHandler */ - public function getTestHandler() + public function getTestHandler(): ?TestHandler { foreach ($this->entity->getHandlers() as $handler) { if ($handler instanceof TestHandler) { @@ -172,13 +157,16 @@ public function getTestHandler() } /** - * @param $level - * @param $message - * @param array $context + * Adds a log record at an arbitrary level. + * + * This method allows for compatibility with common interfaces. + * + * @param mixed $level The log level (a Monolog, PSR-3 or RFC 5424 level) + * @param string|\Stringable $message The log message + * @param array $context The log context * - * @return void */ - public function log($level, $message, array $context = []) + public function log(mixed $level, string|\Stringable $message, array $context = []): void { $this->entity->log($level, $message, $context); } @@ -190,9 +178,9 @@ public function log($level, $message, array $context = []) * * @return int PSR-3 log level */ - public function getDefaultLogLevel() + public function getDefaultLogLevel(): int { - if ($this->defaultLogLevel !== null) { + if (isset($this->defaultLogLevel)) { return $this->defaultLogLevel; } diff --git a/src/Log/LoggerDecorator.php b/src/Log/LoggerDecorator.php index 1305e0a3..4b6a696a 100644 --- a/src/Log/LoggerDecorator.php +++ b/src/Log/LoggerDecorator.php @@ -21,20 +21,14 @@ class LoggerDecorator implements LoggerInterface { use LoggerDecoratorTrait; - /** - * @var Logger - */ - private $logger; - /** - * @var LoggingConfig - */ - private $config; + private ?Logger $logger; + + private ?LoggingConfig $config; /** * LoggerDecorator constructor. * - * @param LoggingConfig|null $config */ public function __construct(?LoggingConfig $config = null) { @@ -44,15 +38,11 @@ public function __construct(?LoggingConfig $config = null) /** * Get the TestHandler (if one has been defined) * - * @return TestHandler|null */ - public function getTestHandler() + public function getTestHandler(): ?TestHandler { - if ($this->logger !== null) { - return $this->logger->getTestHandler(); - } + return $this->logger?->getTestHandler(); - return null; } /** @@ -60,7 +50,7 @@ public function getTestHandler() * * @return HandlerInterface[] */ - public function getHandlers() + public function getHandlers(): array { if ($this->logger !== null) { return $this->logger->getHandlers(); diff --git a/src/Log/LoggerDecoratorTrait.php b/src/Log/LoggerDecoratorTrait.php index 8d3738c3..f7bbc3df 100644 --- a/src/Log/LoggerDecoratorTrait.php +++ b/src/Log/LoggerDecoratorTrait.php @@ -41,7 +41,7 @@ public function debug(string|\Stringable $message, array $context = []): void */ public function log($level, string|\Stringable $message, array $context = []): void { - if ($this->logger === null) { + if (! isset($this->logger)) { $this->logger = LoggersList::instance()->getLogger($this->config); } diff --git a/src/Log/LoggerTrait.php b/src/Log/LoggerTrait.php index 734048e7..e1b671b2 100644 --- a/src/Log/LoggerTrait.php +++ b/src/Log/LoggerTrait.php @@ -142,22 +142,13 @@ */ trait LoggerTrait { - /** - * @var LoggingConfig $logging - */ - public $logging; + public LoggingConfig $logging; - /** - * @var LoggerInterface $logger - */ - private $logger; + private LoggerInterface $logger; - /** - * @return LoggerInterface - */ - protected function getLogger() + protected function getLogger(): LoggerDecorator|LoggerInterface { - if ($this->logger === null) { + if (!isset($this->logger)) { $this->logger = new LoggerDecorator($this->logging); } diff --git a/src/Log/LoggersList.php b/src/Log/LoggersList.php index 3139802d..02d71886 100644 --- a/src/Log/LoggersList.php +++ b/src/Log/LoggersList.php @@ -21,12 +21,12 @@ class LoggersList /** * @var Logger[] $loggerInstances */ - private static $loggerInstances = []; + private static array $loggerInstances = []; /** - * @var LoggersList $instance The instance of the LoggersList. + * @var bool|LoggersList $instance The instance of the LoggersList. */ - private static $instance = false; + private static LoggersList|bool $instance = false; /** * LoggersList private constructor. @@ -39,9 +39,8 @@ private function __construct() /** * Returns a singleton instance of the LoggersList. * - * @return LoggersList */ - public static function instance() + public static function instance(): bool|LoggersList { if (self::$instance === false) { self::$instance = new LoggersList(); @@ -50,12 +49,7 @@ public static function instance() return self::$instance; } - /** - * @param LoggingConfig $config - * - * @return Logger|null - */ - public static function getLogger(LoggingConfig $config) + public static function getLogger(LoggingConfig $config): ?Logger { if ($config->enabled === false) { return null; diff --git a/src/Tag/Attribute/AudioSourceType.php b/src/Tag/Attribute/AudioSourceType.php index 12bb7bca..90bcab1f 100644 --- a/src/Tag/Attribute/AudioSourceType.php +++ b/src/Tag/Attribute/AudioSourceType.php @@ -19,12 +19,12 @@ */ class AudioSourceType extends SourceType { - const WAV = 'wav'; - const MP3 = 'mpeg'; - const MP4 = 'mp4'; - const AAC = 'aac'; - const WEBM = 'webm'; - const FLAC = 'flac'; + public const WAV = 'wav'; + public const MP3 = 'mpeg'; + public const MP4 = 'mp4'; + public const AAC = 'aac'; + public const WEBM = 'webm'; + public const FLAC = 'flac'; /** * AudioSourceType constructor. diff --git a/src/Tag/Attribute/Media.php b/src/Tag/Attribute/Media.php index 2238428a..d19044e7 100644 --- a/src/Tag/Attribute/Media.php +++ b/src/Tag/Attribute/Media.php @@ -12,7 +12,6 @@ use Cloudinary\Configuration\Configuration; use Cloudinary\Log\LoggerTrait; -use \InvalidArgumentException; /** * Class Media @@ -24,23 +23,23 @@ class Media use LoggerTrait; /** - * @var int $minWidth The minimum width of the screen. + * @var int|null $minWidth The minimum width of the screen. */ - protected $minWidth; + protected ?int $minWidth; /** - * @var int $maxWidthThe maximum width of the screen. + * @var int|null $maxWidthThe maximum width of the screen. */ - protected $maxWidth; + protected ?int $maxWidth; /** * Media constructor. * - * @param int $minWidth The minimum width of the screen. - * @param int $maxWidth The maximum width of the screen. - * @param Configuration $configuration + * @param int|null $minWidth The minimum width of the screen. + * @param int|null $maxWidth The maximum width of the screen. + * @param Configuration|null $configuration The Configuration source. */ - public function __construct($minWidth = null, $maxWidth = null, $configuration = null) + public function __construct(?int $minWidth = null, ?int $maxWidth = null, ?Configuration $configuration = null) { $this->minWidth = $minWidth; $this->maxWidth = $maxWidth; diff --git a/src/Tag/Attribute/Sizes.php b/src/Tag/Attribute/Sizes.php index 29a543ae..8f88fd2a 100644 --- a/src/Tag/Attribute/Sizes.php +++ b/src/Tag/Attribute/Sizes.php @@ -22,14 +22,14 @@ class Sizes /** * @var Configuration $configuration The Configuration instance. */ - protected $configuration; + protected Configuration $configuration; /** * Sizes constructor. * * @param Configuration $configuration The Configuration instance.. */ - public function __construct($configuration) + public function __construct(Configuration $configuration) { $this->configuration = $configuration; } diff --git a/src/Tag/Attribute/SourceType.php b/src/Tag/Attribute/SourceType.php index cdff8a4e..249b0e4c 100644 --- a/src/Tag/Attribute/SourceType.php +++ b/src/Tag/Attribute/SourceType.php @@ -22,34 +22,34 @@ */ class SourceType { - const MEDIA_TYPE_VIDEO = 'video'; - const MEDIA_TYPE_AUDIO = 'audio'; + public const MEDIA_TYPE_VIDEO = 'video'; + public const MEDIA_TYPE_AUDIO = 'audio'; /** - * @var string $mediaType The media type. Can be self::MEDIA_TYPE_VIDEO or self::MEDIA_TYPE_AUDIO. + * @var string|null $mediaType The media type. Can be self::MEDIA_TYPE_VIDEO or self::MEDIA_TYPE_AUDIO. */ - protected $mediaType; + protected ?string $mediaType; /** - * @var string $type The type(format) of the source. + * @var string|null $type The type(format) of the source. */ - public $type; + public ?string $type; /** * @var array $codecs The codecs. */ - public $codecs = []; + public array $codecs = []; - public static $typeOverrides = [Format::OGV => VideoSourceType::OGG]; + public static array $typeOverrides = [Format::OGV => VideoSourceType::OGG]; /** * SourceType constructor. * - * @param string $mediaType The media type. Can be self::MEDIA_TYPE_VIDEO or self::MEDIA_TYPE_AUDIO. - * @param string $type The type(format) of the source. - * @param string|array|null $codecs The codecs. + * @param string|null $mediaType The media type. Can be self::MEDIA_TYPE_VIDEO or self::MEDIA_TYPE_AUDIO. + * @param string|null $type The type(format) of the source. + * @param array|string|null $codecs The codecs. */ - public function __construct($mediaType = null, $type = null, $codecs = null) + public function __construct(?string $mediaType = null, ?string $type = null, array|string|null $codecs = null) { $this->mediaType = $mediaType; $this->type = $type; diff --git a/src/Tag/Attribute/SrcSet.php b/src/Tag/Attribute/SrcSet.php index 62806dbd..811e67a0 100644 --- a/src/Tag/Attribute/SrcSet.php +++ b/src/Tag/Attribute/SrcSet.php @@ -31,7 +31,7 @@ class SrcSet /** * @var array RES_DISTRIBUTION The distribution of screen resolutions. */ - const RES_DISTRIBUTION + public const RES_DISTRIBUTION = [ 1366, 828, @@ -47,46 +47,42 @@ class SrcSet /** * @var int DEFAULT_DPR_THRESHOLD The threshold for switching from DEFAULT_DPR to DPR 1.0. */ - const DEFAULT_DPR_THRESHOLD = 768; + public const DEFAULT_DPR_THRESHOLD = 768; /** * @var float DEFAULT_DPR The default DPR for width below DEFAULT_DPR_THRESHOLD. */ - const DEFAULT_DPR = 2.0; + public const DEFAULT_DPR = 2.0; use LoggerTrait; /** - * @var array The list of the breakpoints. + * @var ?array The list of the breakpoints. */ - protected $breakpoints = []; + protected ?array $breakpoints = []; /** * @var Image $image The Image of the attribute. */ - protected $image; + protected mixed $image; /** * @var ResponsiveBreakpointsConfig $responsiveBreakpointsConfig The configuration instance. */ - protected $responsiveBreakpointsConfig; + protected ResponsiveBreakpointsConfig $responsiveBreakpointsConfig; /** * @var Transformation $transformation The srcset transformation. */ - protected $transformation; + protected Transformation $transformation; - /** - * @var float - */ - protected $relativeWidth; + protected float $relativeWidth; /** * SrcSet constructor. * - * @param $image - * @param Configuration $configuration + * @param Configuration|null $configuration The Configuration source. */ - public function __construct($image, $configuration = null) + public function __construct($image, ?Configuration $configuration = null) { $this->image = ClassUtils::forceInstance($image, Image::class, null, $configuration); $this->logging = $configuration->logging; @@ -104,7 +100,7 @@ public function __construct($image, $configuration = null) * * @return $this */ - public function breakpoints(?array $breakpoints = null) + public function breakpoints(?array $breakpoints = null): static { $this->breakpoints = $breakpoints; @@ -118,7 +114,7 @@ public function breakpoints(?array $breakpoints = null) * * @return $this */ - public function autoOptimalBreakpoints($autoOptimalBreakpoints = true) + public function autoOptimalBreakpoints(bool $autoOptimalBreakpoints = true): static { $this->responsiveBreakpointsConfig->autoOptimalBreakpoints = $autoOptimalBreakpoints; @@ -132,7 +128,7 @@ public function autoOptimalBreakpoints($autoOptimalBreakpoints = true) * * @return $this */ - public function relativeWidth($relativeWidth = 1.0) + public function relativeWidth(float $relativeWidth = 1.0): static { $this->relativeWidth = $relativeWidth; @@ -146,13 +142,12 @@ public function relativeWidth($relativeWidth = 1.0) * @param int $maxWidth The maximum width needed for this image. * @param int $maxImages The number of breakpoints to use. * - * @return array */ - private function calculateAutoOptimalBreakpoints($minWidth, $maxWidth, $maxImages) + private function calculateAutoOptimalBreakpoints(int $minWidth, int $maxWidth, int $maxImages): array { - list($minWidth, $maxWidth, $maxImages) = $this->validateInput($minWidth, $maxWidth, $maxImages); + [$minWidth, $maxWidth, $maxImages] = $this->validateInput($minWidth, $maxWidth, $maxImages); - list($physicalMinWidth, $physicalMaxWidth) = self::getPhysicalDimensions($minWidth, $maxWidth); + [$physicalMinWidth, $physicalMaxWidth] = self::getPhysicalDimensions($minWidth, $maxWidth); if ($physicalMinWidth === $physicalMaxWidth) { return [$physicalMaxWidth]; @@ -160,9 +155,7 @@ private function calculateAutoOptimalBreakpoints($minWidth, $maxWidth, $maxImage $validBreakpoints = array_filter( self::RES_DISTRIBUTION, - static function ($v) use ($physicalMinWidth, $physicalMaxWidth) { - return $v >= $physicalMinWidth && $v <= $physicalMaxWidth; - } + static fn($v) => $v >= $physicalMinWidth && $v <= $physicalMaxWidth ); $res = self::collectFromGroup( @@ -175,49 +168,39 @@ static function ($v) use ($physicalMinWidth, $physicalMaxWidth) { sort($res); - $res = array_map(function ($bp) { - return (int)ceil($bp * $this->relativeWidth); - }, $res); - - return $res; + return array_map(fn($bp) => (int)ceil($bp * $this->relativeWidth), $res); } /** - * @param $minWidth - * @param $maxWidth * * @return int[] */ - protected static function getPhysicalDimensions($minWidth, $maxWidth) + protected static function getPhysicalDimensions($minWidth, $maxWidth): array { $physicalMinWidth = self::getDprDimension($minWidth); $physicalMaxWidth = self::getDprDimension($maxWidth); if ($physicalMinWidth > $physicalMaxWidth) { - list($physicalMinWidth, $physicalMaxWidth) = [$physicalMaxWidth, $physicalMinWidth]; + [$physicalMinWidth, $physicalMaxWidth] = [$physicalMaxWidth, $physicalMinWidth]; } return [$physicalMinWidth, $physicalMaxWidth]; } - /** - * @param int $dimension - * - * @return int - */ - protected static function getDprDimension($dimension) + protected static function getDprDimension(int $dimension): float|int { - return $dimension < self::DEFAULT_DPR_THRESHOLD ? (int)$dimension * self::DEFAULT_DPR : $dimension; + return $dimension < self::DEFAULT_DPR_THRESHOLD ? $dimension * self::DEFAULT_DPR : $dimension; } /** - * @param $group - * @param $whitelist - * @param int $count + * Collect breakpoints from group. + * + * @param array $group The group of breakpoints. + * @param array $whitelist The whitelisted values. + * @param int $count The amount to collect. * - * @return array */ - protected static function collectFromGroup($group, $whitelist, $count = 1) + protected static function collectFromGroup(array $group, array $whitelist, int $count = 1): array { $result = []; @@ -226,7 +209,7 @@ protected static function collectFromGroup($group, $whitelist, $count = 1) } foreach ($group as $res) { - if (in_array($res, $whitelist, false) && ! in_array($res, $result, false)) { + if (in_array($res, $whitelist) && ! in_array($res, $result)) { $result [] = $res; $count--; if (! $count) { @@ -245,9 +228,8 @@ protected static function collectFromGroup($group, $whitelist, $count = 1) * @param int $maxWidth The maximum width needed for this image. * @param int $maxImages The number of breakpoints to use. * - * @return array */ - private function validateInput($minWidth, $maxWidth, $maxImages) + private function validateInput(int $minWidth, int $maxWidth, int $maxImages): ?array { // When called without any values, just return null if ($minWidth === null && $maxWidth === null && $maxImages === null) { @@ -299,9 +281,7 @@ public function __toString() return implode( ', ', array_map( - function ($b) { - return $this->image->toUrl(Resize::scale($b)) . " {$b}w"; - }, + fn($b) => $this->image->toUrl(Resize::scale($b)) . " {$b}w", $breakpoints ) ); @@ -310,11 +290,10 @@ function ($b) { /** * Gets the breakpoints. * - * @return array * * @internal */ - public function getBreakpoints() + public function getBreakpoints(): array { if (! empty($this->breakpoints)) { return $this->breakpoints; diff --git a/src/Tag/Attribute/VideoSourceType.php b/src/Tag/Attribute/VideoSourceType.php index b1cfe2bb..631d394a 100644 --- a/src/Tag/Attribute/VideoSourceType.php +++ b/src/Tag/Attribute/VideoSourceType.php @@ -19,17 +19,17 @@ */ class VideoSourceType extends SourceType { - const MP4 = 'mp4'; - const WEBM = 'webm'; - const OGG = 'ogg'; + public const MP4 = 'mp4'; + public const WEBM = 'webm'; + public const OGG = 'ogg'; /** * VideoSourceType constructor. * - * @param string $type The type of the video source. - * @param null $codecs The codecs. + * @param ?string $type The type of the video source. + * @param array|string|null $codecs The codecs. */ - public function __construct($type = null, $codecs = null) + public function __construct(?string $type = null, array|string|null $codecs = null) { parent::__construct(self::MEDIA_TYPE_VIDEO, $type, $codecs); } @@ -37,11 +37,10 @@ public function __construct($type = null, $codecs = null) /** * The mp4 video source type. * - * @param string|array $codecs The codecs. + * @param array|string|null $codecs The codecs. * - * @return VideoSourceType */ - public static function mp4($codecs = null) + public static function mp4(array|string|null $codecs = null): VideoSourceType { return new VideoSourceType(self::MP4, $codecs); } @@ -49,11 +48,10 @@ public static function mp4($codecs = null) /** * The webm video source type. * - * @param string|array $codecs The codecs. + * @param array|string|null $codecs The codecs. * - * @return VideoSourceType */ - public static function webm($codecs = null) + public static function webm(array|string|null $codecs = null): VideoSourceType { return new VideoSourceType(self::WEBM, $codecs); } @@ -61,11 +59,10 @@ public static function webm($codecs = null) /** * The ogg video source type. * - * @param string|array $codecs The codecs. + * @param array|string|null $codecs The codecs. * - * @return VideoSourceType */ - public static function ogg($codecs = null) + public static function ogg(array|string|null $codecs = null): VideoSourceType { return new VideoSourceType(self::OGG, $codecs); } diff --git a/src/Tag/BaseConfigurableApiTag.php b/src/Tag/BaseConfigurableApiTag.php index a4696108..308b5a46 100644 --- a/src/Tag/BaseConfigurableApiTag.php +++ b/src/Tag/BaseConfigurableApiTag.php @@ -28,37 +28,40 @@ class BaseConfigurableApiTag extends BaseTag /** * @var ApiConfig $apiConfig The API configuration instance. */ - public $apiConfig; + public ApiConfig $apiConfig; /** * @var array $uploadParams The upload parameters. */ - protected $uploadParams; + protected array $uploadParams; /** * @var string $assetType The type of the asset. */ - protected $assetType; + protected string $assetType; /** * @var UploadApi $uploadApi Upload API instance. */ - protected $uploadApi; + protected UploadApi $uploadApi; /** * BaseConfigurableApiTag constructor. * - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * @param array $uploadParams The upload parameters. * @param string $assetType The type of the asset. */ - public function __construct($configuration = null, $uploadParams = [], $assetType = AssetType::AUTO) - { + public function __construct( + Configuration|array|string|null $configuration = null, + array $uploadParams = [], + string $assetType = AssetType::AUTO + ) { parent::__construct($configuration); - $this->uploadApi = new UploadApi($configuration); + $this->uploadApi = new UploadApi($configuration); $this->uploadParams = $uploadParams; - $this->assetType = $assetType; + $this->assetType = $assetType; } /** @@ -66,10 +69,9 @@ public function __construct($configuration = null, $uploadParams = [], $assetTyp * * If signed upload then also adds a signature param to the array. * - * @return array * @noinspection StaticInvocationViaThisInspection */ - protected function getUploadParams() + protected function getUploadParams(): array { $params = $this->uploadApi->buildUploadParams($this->uploadParams); @@ -83,11 +85,10 @@ protected function getUploadParams() /** * Sets the configuration. * - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return Configuration */ - public function configuration($configuration) + public function configuration(Configuration|array|string|null $configuration): Configuration { $tempConfiguration = parent::configuration($configuration); $this->apiConfig = $tempConfiguration->api; diff --git a/src/Tag/BaseImageTag.php b/src/Tag/BaseImageTag.php index 9d2218f4..b2aab1a0 100644 --- a/src/Tag/BaseImageTag.php +++ b/src/Tag/BaseImageTag.php @@ -36,32 +36,35 @@ abstract class BaseImageTag extends BaseTag implements ImageTransformationInterf use AssetDescriptorTrait; use AssetConfigTrait; - const IS_VOID = true; + public const IS_VOID = true; /** * @var Image $image The image of the tag. */ - public $image; + public Image $image; /** * @var SrcSet $srcset The srcset of the tag. */ - public $srcset; + public SrcSet $srcset; /** - * @var ImageTransformation $additionalTransformation Additional transformation to be applied on the tag image. + * @var ImageTransformation|null $additionalTransformation Additional transformation to be applied on the tag image. */ - public $additionalTransformation; + public ?ImageTransformation $additionalTransformation; /** * BaseImageTag constructor. * * @param string|Image $source The Public ID or Image instance - * @param Configuration|string|array|null $configuration The Configuration source. - * @param ImageTransformation $additionalTransformation The additional transformation. + * @param array|string|Configuration|null $configuration The Configuration source. + * @param ImageTransformation|null $additionalTransformation The additional transformation. */ - public function __construct($source, $configuration = null, $additionalTransformation = null) - { + public function __construct( + $source, + Configuration|array|string|null $configuration = null, + ?ImageTransformation $additionalTransformation = null + ) { parent::__construct($configuration); $this->image($source, $this->config); @@ -77,9 +80,8 @@ public function __construct($source, $configuration = null, $additionalTransform * @param string $source The public ID of the asset. * @param array $params The asset parameters. * - * @return BaseImageTag */ - public static function fromParams($source, $params = []) + public static function fromParams(string $source, array $params = []): BaseImageTag { $configuration = self::fromParamsDefaultConfig(); @@ -105,11 +107,7 @@ public static function fromParams($source, $params = []) return (new static($image, $configuration))->setAttributes($tagAttributes); } - /** - * @param array $params - * @param Configuration $configuration - */ - public static function handleResponsive(&$params, $configuration) + public static function handleResponsive(array &$params, Configuration $configuration): void { if ($configuration->url->responsiveWidth) { $configuration->tag->responsive = true; @@ -131,11 +129,10 @@ public static function handleResponsive(&$params, $configuration) /** * Imports (merges) the configuration. * - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public function importConfiguration($configuration) + public function importConfiguration(Configuration|array|string|null $configuration): static { parent::importConfiguration($configuration); @@ -147,12 +144,11 @@ public function importConfiguration($configuration) /** * Sets the image. * - * @param mixed $image The public ID or Image asset. - * @param Configuration $configuration The configuration instance. + * @param mixed $image The public ID or Image asset. + * @param Configuration|null $configuration The configuration instance. * - * @return static */ - public function image($image, $configuration = null) + public function image(mixed $image, ?Configuration $configuration = null): static { if ($configuration === null) { $configuration = $this->config; @@ -165,24 +161,26 @@ public function image($image, $configuration = null) /** * Serializes to json. - * - * @return mixed */ - public function jsonSerialize() + public function jsonSerialize(): array { // TODO: Implement jsonSerialize() method. + return []; } /** - * Adds (appends) a transformation in URL syntax to the current chain. A transformation is a set of instructions for adjusting images or videos—such as resizing, cropping, applying filters, adding overlays, or optimizing formats. For a detailed listing of all transformations, see the [Transformation Reference](https://cloudinary.com/documentation/transformation_reference) or the [PHP reference](https://cloudinary.com/documentation/sdks/php/php-transformation-builder/index.html). + * Adds (appends) a transformation in URL syntax to the current chain. A transformation is a set of instructions + * for adjusting images or videos—such as resizing, cropping, applying filters, adding overlays, or optimizing + * formats. For a detailed listing of all transformations, see the [Transformation + * Reference](https://cloudinary.com/documentation/transformation_reference) or the [PHP + * reference](https://cloudinary.com/documentation/sdks/php/php-transformation-builder/index.html). * * Appended transformation is nested. * * @param CommonTransformation $transformation The transformation to add. * - * @return static */ - public function addTransformation($transformation) + public function addTransformation($transformation): static { $this->image->addTransformation($transformation); @@ -195,9 +193,8 @@ public function addTransformation($transformation) * @param BaseAction|BaseQualifier|mixed $action The transformation action to add. * If BaseQualifier is provided, it is wrapped with action. * - * @return static */ - public function addAction($action) + public function addAction($action): static { $this->image->addAction($action); @@ -209,9 +206,8 @@ public function addAction($action) * * @param array|null $breakpoints The breakpoints. * - * @return $this */ - public function breakpoints(?array $breakpoints = null) + public function breakpoints(?array $breakpoints = null): static { $this->srcset->breakpoints($breakpoints); @@ -225,7 +221,7 @@ public function breakpoints(?array $breakpoints = null) * * @return $this */ - public function autoOptimalBreakpoints($autoOptimalBreakpoints = true) + public function autoOptimalBreakpoints(bool $autoOptimalBreakpoints = true): static { $this->srcset->autoOptimalBreakpoints($autoOptimalBreakpoints); @@ -239,7 +235,7 @@ public function autoOptimalBreakpoints($autoOptimalBreakpoints = true) * * @return $this */ - public function relativeWidth($relativeWidth = 1.0) + public function relativeWidth(float $relativeWidth = 1.0): static { $this->srcset->relativeWidth($relativeWidth); @@ -258,7 +254,7 @@ public function relativeWidth($relativeWidth = 1.0) * * @internal */ - public function setAssetProperty($propertyName, $propertyValue) + public function setAssetProperty(string $propertyName, mixed $propertyValue): static { $this->image->setAssetProperty($propertyName, $propertyValue); @@ -275,7 +271,7 @@ public function setAssetProperty($propertyName, $propertyValue) * * @internal */ - public function setCloudConfig($configKey, $configValue) + public function setCloudConfig(string $configKey, mixed $configValue): static { $this->image->setCloudConfig($configKey, $configValue); @@ -293,7 +289,7 @@ public function setCloudConfig($configKey, $configValue) * * @internal */ - public function setUrlConfig($configKey, $configValue) + public function setUrlConfig(string $configKey, mixed $configValue): static { $this->image->setUrlConfig($configKey, $configValue); diff --git a/src/Tag/BaseTag.php b/src/Tag/BaseTag.php index a80f7034..307ac72f 100644 --- a/src/Tag/BaseTag.php +++ b/src/Tag/BaseTag.php @@ -27,45 +27,45 @@ abstract class BaseTag { use TagConfigTrait; - const SINGLE_QUOTES = 'single_quotes'; - const DOUBLE_QUOTES = 'double_quotes'; + public const SINGLE_QUOTES = 'single_quotes'; + public const DOUBLE_QUOTES = 'double_quotes'; /** - * @var string NAME Mandatory. The name of the tag. + * @var ?string NAME Mandatory. The name of the tag. */ - const NAME = null; + public const NAME = null; /** * @var bool IS_VOID Indicates whether the tag is a void (self-closed, without body) tag. */ - const IS_VOID = false; + protected const IS_VOID = false; /** * @var array $classes An array of tag (unique) classes. Keys are used for uniqueness. */ - protected $classes = []; + protected array $classes = []; /** * @var array $attributes An array of tag attributes. */ - protected $attributes = []; + protected array $attributes = []; /** * @var Configuration $config The Configuration instance. */ - public $config; + public Configuration $config; /** * @var array $content The items of the tag content(body). */ - protected $content = []; + protected array $content = []; /** * BaseTag constructor. * - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. */ - public function __construct($configuration = null) + public function __construct(Configuration|array|string|null $configuration = null) { if (static::NAME === null) { throw new UnexpectedValueException('Tag name cannot be empty!'); @@ -81,11 +81,10 @@ public function __construct($configuration = null) /** * Sets the configuration. * - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return Configuration */ - public function configuration($configuration) + public function configuration(Configuration|array|string|null $configuration): Configuration { $tempConfiguration = new Configuration($configuration); // TODO: improve performance here $this->config = $tempConfiguration; @@ -96,11 +95,10 @@ public function configuration($configuration) /** * Imports (merges) the configuration. * - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public function importConfiguration($configuration) + public function importConfiguration(Configuration|array|string|null $configuration): static { $this->config->importConfig($configuration); @@ -110,11 +108,10 @@ public function importConfiguration($configuration) /** * Adds a tag class. * - * @param string|array $class The class to add. + * @param array|string|null $class The class to add. * - * @return static */ - public function addClass($class) + public function addClass(array|string|null $class): static { if (empty($class)) { return $this; @@ -132,11 +129,10 @@ public function addClass($class) /** * Resets tag classes and sets the specified one. * - * @param string|array $class The class to set. + * @param array|string $class The class to set. * - * @return static */ - public function setClass($class) + public function setClass(array|string $class): static { $this->classes = []; @@ -146,12 +142,11 @@ public function setClass($class) /** * Sets tag attribute. * - * @param string $key The attribute name. - * @param mixed $value The attribute value. + * @param string $key The attribute name. + * @param mixed|null $value The attribute value. * - * @return static */ - public function setAttribute($key, $value = null) + public function setAttribute(string $key, mixed $value = null): static { $this->attributes[$key] = $value; @@ -163,9 +158,8 @@ public function setAttribute($key, $value = null) * * @param array $attributes The attributes to set. * - * @return static */ - public function setAttributes(array $attributes) + public function setAttributes(array $attributes): static { $this->attributes = ArrayUtils::convertToAssoc($attributes); @@ -177,9 +171,8 @@ public function setAttributes(array $attributes) * * @param string $key The name of the attribute to delete. * - * @return static */ - public function deleteAttribute($key) + public function deleteAttribute(string $key): static { unset($this->attributes[$key]); @@ -189,13 +182,13 @@ public function deleteAttribute($key) /** * Adds tag content. * - * @param mixed $content The content value. + * @param mixed $content The content value. * - * @param mixed $key Optional. Used for uniqueness. + * @param mixed|null $key Optional. Used for uniqueness. * * @return $this */ - public function addContent($content, $key = null) + public function addContent(mixed $content, mixed $key = null): static { if ($key === null) { $this->content [] = $content; @@ -211,9 +204,8 @@ public function addContent($content, $key = null) * * @param mixed $content The content of the tag. * - * @return static */ - public function setContent($content) + public function setContent(mixed $content): static { $this->content = []; @@ -223,9 +215,8 @@ public function setContent($content) /** * Serializes the tag to string. * - * @return string */ - public function serialize() + public function serialize(): string { $closingChar = static::IS_VOID && $this->config->tag->voidClosingSlash ? '/>' : '>'; @@ -246,9 +237,8 @@ public function serialize() * @param array $additionalContent The additional content. * @param bool $prependAdditionalContent Whether to prepend additional content (instead of append). * - * @return string */ - public function serializeContent($additionalContent = [], $prependAdditionalContent = false) + public function serializeContent(array $additionalContent = [], bool $prependAdditionalContent = false): string { $content = $prependAdditionalContent ? ArrayUtils::mergeNonEmpty( $additionalContent, @@ -266,9 +256,8 @@ public function serializeContent($additionalContent = [], $prependAdditionalCont * * @param array $attributes Optional. Additional attributes to add without affecting the tag state. * - * @return string */ - public function serializeAttributes($attributes = []) + public function serializeAttributes(array $attributes = []): string { $classAttr = ! empty($this->classes) ? ['class' => implode(' ', array_keys($this->classes))] : []; $allAttributes = array_merge($classAttr, $this->attributes, $attributes); @@ -304,9 +293,8 @@ public function serializeAttributes($attributes = []) * @param string $name The name of the attribute * @param mixed $value The value of the attribute * - * @return string */ - protected function serializeAttribute($name, $value) + protected function serializeAttribute(string $name, mixed $value): string { if (empty($value)) { return $name; @@ -328,9 +316,8 @@ protected function serializeAttribute($name, $value) * * @param array $params The input parameters. * - * @return array */ - protected static function collectAttributesFromParams($params) + protected static function collectAttributesFromParams(array $params): array { $attributes = ArrayUtils::pop($params, 'attributes', []); @@ -349,11 +336,10 @@ protected static function collectAttributesFromParams($params) /** * Returns Configuration for fromParams function. * - * @return Configuration */ - protected static function fromParamsDefaultConfig() + protected static function fromParamsDefaultConfig(): Configuration { - $configuration = (new Configuration(Configuration::instance())); + $configuration = new Configuration(Configuration::instance()); # set v1 defaults $configuration->tag->quotesType = self::SINGLE_QUOTES; $configuration->tag->sortAttributes = true; @@ -373,7 +359,7 @@ protected static function fromParamsDefaultConfig() * * @internal */ - public function setTagConfig($configKey, $configValue) + public function setTagConfig($configKey, $configValue): static { $this->config->tag->setTagConfig($configKey, $configValue); @@ -383,9 +369,8 @@ public function setTagConfig($configKey, $configValue) /** * Serializes the tag to string. * - * @return string */ - public function toTag() + public function toTag(): string { return $this->serialize(); } diff --git a/src/Tag/ClientHintsMetaTag.php b/src/Tag/ClientHintsMetaTag.php index c59ce6a6..508d48e8 100644 --- a/src/Tag/ClientHintsMetaTag.php +++ b/src/Tag/ClientHintsMetaTag.php @@ -24,17 +24,17 @@ class ClientHintsMetaTag extends BaseTag /** * @var string NAME Mandatory. The name of the tag. */ - const NAME = 'meta'; + public const NAME = 'meta'; /** * @var bool IS_VOID Indicates whether the tag is a void (self-closed, without body) tag. */ - const IS_VOID = true; + protected const IS_VOID = true; /** * @var array $attributes An array of tag attributes. */ - protected $attributes = [ + protected array $attributes = [ 'http-equiv' => 'Accept-CH', 'content' => 'DPR, Viewport-Width, Width', ]; diff --git a/src/Tag/FormInputTag.php b/src/Tag/FormInputTag.php index 5c0497fa..264509b3 100644 --- a/src/Tag/FormInputTag.php +++ b/src/Tag/FormInputTag.php @@ -19,15 +19,13 @@ */ class FormInputTag extends BaseTag { - const NAME = 'input'; - const IS_VOID = true; + public const NAME = 'input'; + protected const IS_VOID = true; /** * @var array $attributes An array of tag attributes. */ - protected $attributes = [ - 'type' => 'hidden', - ]; + protected array $attributes = ['type' => 'hidden']; /** * FormInputTag constructor. @@ -35,7 +33,7 @@ class FormInputTag extends BaseTag * @param string $name The name of the input tag. * @param mixed $value The value of the input tag. */ - public function __construct($name, $value) + public function __construct($name, mixed $value) { parent::__construct(); diff --git a/src/Tag/FormTag.php b/src/Tag/FormTag.php index 387a914e..ab35d1b4 100644 --- a/src/Tag/FormTag.php +++ b/src/Tag/FormTag.php @@ -31,12 +31,12 @@ */ class FormTag extends BaseConfigurableApiTag { - const NAME = 'form'; + public const NAME = 'form'; /** * @var array $attributes An array of tag attributes. */ - protected $attributes = [ + protected array $attributes = [ 'enctype' => 'multipart/form-data', 'method' => HttpMethod::POST, ]; @@ -46,11 +46,9 @@ class FormTag extends BaseConfigurableApiTag * * @param array $attributes Optional. Additional attributes to add without affecting the tag state. * - * @return string - * * @internal */ - public function serializeAttributes($attributes = []) + public function serializeAttributes(array $attributes = []): string { $attributes['action'] = $this->uploadApi->getUploadUrl($this->assetType); @@ -71,17 +69,16 @@ public function serializeAttributes($attributes = []) * @param array $additionalContent The additional content. * @param bool $prependAdditionalContent Whether to prepend additional content (instead of append). * - * @return string * * @internal */ - public function serializeContent($additionalContent = [], $prependAdditionalContent = false) + public function serializeContent(array $additionalContent = [], bool $prependAdditionalContent = false): string { $inputTags = []; $uploadParams = $this->getUploadParams(); foreach ($uploadParams as $key => $value) { - $inputTags[] = (string)(new FormInputTag($key, $value)); + $inputTags[] = (string)new FormInputTag($key, $value); } return parent::serializeContent( diff --git a/src/Tag/ImageTag.php b/src/Tag/ImageTag.php index 2b3c0f90..224f4bdf 100644 --- a/src/Tag/ImageTag.php +++ b/src/Tag/ImageTag.php @@ -15,30 +15,29 @@ /** * Generates an HTML `` tag with the `src` attribute set to the transformation URL, optional `srcset` and other * specified attributes. - * + * * For more information, see the [PHP SDK guide](https://cloudinary.com/documentation/php_image_manipulation#deliver_and_transform_images). * * @api */ class ImageTag extends BaseImageTag { - const NAME = 'img'; - const IS_VOID = true; + public const NAME = 'img'; + public const IS_VOID = true; - const BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; - const RESPONSIVE_CLASS = 'cld-responsive'; - const HI_DPI_CLASS = 'cld-hidpi'; + public const BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; + protected const RESPONSIVE_CLASS = 'cld-responsive'; + protected const HI_DPI_CLASS = 'cld-hidpi'; /** * Serializes the tag attributes. * * @param array $attributes Optional. Additional attributes to add without affecting the tag state. * - * @return string */ - public function serializeAttributes($attributes = []) + public function serializeAttributes(array $attributes = []): string { - if (($this->config->tag->responsive || $this->config->tag->hidpi) && ! (bool)$this->config->tag->clientHints) { + if (($this->config->tag->responsive || $this->config->tag->hidpi) && ! $this->config->tag->clientHints) { $attributes['data-src'] = $this->image; $this->addClass($this->config->tag->responsive ? self::RESPONSIVE_CLASS : self::HI_DPI_CLASS); diff --git a/src/Tag/ImageTagDeliveryTypeTrait.php b/src/Tag/ImageTagDeliveryTypeTrait.php index 65418946..98b73542 100644 --- a/src/Tag/ImageTagDeliveryTypeTrait.php +++ b/src/Tag/ImageTagDeliveryTypeTrait.php @@ -24,11 +24,10 @@ trait ImageTagDeliveryTypeTrait * Static builder for uploaded asset image tag. * * @param string $publicId The public ID of the asset. - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function upload($publicId, $configuration = null) + public static function upload(string $publicId, Configuration|array|string|null $configuration = null): static { return new static(Image::upload($publicId, $configuration)); } @@ -36,12 +35,10 @@ public static function upload($publicId, $configuration = null) /** * Static builder for fetch image tag (from URL). * - * @param string $url - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function fetch($url, $configuration = null) + public static function fetch(string $url, Configuration|array|string|null $configuration = null): static { return new static(Image::fetch($url, $configuration)); } @@ -49,12 +46,10 @@ public static function fetch($url, $configuration = null) /** * Static builder for facebook profile picture tag. * - * @param string $facebookId - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function facebook($facebookId, $configuration = null) + public static function facebook(string $facebookId, Configuration|array|string|null $configuration = null): static { return new static(Image::facebook($facebookId, $configuration)); } @@ -62,12 +57,10 @@ public static function facebook($facebookId, $configuration = null) /** * Static builder for gravatar profile picture tag. * - * @param string $email - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function gravatar($email, $configuration = null) + public static function gravatar(string $email, Configuration|array|string|null $configuration = null): static { return new static(Image::gravatar($email, $configuration)); } @@ -75,12 +68,10 @@ public static function gravatar($email, $configuration = null) /** * Static builder for twitter profile picture tag. * - * @param string $userId - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function twitter($userId, $configuration = null) + public static function twitter(string $userId, Configuration|array|string|null $configuration = null): static { return new static(Image::twitter($userId, $configuration)); } @@ -88,12 +79,10 @@ public static function twitter($userId, $configuration = null) /** * Static builder for twitter profile picture by name. * - * @param string $username - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function twitterName($username, $configuration = null) + public static function twitterName(string $username, Configuration|array|string|null $configuration = null): static { return new static(Image::twitterName($username, $configuration)); } @@ -101,12 +90,10 @@ public static function twitterName($username, $configuration = null) /** * Static builder for the thumbnail of the YouTube video. * - * @param string $videoId - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function youTube($videoId, $configuration = null) + public static function youTube(string $videoId, Configuration|array|string|null $configuration = null): static { return new static(Image::youTube($videoId, $configuration)); } @@ -114,12 +101,10 @@ public static function youTube($videoId, $configuration = null) /** * Static builder for the thumbnail of the YouTube video. * - * @param string $videoId - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function hulu($videoId, $configuration = null) + public static function hulu(string $videoId, Configuration|array|string|null $configuration = null): static { return new static(Image::hulu($videoId, $configuration)); } @@ -127,12 +112,10 @@ public static function hulu($videoId, $configuration = null) /** * Static builder for the thumbnail of the Vimeo video. * - * @param string $videoId - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function vimeo($videoId, $configuration = null) + public static function vimeo(string $videoId, Configuration|array|string|null $configuration = null): static { return new static(Image::vimeo($videoId, $configuration)); } @@ -140,12 +123,10 @@ public static function vimeo($videoId, $configuration = null) /** * Static builder for the thumbnail of the animoto video. * - * @param string $videoId - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function animoto($videoId, $configuration = null) + public static function animoto(string $videoId, Configuration|array|string|null $configuration = null): static { return new static(Image::animoto($videoId, $configuration)); } @@ -153,25 +134,23 @@ public static function animoto($videoId, $configuration = null) /** * Static builder for the thumbnail of the World Star Hip Hop video. * - * @param string $videoId - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function worldStarHipHop($videoId, $configuration = null) - { + public static function worldStarHipHop( + string $videoId, + Configuration|array|string|null $configuration = null + ): static { return new static(Image::worldStarHipHop($videoId, $configuration)); } /** * Static builder for the thumbnail of the DailyMotion video. * - * @param string $videoId - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function dailyMotion($videoId, $configuration = null) + public static function dailyMotion(string $videoId, Configuration|array|string|null $configuration = null): static { return new static(Image::dailyMotion($videoId, $configuration)); } @@ -179,12 +158,10 @@ public static function dailyMotion($videoId, $configuration = null) /** * Static builder for sprite tag. * - * @param string $tag - * @param Configuration|string|array|null $configuration The Configuration source. + * @param array|string|Configuration|null $configuration The Configuration source. * - * @return static */ - public static function sprite($tag, $configuration = null) + public static function sprite(string $tag, Configuration|array|string|null $configuration = null): static { return new static(Image::sprite($tag, $configuration)); } diff --git a/src/Tag/JsConfigTag.php b/src/Tag/JsConfigTag.php index fe93228a..9fe12b7a 100644 --- a/src/Tag/JsConfigTag.php +++ b/src/Tag/JsConfigTag.php @@ -26,12 +26,12 @@ */ class JsConfigTag extends BaseTag { - const NAME = 'script'; + public const NAME = 'script'; /** * @var array $attributes An array of tag attributes. */ - protected $attributes = [ + protected array $attributes = [ 'type' => 'text/javascript', ]; diff --git a/src/Tag/PictureSourceTag.php b/src/Tag/PictureSourceTag.php index 9d89b14e..f1762e42 100644 --- a/src/Tag/PictureSourceTag.php +++ b/src/Tag/PictureSourceTag.php @@ -31,31 +31,36 @@ */ class PictureSourceTag extends BaseImageTag { - const NAME = 'source'; + public const NAME = 'source'; - const IS_VOID = true; + public const IS_VOID = true; /** * @var Media $media The media query attribute. */ - protected $media; + protected Media $media; /** * @var mixed $sizes The sizes attribute. */ - protected $sizes; + protected mixed $sizes; /** * PictureSourceTag constructor. * * @param string|Image $source The Public ID or Image instance - * @param int $minWidth The minimum width of the screen. - * @param int $maxWidth The maximum width of the screen. - * @param string $sizes The sizes attribute value. - * @param Configuration|string|array|null $configuration The Configuration source. + * @param int|null $minWidth The minimum width of the screen. + * @param int|null $maxWidth The maximum width of the screen. + * @param string|null $sizes The sizes attribute value. + * @param array|string|Configuration|null $configuration The Configuration source. */ - public function __construct($source, $minWidth = null, $maxWidth = null, $sizes = null, $configuration = null) - { + public function __construct( + string|Image $source, + ?int $minWidth = null, + ?int $maxWidth = null, + ?string $sizes = null, + Configuration|array|string|null $configuration = null + ) { parent::__construct($source, $configuration); $this->sizes($sizes); @@ -65,12 +70,11 @@ public function __construct($source, $minWidth = null, $maxWidth = null, $sizes /** * Sets the media query $minWidth and $maxWidth. * - * @param int $minWidth The minimum width of the screen. - * @param int $maxWidth The maximum width of the screen. + * @param int|null $minWidth The minimum width of the screen. + * @param int|null $maxWidth The maximum width of the screen. * - * @return PictureSourceTag */ - public function media($minWidth = null, $maxWidth = null) + public function media(?int $minWidth = null, ?int $maxWidth = null): static { $this->media = new Media($minWidth, $maxWidth, $this->config); @@ -83,11 +87,9 @@ public function media($minWidth = null, $maxWidth = null) /** * Sets the sizes tag attribute. * - * @param string $sizes The sizes attribute value. - * - * @return PictureSourceTag + * @param string|null $sizes The sizes attribute value. */ - public function sizes($sizes = null) + public function sizes(?string $sizes = null): static { if ($sizes && $this->config->responsiveBreakpoints->autoOptimalBreakpoints) { throw new \InvalidArgumentException("Invalid input: sizes must not be used with autoOptimalBreakpoints"); @@ -103,9 +105,8 @@ public function sizes($sizes = null) * * @param array $attributes Optional. Additional attributes to add without affecting the tag state. * - * @return string */ - public function serializeAttributes($attributes = []) + public function serializeAttributes(array $attributes = []): string { if (! empty($this->srcset->getBreakpoints())) { $attributes['srcset'] = $this->srcset; diff --git a/src/Tag/PictureTag.php b/src/Tag/PictureTag.php index 79900530..d9ba4c89 100644 --- a/src/Tag/PictureTag.php +++ b/src/Tag/PictureTag.php @@ -34,26 +34,26 @@ class PictureTag extends BaseTag { use ImageTagDeliveryTypeTrait; - const NAME = 'picture'; + public const NAME = 'picture'; /** * @var ImageTag $imageTag The fallback image tag of the picture tag. */ - public $imageTag; + public ImageTag $imageTag; /** * @var array of PictureSourceTag $sources */ - public $sources; + public array $sources; /** * PictureTag constructor. * - * @param string|Image $source The public ID or Image instance. - * @param array $sources The sources definitions. - * @param Configuration $configuration The configuration instance. + * @param string|Image $source The public ID or Image instance. + * @param array $sources The sources definitions. + * @param Configuration|null $configuration The configuration instance. */ - public function __construct($source, $sources, $configuration = null) + public function __construct($source, array $sources, ?Configuration $configuration = null) { parent::__construct($configuration); @@ -65,11 +65,10 @@ public function __construct($source, $sources, $configuration = null) /** * Sets the image of the picture. * - * @param mixed $image The public ID or Image asset. + * @param mixed $image The public ID or Image asset. * - * @return static */ - public function image($image) + public function image(mixed $image): static { $this->imageTag = new ImageTag(new Image($image, $this->config), $this->config); @@ -81,15 +80,14 @@ public function image($image) * * @param array $sourcesDefinitions The definitions of the sources. * - * @return static */ - public function setSources($sourcesDefinitions) + public function setSources(array $sourcesDefinitions): static { $this->sources = []; foreach ($sourcesDefinitions as $source) { if (is_array($source)) { - $sourceTag = new PictureSourceTag(ArrayUtils::get($source, 'image'), $this->config); + $sourceTag = new PictureSourceTag(ArrayUtils::get($source, 'image'), null, null, null, $this->config); $sourceTag->media(ArrayUtils::get($source, 'min_width'), ArrayUtils::get($source, 'max_width')); $sourceTag->sizes(ArrayUtils::get($source, 'sizes')); @@ -108,9 +106,8 @@ public function setSources($sourcesDefinitions) * @param array $additionalContent The additional content. * @param bool $prependAdditionalContent Whether to prepend additional content (instead of append). * - * @return string */ - public function serializeContent($additionalContent = [], $prependAdditionalContent = false) + public function serializeContent(array $additionalContent = [], bool $prependAdditionalContent = false): string { return parent::serializeContent( ArrayUtils::mergeNonEmpty( diff --git a/src/Tag/SpriteTag.php b/src/Tag/SpriteTag.php index 6456c1ed..8ae1cdc7 100644 --- a/src/Tag/SpriteTag.php +++ b/src/Tag/SpriteTag.php @@ -31,37 +31,39 @@ class SpriteTag extends BaseTag { use ImageTransformationTrait; - const NAME = 'link'; - const IS_VOID = true; + public const NAME = 'link'; + protected const IS_VOID = true; /** * @var array $attributes An array of tag attributes. */ - protected $attributes = [ - 'type' => 'text/css', - 'rel' => 'stylesheet', - // 'href' is set in constructor - ]; + protected array $attributes + = [ + 'type' => 'text/css', + 'rel' => 'stylesheet', + // 'href' is set in constructor + ]; /** * @var Image $image The sprite image of the tag. */ - public $image; + public Image $image; /** - * @var ImageTransformation $additionalTransformation Additional transformation to be applied on the tag image. + * @var ImageTransformation|null $additionalTransformation Additional transformation to be applied on the tag image. */ - public $additionalTransformation; + public ?ImageTransformation $additionalTransformation; /** * SpriteTag constructor. * - * @param string $tag - The sprite is created from all images with this tag. - * @param Configuration $configuration - * @param ImageTransformation $additionalTransformation + * @param string $tag - The sprite is created from all images with this tag. */ - public function __construct($tag, $configuration = null, $additionalTransformation = null) - { + public function __construct( + $tag, + ?Configuration $configuration = null, + ?ImageTransformation $additionalTransformation = null + ) { parent::__construct($configuration); $this->image($tag, $configuration); @@ -71,12 +73,11 @@ public function __construct($tag, $configuration = null, $additionalTransformati /** * Creates a new sprite tag from the provided public id and array of parameters. * - * @param string $tag The public ID of the asset. + * @param string $tag The public ID of the asset. * @param array $params The media asset parameters. * - * @return SpriteTag */ - public static function fromParams($tag, $params = []) + public static function fromParams(string $tag, array $params = []): SpriteTag { $spriteTag = new static($tag, self::fromParamsDefaultConfig()); @@ -89,12 +90,11 @@ public static function fromParams($tag, $params = []) /** * Creates the sprite image. * - * @param mixed $tag The tag that indicates which images to use in the sprite. - * @param Configuration $configuration The configuration instance. + * @param mixed $tag The tag that indicates which images to use in the sprite. + * @param Configuration|null $configuration The configuration instance. * - * @return static */ - public function image($tag, $configuration = null) + public function image(mixed $tag, ?Configuration $configuration = null): static { $this->image = Image::sprite($tag, $configuration); @@ -106,9 +106,8 @@ public function image($tag, $configuration = null) * * @param array $attributes Optional. Additional attributes to add without affecting the tag state. * - * @return string */ - public function serializeAttributes($attributes = []) + public function serializeAttributes(array $attributes = []): string { $attributes['href'] = $this->image->toUrl($this->additionalTransformation); diff --git a/src/Tag/Tag.php b/src/Tag/Tag.php index 74c1ea32..ec3f3490 100644 --- a/src/Tag/Tag.php +++ b/src/Tag/Tag.php @@ -32,73 +32,79 @@ abstract class Tag /** * Creates a new image tag. * - * @param string|Image $image The Public ID or the Image instance. - * @param Configuration $configuration The configuration instance. - * @param ImageTransformation $additionalTransformation The additional transformation. + * @param string|Image $image The Public ID or the Image instance. + * @param Configuration|null $configuration The configuration instance. + * @param ImageTransformation|null $additionalTransformation The additional transformation. * - * @return ImageTag */ - public static function imageTag($image, $configuration = null, $additionalTransformation = null) - { + public static function imageTag( + string|Image $image, + ?Configuration $configuration = null, + ?ImageTransformation $additionalTransformation = null + ): ImageTag { return new ImageTag($image, $configuration, $additionalTransformation); } /** * Creates a new video tag. * - * @param string|Video $video The public ID or Video instance. - * @param array|null $sources The tag sources definition. - * @param Configuration $configuration The configuration instance. + * @param string|Video $video The public ID or Video instance. + * @param array|null $sources The tag sources definition. + * @param Configuration|null $configuration The configuration instance. * - * @return VideoTag */ - public static function videoTag($video, $sources = null, $configuration = null) - { + public static function videoTag( + Video|string $video, + ?array $sources = null, + ?Configuration $configuration = null + ): VideoTag { return new VideoTag($video, $sources, $configuration); } /** * Generates an HTML `` tag based on a captured frame from the specified video source. * - * @param string|Video $video The public ID of the video. - * @param Configuration $configuration The configuration instance. + * @param string|Video $video The public ID of the video. + * @param Configuration|null $configuration The configuration instance. * - * @return VideoThumbnailTag * * @see VideoThumbnailTag */ - public static function videoThumbnailTag($video, $configuration = null) - { + public static function videoThumbnailTag( + Video|string $video, + ?Configuration $configuration = null + ): VideoThumbnailTag { return new VideoThumbnailTag($video, $configuration); } /** * Generates an HTML `` tag containing `` and `` tags. * - * @param string|Image $image The public ID or Image instance. - * @param array $sources The sources definitions. - * @param Configuration $configuration The configuration instance. + * @param string|Image $image The public ID or Image instance. + * @param array $sources The sources definitions. + * @param Configuration|null $configuration The configuration instance. * * - * @return PictureTag * * @see PictureTag */ - public static function pictureTag($image, $sources, $configuration = null) - { + public static function pictureTag( + string|Image $image, + array $sources, + ?Configuration $configuration = null + ): PictureTag { return new PictureTag($image, $sources, $configuration); } /** * Generates an HTML `