diff --git a/.prettierrc b/.prettierrc index 3088371..8121cab 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,5 +1,6 @@ { - "phpVersion": "8.1", - "singleQuote": true, - "trailingCommaPHP": true + "plugins": ["@prettier/plugin-php"], + "phpVersion": "8.1", + "trailingComma": "all", + "singleQuote": true } diff --git a/package.json b/package.json index 2b5b7a5..60c7341 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,9 @@ { "dependencies": { - "@prettier/plugin-php": "^0.19.7", + "@prettier/plugin-php": "^0.22.1", "husky": "^3.0.5", "lint-staged": "^9.4.0", - "prettier": "^1.18.2" + "prettier": "^3.1.1" }, "scripts": { "stan": "vendor/bin/phpstan analyse src/ -c phpstan.neon", diff --git a/src/Collection/Collection.php b/src/Collection/Collection.php index 3dbcc60..c348879 100644 --- a/src/Collection/Collection.php +++ b/src/Collection/Collection.php @@ -9,11 +9,7 @@ * * @author Florent Clerc */ -class Collection implements - \IteratorAggregate, - \Serializable, - \Countable, - \ArrayAccess +class Collection implements \IteratorAggregate, \Serializable, \Countable, \ArrayAccess { /** * The elements of the collection. @@ -38,7 +34,7 @@ class Collection implements */ public function __construct( array $elements = [], - array $extraProperties = [] + array $extraProperties = [], ) { $this->elements = $elements; $this->extraProperties = $extraProperties; @@ -53,8 +49,6 @@ public function __serialize(): array } /** - * {@inheritdoc} - * * @param string $values */ public function __unserialize($values): void @@ -75,8 +69,6 @@ public function toArray(): array } /** - * {@inheritdoc} - * * @deprecated `serialize` method is deprecated, `__serialize` is used instead. See https://php.watch/versions/8.1/serializable-deprecated */ public function serialize(): string @@ -92,9 +84,6 @@ public function unserialize($data): void $this->__unserialize($data); } - /** - * {@inheritdoc} - */ public function count(): int { return count($this->elements); @@ -109,10 +98,7 @@ public function getTotalItems(): int } /** - * {@inheritdoc} - * * @param mixed|null $offset - * @param mixed $value */ public function offsetSet($offset, $value): void { @@ -124,8 +110,6 @@ public function offsetSet($offset, $value): void } /** - * {@inheritdoc} - * * @param mixed|null $offset */ public function offsetExists($offset): bool @@ -134,8 +118,6 @@ public function offsetExists($offset): bool } /** - * {@inheritdoc} - * * @param mixed|null $offset */ public function offsetUnset($offset): void @@ -144,8 +126,6 @@ public function offsetUnset($offset): void } /** - * {@inheritdoc} - * * @param mixed|null $offset * * @return mixed|null @@ -155,9 +135,6 @@ public function offsetGet($offset): mixed return $this->elements[$offset] ?? null; } - /** - * {@inheritdoc} - */ public function getIterator(): \ArrayIterator { return new \ArrayIterator($this->elements); @@ -187,13 +164,13 @@ public function getIntExtraProperty(string $key): ?int /** * return the value of an extra property - * - * @return mixed */ - public function getExtraProperty(string $key) + public function getExtraProperty(string $key): mixed { if (isset($this->extraProperties[$key])) { return $this->extraProperties[$key]; } + + return null; } } diff --git a/src/EntityRepository.php b/src/EntityRepository.php index 65cde95..c6ea9d0 100644 --- a/src/EntityRepository.php +++ b/src/EntityRepository.php @@ -59,7 +59,7 @@ public function __construct( SdkClient $sdkClient, RestClient $restClient, UnitOfWork $unitOfWork, - string $entityName + string $entityName, ) { $this->sdk = $sdkClient; $this->restClient = $restClient; @@ -86,12 +86,18 @@ public function __call(string $method, array $arguments) break; default: - throw new \BadMethodCallException('Undefined method \'' . $method . '\'. The method name must start with - either findBy or findOneBy!'); + throw new \BadMethodCallException( + 'Undefined method \'' . + $method . + '\'. The method name must start with + either findBy or findOneBy!', + ); } if (empty($arguments)) { - throw new SdkException('You need to pass a parameter to ' . $method); + throw new SdkException( + 'You need to pass a parameter to ' . $method, + ); } $mapping = $this->sdk->getMapping(); @@ -130,7 +136,7 @@ public function __call(string $method, array $arguments) if (null !== $hydratedData) { $this->unitOfWork->registerClean( $identifier, - $hydratedData + $hydratedData, ); } $this->saveToCache($identifier, $hydratedData); @@ -201,7 +207,11 @@ public function findAll(): Collection // if entityList is found in cache, return it if (false !== $entityListFromCache) { if (!$entityListFromCache instanceof Collection) { - throw new \RuntimeException('Entity list in cache should be an instance of ' . Collection::class . '. This should not happen.'); + throw new \RuntimeException( + 'Entity list in cache should be an instance of ' . + Collection::class . + '. This should not happen.', + ); } return $entityListFromCache; @@ -219,7 +229,9 @@ public function findAll(): Collection // then cache each entity from list foreach ($entityList as $entity) { if (!is_object($entity)) { - throw new \RuntimeException("Entity should be an object. This should not happen."); + throw new \RuntimeException( + 'Entity should be an object. This should not happen.', + ); } $identifier = $entity->{$this->getClassMetadata()->getIdGetter()}(); @@ -248,14 +260,14 @@ public function remove(object $model): void public function update( object $model, array $serializationContext = [], - array $queryParams = [] + array $queryParams = [], ): object { $identifier = $model->{$this->getClassMetadata()->getIdGetter()}(); $serializer = $this->sdk->getSerializer(); $newSerializedModel = $serializer->serialize( $model, $this->entityName, - $serializationContext + $serializationContext, ); $oldModel = $this->unitOfWork->getDirtyEntity($identifier); @@ -263,12 +275,12 @@ public function update( $oldSerializedModel = $serializer->serialize( $oldModel, $this->entityName, - $serializationContext + $serializationContext, ); $newSerializedModel = $this->unitOfWork->getDirtyData( $newSerializedModel, $oldSerializedModel, - $this->getClassMetadata() + $this->getClassMetadata(), ); } @@ -283,7 +295,9 @@ public function update( $out = $hydrator->hydrate($data, $this->entityName); if (null === $out) { - throw new HydratorException("Unable to convert data from PUT request ({$path}) to an instance of {$this->entityName}. Maybe you have a custom hydrator returning null?"); + throw new HydratorException( + "Unable to convert data from PUT request ({$path}) to an instance of {$this->entityName}. Maybe you have a custom hydrator returning null?", + ); } return $out; @@ -292,7 +306,7 @@ public function update( public function persist( object $model, array $serializationContext = [], - array $queryParams = [] + array $queryParams = [], ): object { $mapping = $this->sdk->getMapping(); $prefix = $mapping->getIdPrefix(); @@ -308,17 +322,20 @@ public function persist( $diff = $this->unitOfWork->getDirtyData( $newSerializedModel, $oldSerializedModel, - $this->getClassMetadata() + $this->getClassMetadata(), ); $data = $this->restClient->post( $this->addQueryParameter($path, $queryParams), - $diff + $diff, ); $data = $this->assertNotObject($data, __METHOD__); if (null === $data) { - throw new RestException("No data found after sending a `POST` request to {$path}. Did the server returned a 4xx or 5xx status code?", $path); + throw new RestException( + "No data found after sending a `POST` request to {$path}. Did the server returned a 4xx or 5xx status code?", + $path, + ); } $hydrator = $this->sdk->getModelHydrator(); @@ -326,7 +343,9 @@ public function persist( $out = $hydrator->hydrate($data, $this->entityName); if (null === $out) { - throw new HydratorException("Unable to convert data from POST request ({$path}) to an instance of {$this->entityName}. Maybe you have a custom hydrator returning null?"); + throw new HydratorException( + "Unable to convert data from POST request ({$path}) to an instance of {$this->entityName}. Maybe you have a custom hydrator returning null?", + ); } return $out; @@ -343,7 +362,9 @@ protected function fetchFromCache(string $key): object|false $cacheData = $cacheItem->get(); if (!is_object($cacheData)) { - throw new \RuntimeException('Cache data should be an object. This should not happen.'); + throw new \RuntimeException( + 'Cache data should be an object. This should not happen.', + ); } return $cacheData; @@ -390,7 +411,7 @@ protected function removeFromCache(string $key): bool protected function addQueryParameter( string $path, - array $params = [] + array $params = [], ): string { if (empty($params)) { return $path; @@ -405,7 +426,7 @@ private function convertQueryParameters(array $queryParameters): array return array_map(function ($item) use ($mapping) { if (is_object($item)) { - $classname = get_class($item); + $classname = $item::class; if ($mapping->hasClassMetadata($classname)) { $idGetter = $mapping @@ -425,7 +446,9 @@ private function normalizeCacheKey(string $key): string $out = preg_replace('~[\\/\{\}@:\(\)]~', '_', $key); if (null === $out) { - throw new \RuntimeException('Unable to normalize cache key. This should not happen.'); + throw new \RuntimeException( + 'Unable to normalize cache key. This should not happen.', + ); } return $out; @@ -451,9 +474,11 @@ private function assertArray($data, string $methodName): array return $data; } - $type = null === $data ? 'null' : get_class($data); + $type = null === $data ? 'null' : $data::class; - throw new UnexpectedTypeException("Return of method {$methodName} should be an array. {$type} given."); + throw new UnexpectedTypeException( + "Return of method {$methodName} should be an array. {$type} given.", + ); } /** @@ -467,8 +492,10 @@ private function assertNotObject($data, string $methodName) return $data; } - $type = get_class($data); + $type = $data::class; - throw new UnexpectedTypeException("Return of method {$methodName} should be an array. {$type} given."); + throw new UnexpectedTypeException( + "Return of method {$methodName} should be an array. {$type} given.", + ); } } diff --git a/src/Exception/RestException.php b/src/Exception/RestException.php index e42352a..01c8ee9 100644 --- a/src/Exception/RestException.php +++ b/src/Exception/RestException.php @@ -4,7 +4,6 @@ namespace Mapado\RestClientSdk\Exception; -use Exception; use GuzzleHttp\Exception\RequestException; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -41,7 +40,7 @@ public function __construct( string $path, array $params = [], int $code = 0, - ?Exception $previous = null + \Exception $previous = null, ) { parent::__construct($message, $code, $previous); $this->path = $path; diff --git a/src/Helper/ArrayHelper.php b/src/Helper/ArrayHelper.php index 51fc1b2..7790ded 100644 --- a/src/Helper/ArrayHelper.php +++ b/src/Helper/ArrayHelper.php @@ -14,15 +14,11 @@ class ArrayHelper { /** * Get an item from an array using "dot" notation. - * - * @param mixed $default - * - * @return mixed */ public static function arrayGet( array $array, ?string $key, - $default = null + mixed $default = null, ): mixed { if (null === $key) { return $array; @@ -76,7 +72,7 @@ public static function arrayDot(array $array, string $prepend = ''): array if (is_array($value) && !empty($value)) { $results = array_merge( $results, - static::arrayDot($value, $prepend . $key . '.') + static::arrayDot($value, $prepend . $key . '.'), ); } else { $results[$prepend . $key] = $value; @@ -88,11 +84,11 @@ public static function arrayDot(array $array, string $prepend = ''): array public static function arrayDiffAssocRecursive( array $array1, - array $array2 + array $array2, ): array { return array_diff_assoc( static::arrayDot($array1), - static::arrayDot($array2) + static::arrayDot($array2), ); } @@ -103,12 +99,8 @@ public static function arraySame(array $array1, array $array2): bool /** * Return the default value of the given value. - * - * @param mixed $value - * - * @return mixed */ - public static function value($value) + public static function value(mixed $value): mixed { return $value instanceof \Closure ? $value() : $value; } diff --git a/src/Mapping.php b/src/Mapping.php index a11d7c9..3c3952c 100644 --- a/src/Mapping.php +++ b/src/Mapping.php @@ -92,9 +92,7 @@ public function getModelName(string $key): string */ public function getMappingKeys(): array { - return array_map(function (ClassMetadata $classMetadata) { - return $classMetadata->getKey(); - }, $this->classMetadataList); + return array_map(fn (ClassMetadata $classMetadata) => $classMetadata->getKey(), $this->classMetadataList); } /** @@ -126,7 +124,7 @@ public function getKeyFromModel(string $modelName): string } throw new MappingException( - 'Model name ' . $modelName . ' not found in mapping' + 'Model name ' . $modelName . ' not found in mapping', ); } @@ -201,7 +199,7 @@ private function parseKeyFromId(string $id): ?string private function checkMappingExistence( string $key, - bool $checkModelName = false + bool $checkModelName = false, ): void { if (empty($key)) { throw new MappingException('key is not set'); @@ -215,7 +213,7 @@ private function checkMappingExistence( if ($checkModelName) { if (empty($metadata->getModelName())) { throw new MappingException( - $key . ' key is mapped but the model name is empty' + $key . ' key is mapped but the model name is empty', ); } } @@ -224,8 +222,8 @@ private function checkMappingExistence( private function removePrefix(string $value): string { if ( - $this->idPrefixLength > 0 && - 0 === mb_strpos($value, $this->idPrefix) + $this->idPrefixLength > 0 + && 0 === mb_strpos($value, $this->idPrefix) ) { return mb_substr($value, $this->idPrefixLength); } diff --git a/src/Mapping/Attribute.php b/src/Mapping/Attribute.php index 84b8edb..3ade600 100644 --- a/src/Mapping/Attribute.php +++ b/src/Mapping/Attribute.php @@ -36,9 +36,9 @@ class Attribute */ public function __construct( string $serializedKey, - ?string $attributeName = null, - ?string $type = null, - bool $isIdentifier = false + string $attributeName = null, + string $type = null, + bool $isIdentifier = false, ) { if (empty($serializedKey)) { throw new \InvalidArgumentException('attribute name must be set'); diff --git a/src/Mapping/ClassMetadata.php b/src/Mapping/ClassMetadata.php index 0fe1c6a..138e451 100644 --- a/src/Mapping/ClassMetadata.php +++ b/src/Mapping/ClassMetadata.php @@ -64,7 +64,7 @@ class ClassMetadata public function __construct( string $key, string $modelName, - ?string $repositoryName = null + string $repositoryName = null, ) { $this->key = $key; $this->modelName = $modelName; @@ -83,6 +83,7 @@ public function getModelName(): string /** * @param class-string $modelName + * * @return $this */ public function setModelName(string $modelName): self @@ -124,8 +125,8 @@ public function getIdentifierAttribute(): Attribute sprintf( 'Ressource "%s" does not contains an identifier. You can not call %s. You may want to call `hasIdentifierAttribute` before.', $this->modelName, - __METHOD__ - ) + __METHOD__, + ), ); } @@ -158,8 +159,8 @@ public function setAttributeList($attributeList): self sprintf( 'Class metadata for model "%s" already has an identifier named "%s". Only one identifier is allowed.', $this->modelName, - $this->identifierAttribute->getSerializedKey() - ) + $this->identifierAttribute->getSerializedKey(), + ), ); } diff --git a/src/Mapping/Driver/AnnotationDriver.php b/src/Mapping/Driver/AnnotationDriver.php index 23c1da9..827150a 100644 --- a/src/Mapping/Driver/AnnotationDriver.php +++ b/src/Mapping/Driver/AnnotationDriver.php @@ -37,7 +37,7 @@ public function __construct(string $cachePath, bool $debug = false) $this->debug = $debug; AnnotationRegistry::registerFile( - __DIR__ . '/../Annotations/AllAnnotations.php' + __DIR__ . '/../Annotations/AllAnnotations.php', ); } @@ -57,12 +57,12 @@ public function loadDirectory(string $path): array new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $path, - \FilesystemIterator::SKIP_DOTS + \FilesystemIterator::SKIP_DOTS, ), - \RecursiveIteratorIterator::LEAVES_ONLY + \RecursiveIteratorIterator::LEAVES_ONLY, ), '/^.+\.php$/i', - \RecursiveRegexIterator::GET_MATCH + \RecursiveRegexIterator::GET_MATCH, ); $classes = []; @@ -116,19 +116,19 @@ public function loadClassname(string $classname): array * @throws \ReflectionException */ private function getClassMetadataForClassname( - string $classname + string $classname, ): ?ClassMetadata { $reader = new FileCacheReader( new AnnotationReader(), $this->cachePath, - $this->debug + $this->debug, ); $reflClass = new \ReflectionClass($classname); /** @var Annotations\Entity|null */ $classAnnotation = $reader->getClassAnnotation( $reflClass, - Annotations\Entity::class + Annotations\Entity::class, ); if (!$classAnnotation) { @@ -143,7 +143,7 @@ private function getClassMetadataForClassname( $propertyAnnotation = $this->getPropertyAnnotation( $reader, $property, - 'Attribute' + 'Attribute', ); if ($propertyAnnotation) { @@ -153,7 +153,7 @@ private function getClassMetadataForClassname( $propertyAnnotation->name, $property->getName(), $propertyAnnotation->type, - (bool) $isId + (bool) $isId, ); } else { // manage relations @@ -161,21 +161,21 @@ private function getClassMetadataForClassname( $relation = $this->getPropertyAnnotation( $reader, $property, - 'OneToMany' + 'OneToMany', ); if (!$relation) { /** @var Annotations\ManyToOne|null */ $relation = $this->getPropertyAnnotation( $reader, $property, - 'ManyToOne' + 'ManyToOne', ); } if ($relation) { $attributeList[] = new Attribute( $relation->name, - $property->getName() + $property->getName(), ); $targetEntity = $relation->targetEntity; @@ -184,14 +184,14 @@ private function getClassMetadataForClassname( mb_substr( $classname, 0, - mb_strrpos($classname, '\\') + 1 + mb_strrpos($classname, '\\') + 1, ) . $targetEntity; } $relationList[] = new Relation( $relation->name, $relation->type, - $targetEntity + $targetEntity, ); } } @@ -200,7 +200,7 @@ private function getClassMetadataForClassname( $classMetadata = new ClassMetadata( $classAnnotation->key, $classname, - $classAnnotation->getRepository() + $classAnnotation->getRepository(), ); $classMetadata->setAttributeList($attributeList); $classMetadata->setRelationList($relationList); @@ -214,7 +214,7 @@ private function getClassMetadataForClassname( private function getPropertyAnnotation( Reader $reader, \ReflectionProperty $property, - string $classname + string $classname, ): ?object { /** @var class-string $classname */ $classname = diff --git a/src/Mapping/Relation.php b/src/Mapping/Relation.php index 357ec56..f574195 100644 --- a/src/Mapping/Relation.php +++ b/src/Mapping/Relation.php @@ -32,7 +32,7 @@ class Relation public function __construct( string $serializedKey, string $type, - string $targetEntity + string $targetEntity, ) { $this->serializedKey = $serializedKey; $this->type = $type; diff --git a/src/Model/ModelHydrator.php b/src/Model/ModelHydrator.php index eb35515..3813817 100644 --- a/src/Model/ModelHydrator.php +++ b/src/Model/ModelHydrator.php @@ -71,9 +71,13 @@ public function hydrateList(?array $data, string $modelName): Collection } /** + * @template T + * * convert list of data as array to Collection containing entities * - * @param class-string $modelName + * @param class-string $modelName + * + * @return Collection */ private function deserializeAll(array $data, string $modelName): Collection { @@ -82,29 +86,43 @@ private function deserializeAll(array $data, string $modelName): Collection $itemList = ArrayHelper::arrayGet($data, $collectionKey); if (!is_array($itemList)) { - throw new \RuntimeException(sprintf( - 'Unable to deserialize collection, %s key not found in response', - $collectionKey - )); + throw new \RuntimeException( + sprintf( + 'Unable to deserialize collection, %s key not found in response', + $collectionKey, + ), + ); } - $itemList = array_map(fn (?array $member) => $this->deserialize($member, $modelName), $itemList); + $itemList = array_map( + fn(?array $member) => $this->deserialize($member, $modelName), + $itemList, + ); $extraProperties = array_filter( $data, - fn ($key) => $key !== $collectionKey, - \ARRAY_FILTER_USE_KEY + fn($key) => $key !== $collectionKey, + \ARRAY_FILTER_USE_KEY, ); /** @var class-string $collectionClassName */ $collectionClassName = $this->guessCollectionClassname($data); if (!class_exists($collectionClassName)) { - throw new \RuntimeException("Seem's like $collectionClassName does not exist"); + throw new \RuntimeException( + "Seem's like $collectionClassName does not exist", + ); + } + + $collection = new $collectionClassName($itemList, $extraProperties); + + if (!$collection instanceof Collection) { + throw new \RuntimeException( + "Seem's like $collectionClassName is not a collection class", + ); } - /** @var Collection */ - return new $collectionClassName($itemList, $extraProperties); + return $collection; } /** diff --git a/src/Model/Serializer.php b/src/Model/Serializer.php index c97ddbf..e2c2633 100644 --- a/src/Model/Serializer.php +++ b/src/Model/Serializer.php @@ -4,9 +4,7 @@ namespace Mapado\RestClientSdk\Model; -use DateTime; use DateTimeImmutable; -use DateTimeInterface; use libphonenumber\PhoneNumber; use libphonenumber\PhoneNumberFormat; use libphonenumber\PhoneNumberUtil; @@ -73,13 +71,13 @@ public function setSdk(SdkClient $sdk): self public function serialize( object $entity, string $modelName, - array $context = [] + array $context = [], ): array { $out = $this->recursiveSerialize($entity, $modelName, 0, $context); if (is_string($out)) { throw new \RuntimeException( - 'recursiveSerialize should return an array for level 0 of serialization. This should not happen.' + 'recursiveSerialize should return an array for level 0 of serialization. This should not happen.', ); } @@ -87,7 +85,6 @@ public function serialize( } /** - * @param array $data * @param class-string $className */ public function deserialize(array $data, string $className): object @@ -102,7 +99,7 @@ public function deserialize(array $data, string $className): object if (!is_object($instance)) { throw new \RuntimeException( - "The class $className is not instantiable" + "The class $className is not instantiable", ); } @@ -126,13 +123,13 @@ public function deserialize(array $data, string $className): object } elseif (is_array($value)) { $targetEntity = $relation->getTargetEntity(); $relationClassMetadata = $this->mapping->getClassMetadata( - $targetEntity + $targetEntity, ); if ($relation->isManyToOne()) { $value = $this->deserialize( $value, - $relationClassMetadata->getModelName() + $relationClassMetadata->getModelName(), ); } else { // One-To-Many association @@ -143,7 +140,7 @@ public function deserialize(array $data, string $className): object } elseif (is_array($item)) { $list[] = $this->deserialize( $item, - $relationClassMetadata->getModelName() + $relationClassMetadata->getModelName(), ); } } @@ -157,20 +154,20 @@ public function deserialize(array $data, string $className): object if ('datetime' === $attribute->getType()) { if (!is_string($value)) { throw new \RuntimeException( - "The value for $attributeName to cast to datetime value should be a string" + "The value for $attributeName to cast to datetime value should be a string", ); } $this->setDateTimeValue( $instance, $attributeName, - $value + $value, ); } else { $this->propertyAccessor->setValue( $instance, $attributeName, - $value + $value, ); } } @@ -190,7 +187,7 @@ public function deserialize(array $data, string $className): object if ($identifier) { $this->unitOfWork->registerClean( (string) $identifier, - $instance + $instance, ); } } @@ -205,11 +202,11 @@ public function deserialize(array $data, string $className): object */ private function resolveRealClassName( array $data, - string $className + string $className, ): string { if (!empty($data['@id'])) { $classMetadata = $this->mapping->tryGetClassMetadataById( - $data['@id'] + $data['@id'], ); if ($classMetadata) { @@ -228,7 +225,7 @@ private function recursiveSerialize( object $entity, string $modelName, int $level = 0, - array $context = [] + array $context = [], ) { $classMetadata = $this->mapping->getClassMetadata($modelName); @@ -252,16 +249,16 @@ private function recursiveSerialize( continue; } $relation = $classMetadata->getRelation( - $attribute->getSerializedKey() + $attribute->getSerializedKey(), ); $data = $entity->{$method}(); if ( - null === $data && - $relation && - $relation->isManyToOne() && - $level > 0 + null === $data + && $relation + && $relation->isManyToOne() + && $level > 0 ) { /* We only serialize the root many-to-one relations to prevent, hopefully, @@ -270,23 +267,23 @@ private function recursiveSerialize( CartItem entities explicitly bound to a null Cart instead of the created/updated Cart. */ continue; - } elseif ($data instanceof DateTimeInterface) { + } elseif ($data instanceof \DateTimeInterface) { $data = $data->format('c'); } elseif (is_object($data) && $data instanceof PhoneNumber) { $phoneNumberUtil = PhoneNumberUtil::getInstance(); $data = $phoneNumberUtil->format( $data, - PhoneNumberFormat::INTERNATIONAL + PhoneNumberFormat::INTERNATIONAL, ); } elseif ( - is_object($data) && - $relation && - $this->mapping->hasClassMetadata( - $relation->getTargetEntity() + is_object($data) + && $relation + && $this->mapping->hasClassMetadata( + $relation->getTargetEntity(), ) ) { $relationClassMetadata = $this->mapping->getClassMetadata( - $relation->getTargetEntity() + $relation->getTargetEntity(), ); if (!$relationClassMetadata->hasIdentifierAttribute()) { @@ -294,7 +291,7 @@ private function recursiveSerialize( $data, $relation->getTargetEntity(), $level + 1, - $context + $context, ); } else { $idAttribute = $relationClassMetadata->getIdentifierAttribute(); @@ -302,8 +299,8 @@ private function recursiveSerialize( 'get' . ucfirst($idAttribute->getAttributeName()); if ( - method_exists($data, $idGetter) && - $data->{$idGetter}() + method_exists($data, $idGetter) + && $data->{$idGetter}() ) { $data = $data->{$idGetter}(); } elseif ($relation->isManyToOne()) { @@ -311,7 +308,7 @@ private function recursiveSerialize( continue; } else { throw new SdkException( - 'Case not allowed for now' + 'Case not allowed for now', ); } } @@ -319,27 +316,27 @@ private function recursiveSerialize( } elseif (is_array($data)) { $newData = []; foreach ($data as $key => $item) { - if ($item instanceof DateTimeInterface) { + if ($item instanceof \DateTimeInterface) { $newData[$key] = $item->format('c'); } elseif ( - is_object($item) && - $relation && - $this->mapping->hasClassMetadata( - $relation->getTargetEntity() + is_object($item) + && $relation + && $this->mapping->hasClassMetadata( + $relation->getTargetEntity(), ) ) { $serializeRelation = - !empty($context['serializeRelations']) && - in_array( + !empty($context['serializeRelations']) + && in_array( $relation->getSerializedKey(), - $context['serializeRelations'] + $context['serializeRelations'], ); $newData[$key] = $this->recursiveSerialize( $item, $relation->getTargetEntity(), $level + 1, - ['serializeRelation' => $serializeRelation] + ['serializeRelation' => $serializeRelation], ); } else { $newData[$key] = $item; @@ -366,20 +363,20 @@ private function getClassMetadataFromId(string $id): ?ClassMetadata private function getClassMetadata(object $entity): ClassMetadata { - return $this->mapping->getClassMetadata(get_class($entity)); + return $this->mapping->getClassMetadata($entity::class); } private function throwIfAttributeIsNotWritable( object $instance, - string $attribute + string $attribute, ): void { if (!$this->propertyAccessor->isWritable($instance, $attribute)) { throw new MissingSetterException( sprintf( 'Property %s is not writable for class %s. Please make it writable. You can check the property-access documentation here : https://symfony.com/doc/current/components/property_access.html#writing-to-objects', $attribute, - get_class($instance) - ) + $instance::class, + ), ); } } @@ -387,25 +384,25 @@ private function throwIfAttributeIsNotWritable( private function setDateTimeValue( object $instance, string $attributeName, - string $value + string $value, ): void { try { $this->propertyAccessor->setValue( $instance, $attributeName, - new DateTime($value) + new \DateTime($value), ); } catch (InvalidArgumentException $e) { if ( false === mb_strpos( $e->getMessage(), - 'Expected argument of type "DateTimeImmutable", "DateTime" given' // symfony < 4.4 message - ) && - false === + 'Expected argument of type "DateTimeImmutable", "DateTime" given', // symfony < 4.4 message + ) + && false === mb_strpos( $e->getMessage(), - 'Expected argument of type "DateTimeImmutable", "instance of DateTime" given' // symfony >= 4.4 message + 'Expected argument of type "DateTimeImmutable", "instance of DateTime" given', // symfony >= 4.4 message ) ) { // not an issue with DateTimeImmutable, then rethrow exception @@ -416,7 +413,7 @@ private function setDateTimeValue( $this->propertyAccessor->setValue( $instance, $attributeName, - new DateTimeImmutable($value) + new \DateTimeImmutable($value), ); } } diff --git a/src/RestClient.php b/src/RestClient.php index 8c29536..33262d4 100644 --- a/src/RestClient.php +++ b/src/RestClient.php @@ -47,7 +47,7 @@ class RestClient public function __construct( ClientInterface $httpClient, - ?string $baseUrl = null + string $baseUrl = null, ) { $this->httpClient = $httpClient; $this->baseUrl = @@ -104,7 +104,7 @@ public function get(string $path, array $parameters = []) $path, [], 7, - $e + $e, ); } catch (TransferException $e) { throw new RestException( @@ -112,7 +112,7 @@ public function get(string $path, array $parameters = []) $path, [], 1, - $e + $e, ); } } @@ -132,7 +132,7 @@ public function delete(string $path): void $path, [], 2, - $e + $e, ); } } @@ -150,7 +150,7 @@ public function post(string $path, array $data, array $parameters = []) return $this->executeRequest( 'POST', $this->baseUrl . $path, - $parameters + $parameters, ); } catch (ClientException $e) { throw new RestClientException( @@ -158,7 +158,7 @@ public function post(string $path, array $data, array $parameters = []) $path, [], 3, - $e + $e, ); } catch (TransferException $e) { throw new RestException( @@ -166,7 +166,7 @@ public function post(string $path, array $data, array $parameters = []) $path, [], 4, - $e + $e, ); } } @@ -185,7 +185,7 @@ public function put(string $path, array $data, array $parameters = []) return $this->executeRequest( 'PUT', $this->baseUrl . $path, - $parameters + $parameters, ); } catch (ClientException $e) { throw new RestClientException( @@ -193,7 +193,7 @@ public function put(string $path, array $data, array $parameters = []) $path, [], 5, - $e + $e, ); } catch (TransferException $e) { throw new RestException( @@ -201,7 +201,7 @@ public function put(string $path, array $data, array $parameters = []) $path, [], 6, - $e + $e, ); } } @@ -225,8 +225,8 @@ protected function mergeDefaultParameters(array $parameters): array throw new \RuntimeException( sprintf( 'Error while calling array_replace_recursive in %s. This should not happen.', - __METHOD__ - ) + __METHOD__, + ), ); } @@ -257,7 +257,7 @@ protected function getCurrentRequest(): ?Request private function executeRequest( string $method, string $url, - array $parameters = [] + array $parameters = [], ) { $parameters = $this->mergeDefaultParameters($parameters); @@ -273,7 +273,7 @@ private function executeRequest( $method, $url, $parameters, - $response + $response, ); } catch (RequestException $e) { $this->logRequest( @@ -281,7 +281,7 @@ private function executeRequest( $method, $url, $parameters, - $e->getResponse() + $e->getResponse(), ); throw $e; } catch (TransferException $e) { @@ -295,7 +295,7 @@ private function executeRequest( $requestIsJson = false; $responseContentType = - $headers['Content-Type'] ?? $headers['content-type'] ?? null; + $headers['Content-Type'] ?? ($headers['content-type'] ?? null); if ($responseContentType) { foreach ($jsonContentTypeList as $contentType) { if ( @@ -322,7 +322,7 @@ private function logRequest( string $method, string $url, array $parameters, - ?ResponseInterface $response = null + ResponseInterface $response = null, ): void { if ($this->isHistoryLogged()) { $queryTime = microtime(true) - $startTime; @@ -336,7 +336,7 @@ private function logRequest( ? json_decode((string) $response->getBody(), true) : null, 'queryTime' => $queryTime, - 'backtrace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), + 'backtrace' => debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS), ]; } } diff --git a/src/SdkClient.php b/src/SdkClient.php index ee521f6..3778c86 100644 --- a/src/SdkClient.php +++ b/src/SdkClient.php @@ -79,8 +79,8 @@ class SdkClient public function __construct( RestClient $restClient, Mapping $mapping, - ?UnitOfWork $unitOfWork = null, - ?Serializer $serializer = null + UnitOfWork $unitOfWork = null, + Serializer $serializer = null, ) { $this->restClient = $restClient; $this->mapping = $mapping; @@ -99,7 +99,7 @@ public function __construct( public function setCacheItemPool( CacheItemPoolInterface $cacheItemPool, - string $cachePrefix = '' + string $cachePrefix = '', ): self { $this->cacheItemPool = $cacheItemPool; $this->cachePrefix = $cachePrefix; @@ -135,7 +135,7 @@ public function getRepository(string $modelName): EntityRepository $this, $this->restClient, $this->unitOfWork, - $modelName + $modelName, ); } @@ -168,7 +168,9 @@ public function createProxy(string $id): GhostObjectInterface $classMetadata = $this->mapping->getClassMetadataByKey($key); if (null === $classMetadata) { - throw new \RuntimeException("Unable to get classMetadata for key {$key}. This should not happen."); + throw new \RuntimeException( + "Unable to get classMetadata for key {$key}. This should not happen.", + ); } /** @var class-string $modelName */ @@ -192,19 +194,19 @@ public function createProxy(string $id): GhostObjectInterface string $method, array $parameters, \Closure|null &$initializer, - array $properties + array $properties, ) use ($sdk, $classMetadata, $id, $proxyModelName) { $isAllowedMethod = - 'jsonSerialize' === $method || - '__set' === $method || - ('__isset' === $method && 'id' === $parameters['name']); + 'jsonSerialize' === $method + || '__set' === $method + || ('__isset' === $method && 'id' === $parameters['name']); if (!$isAllowedMethod) { $initializer = null; // disable initialization // load data and modify the object here if ($id) { $repository = $sdk->getRepository( - $classMetadata->getModelName() + $classMetadata->getModelName(), ); $model = $repository->find($id); @@ -214,7 +216,7 @@ public function createProxy(string $id): GhostObjectInterface foreach ($attributeList as $attribute) { $value = $this->getPropertyAccessor()->getValue( $model, - $attribute->getAttributeName() + $attribute->getAttributeName(), ); $properties[ "\0" . @@ -238,7 +240,7 @@ public function createProxy(string $id): GhostObjectInterface // set the id of the object $idReflexion = new \ReflectionProperty( $modelName, - $classMetadata->getIdentifierAttribute()->getAttributeName() + $classMetadata->getIdentifierAttribute()->getAttributeName(), ); $idReflexion->setAccessible(true); $idReflexion->setValue($instance, $id); diff --git a/src/SdkClientRegistry.php b/src/SdkClientRegistry.php index e1b30a8..c9f0259 100644 --- a/src/SdkClientRegistry.php +++ b/src/SdkClientRegistry.php @@ -25,7 +25,7 @@ public function getSdkClient(string $name): SdkClient if (!$client) { throw new SdkClientNotFoundException( - 'Sdk client not found for name ' . $name + 'Sdk client not found for name ' . $name, ); } @@ -49,7 +49,7 @@ public function getSdkClientForClass(string $entityClassname): SdkClient } throw new SdkClientNotFoundException( - 'Sdk client not found for entity class ' . $entityClassname + 'Sdk client not found for entity class ' . $entityClassname, ); } } diff --git a/src/UnitOfWork.php b/src/UnitOfWork.php index c446b2f..297bf8e 100644 --- a/src/UnitOfWork.php +++ b/src/UnitOfWork.php @@ -42,12 +42,12 @@ public function __construct(Mapping $mapping) public function getDirtyData( array $newSerializedModel, array $oldSerializedModel, - ClassMetadata $classMetadata + ClassMetadata $classMetadata, ): array { return $this->getDirtyFields( $newSerializedModel, $oldSerializedModel, - $classMetadata + $classMetadata, ); } @@ -80,7 +80,7 @@ public function clear(string $id): self private function getDirtyFields( array $newSerializedModel, array $oldSerializedModel, - ClassMetadata $classMetadata + ClassMetadata $classMetadata, ): array { $dirtyFields = []; @@ -97,9 +97,9 @@ private function getDirtyFields( if (!$currentRelation) { if ( - (is_array($value) && - !ArrayHelper::arraySame($value, $oldValue ?: [])) || - $value !== $oldValue + (is_array($value) + && !ArrayHelper::arraySame($value, $oldValue ?: [])) + || $value !== $oldValue ) { $dirtyFields[$key] = $value; } @@ -107,7 +107,7 @@ private function getDirtyFields( } $currentClassMetadata = $this->mapping->getClassMetadata( - $currentRelation->getTargetEntity() + $currentRelation->getTargetEntity(), ); $idSerializedKey = $currentClassMetadata->getIdSerializeKey(); @@ -120,7 +120,7 @@ private function getDirtyFields( $recursiveDiff = $this->getDirtyFields( $value, $oldValue, - $currentClassMetadata + $currentClassMetadata, ); if (!empty($recursiveDiff)) { @@ -141,7 +141,7 @@ private function getDirtyFields( $dirtyFields[$key] = $this->addIdentifiers( $value, [], - $idSerializedKey + $idSerializedKey, ); } @@ -150,20 +150,20 @@ private function getDirtyFields( $oldRelationValue = $this->findOldRelation( $relationValue, $oldValue, - $currentClassMetadata + $currentClassMetadata, ); if ($relationValue !== $oldRelationValue) { if ( - is_string($relationValue) || - is_string($oldRelationValue) + is_string($relationValue) + || is_string($oldRelationValue) ) { $dirtyFields[$key][$relationKey] = $relationValue; } else { $recursiveDiff = $this->getDirtyFields( $relationValue, $oldRelationValue, - $currentClassMetadata + $currentClassMetadata, ); if (!empty($recursiveDiff)) { @@ -171,7 +171,7 @@ private function getDirtyFields( $entityId = self::getEntityId( $relationValue, - $idSerializedKey + $idSerializedKey, ); if (null !== $entityId) { $recursiveDiff[ @@ -194,13 +194,12 @@ private function getDirtyFields( /** * add defined identifiers to given model * - * @param array $newSerializedModel * @param ?string $idSerializedKey */ private function addIdentifiers( array $newSerializedModel, array $dirtyFields, - $idSerializedKey = null + $idSerializedKey = null, ): array { foreach ($newSerializedModel as $key => $value) { if ($idSerializedKey && isset($value[$idSerializedKey])) { @@ -221,7 +220,7 @@ private function addIdentifiers( private function findOldRelation( $relationValue, array $oldValue, - ClassMetadata $classMetadata + ClassMetadata $classMetadata, ) { $idSerializedKey = $classMetadata->getIdSerializeKey(); @@ -230,7 +229,7 @@ private function findOldRelation( foreach ($oldValue as $oldRelationValue) { $oldRelationValueId = self::getEntityId( $oldRelationValue, - $idSerializedKey + $idSerializedKey, ); if ($relationValueId === $oldRelationValueId) { @@ -250,7 +249,7 @@ private function findOldRelation( */ private static function getEntityId( $stringOrEntity, - string $idSerializedKey + string $idSerializedKey, ) { if (!is_array($stringOrEntity)) { return $stringOrEntity; diff --git a/yarn.lock b/yarn.lock index 31c4d35..aa36b3e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -39,13 +39,13 @@ "@nodelib/fs.scandir" "2.1.2" fastq "^1.6.0" -"@prettier/plugin-php@^0.19.7": - version "0.19.7" - resolved "https://registry.yarnpkg.com/@prettier/plugin-php/-/plugin-php-0.19.7.tgz#c11b710f319f83c276b6b3f8ab3f70f612302785" - integrity sha512-QOzBs05nwuR92uak7xBHf7RCZCFXml+6Sk3cjTp2ahQlilBtupqlNjitlTXsOfPIAYwlFgLP1oSfyapS6DN00w== +"@prettier/plugin-php@^0.22.1": + version "0.22.1" + resolved "https://registry.yarnpkg.com/@prettier/plugin-php/-/plugin-php-0.22.1.tgz#352b30cf994e00ad0220d3db41ff93e16f018a6e" + integrity sha512-TN7tzC2/jCM1/H/mlUjqPos8lIV+vm8Qwp83KofuZclGlG9PoUWHU7m0yqskjAoCy+R4ZCV0hxdBLPBkU69S2Q== dependencies: - linguist-languages "^7.21.0" - mem "^8.0.0" + linguist-languages "^7.27.0" + mem "^9.0.2" php-parser "^3.1.5" "@samverschueren/stream-to-observable@^0.3.0": @@ -628,7 +628,7 @@ lines-and-columns@^1.1.6: resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00" integrity sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA= -linguist-languages@^7.21.0: +linguist-languages@^7.27.0: version "7.27.0" resolved "https://registry.yarnpkg.com/linguist-languages/-/linguist-languages-7.27.0.tgz#bf42d6c62bd04655c8f60ed2f77a84eaeae4023a" integrity sha512-Wzx/22c5Jsv2ag+uKy+ITanGA5hzvBZngrNGDXLTC7ZjGM6FLCYGgomauTkxNJeP9of353OM0pWqngYA180xgw== @@ -732,13 +732,13 @@ map-age-cleaner@^0.1.3: dependencies: p-defer "^1.0.0" -mem@^8.0.0: - version "8.1.1" - resolved "https://registry.yarnpkg.com/mem/-/mem-8.1.1.tgz#cf118b357c65ab7b7e0817bdf00c8062297c0122" - integrity sha512-qFCFUDs7U3b8mBDPyz5EToEKoAkgCzqquIgi9nkkR9bixxOVOre+09lbuH7+9Kn2NFpm56M3GUWVbU2hQgdACA== +mem@^9.0.2: + version "9.0.2" + resolved "https://registry.yarnpkg.com/mem/-/mem-9.0.2.tgz#bbc2d40be045afe30749681e8f5d554cee0c0354" + integrity sha512-F2t4YIv9XQUBHt6AOJ0y7lSmP1+cY7Fm1DRh9GClTGzKST7UWLMx6ly9WZdLH/G/ppM5RL4MlQfRT71ri9t19A== dependencies: map-age-cleaner "^0.1.3" - mimic-fn "^3.1.0" + mimic-fn "^4.0.0" merge-stream@^2.0.0: version "2.0.0" @@ -768,10 +768,10 @@ mimic-fn@^2.1.0: resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== -mimic-fn@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-3.1.0.tgz#65755145bbf3e36954b949c16450427451d5ca74" - integrity sha512-Ysbi9uYW9hFyfrThdDEQuykN4Ey6BuwPD2kpI5ES/nFTDn/98yxYNLZJcgUAKPT/mcrLLKaGzJR9YVxJrIdASQ== +mimic-fn@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-4.0.0.tgz#60a90550d5cb0b239cca65d893b1a53b29871ecc" + integrity sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw== minimatch@^3.0.4: version "3.0.4" @@ -967,10 +967,10 @@ please-upgrade-node@^3.1.1, please-upgrade-node@^3.2.0: dependencies: semver-compare "^1.0.0" -prettier@^1.18.2: - version "1.18.2" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.18.2.tgz#6823e7c5900017b4bd3acf46fe9ac4b4d7bda9ea" - integrity sha512-OeHeMc0JhFE9idD4ZdtNibzY0+TPHSpSSb9h8FqtP+YnoZZ1sl8Vc9b1sasjfymH3SonAF4QcA2+mzHPhMvIiw== +prettier@^3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.1.1.tgz#6ba9f23165d690b6cbdaa88cb0807278f7019848" + integrity sha512-22UbSzg8luF4UuZtzgiUOfcGM8s4tjBv6dJRT7j275NXsy2jb4aJa4NNveul5x4eqlF1wuhuR2RElK71RvmVaw== pump@^3.0.0: version "3.0.0"