diff --git a/.lintstagedrc b/.lintstagedrc new file mode 100644 index 0000000..facbe66 --- /dev/null +++ b/.lintstagedrc @@ -0,0 +1,8 @@ +"src/**/*.php": + - "yarn run prettier --write" + - "vendor/bin/php-cs-fixer fix --config=.php_cs" + - "git add" + +"Tests/**/*.php": + - "vendor/bin/php-cs-fixer fix --config=.php_cs" + - "git add" diff --git a/package.json b/package.json index e89b424..5720de8 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,11 @@ { "dependencies": { + "@prettier/plugin-php": "^0.1.0", "husky": "^0.14.3", - "lint-staged": "^7.0.4" + "lint-staged": "^7.0.4", + "prettier": "^1.11.1" }, "scripts": { "precommit": "lint-staged" - }, - "lint-staged": { - "*.php": [ - "vendor/bin/php-cs-fixer fix --config=.php_cs", - "git add" - ] } } diff --git a/src/Collection/Collection.php b/src/Collection/Collection.php index 3745973..58cd98e 100644 --- a/src/Collection/Collection.php +++ b/src/Collection/Collection.php @@ -32,8 +32,10 @@ class Collection implements \IteratorAggregate, \Serializable, \Countable, \Arra * @param array $elements the data elements as an array * @param array $extraProperties the extra properties */ - public function __construct(array $elements = [], array $extraProperties = []) - { + public function __construct( + array $elements = [], + array $extraProperties = [] + ) { $this->elements = $elements; $this->extraProperties = $extraProperties; } @@ -115,7 +117,9 @@ public function offsetUnset($offset) */ public function offsetGet($offset) { - return isset($this->elements[$offset]) ? $this->elements[$offset] : null; + return isset($this->elements[$offset]) + ? $this->elements[$offset] + : null; } /** diff --git a/src/EntityRepository.php b/src/EntityRepository.php index 7d257f5..eb2d554 100644 --- a/src/EntityRepository.php +++ b/src/EntityRepository.php @@ -47,8 +47,12 @@ class EntityRepository * @param RestClient $restClient The client to process the http requests * @param string $entityName The entity to work with */ - public function __construct(SdkClient $sdkClient, RestClient $restClient, UnitOfWork $unitOfWork, $entityName) - { + public function __construct( + SdkClient $sdkClient, + RestClient $restClient, + UnitOfWork $unitOfWork, + $entityName + ) { $this->sdk = $sdkClient; $this->restClient = $restClient; $this->unitOfWork = $unitOfWork; @@ -78,13 +82,17 @@ public function __call($method, $arguments) default: throw new \BadMethodCallException( - 'Undefined method \'' . $method . '\'. The method name must start with + '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(); @@ -97,7 +105,8 @@ public function __call($method, $arguments) } else { $queryParams = current($arguments); } - $path .= '?' . http_build_query($this->convertQueryParameters($queryParams)); + $path .= + '?' . http_build_query($this->convertQueryParameters($queryParams)); // if entityList is found in cache, return it $entityListFromCache = $this->fetchFromCache($path); @@ -230,16 +239,31 @@ public function remove($model) * * @return object */ - public function update($model, $serializationContext = [], $queryParams = []) - { + public function update( + $model, + $serializationContext = [], + $queryParams = [] + ) { $identifier = $model->{$this->getClassMetadata()->getIdGetter()}(); $serializer = $this->sdk->getSerializer(); - $newSerializedModel = $serializer->serialize($model, $this->entityName, $serializationContext); + $newSerializedModel = $serializer->serialize( + $model, + $this->entityName, + $serializationContext + ); $oldModel = $this->unitOfWork->getDirtyEntity($identifier); if ($oldModel) { - $oldSerializedModel = $serializer->serialize($oldModel, $this->entityName, $serializationContext); - $newSerializedModel = $this->unitOfWork->getDirtyData($newSerializedModel, $oldSerializedModel, $this->getClassMetadata()); + $oldSerializedModel = $serializer->serialize( + $oldModel, + $this->entityName, + $serializationContext + ); + $newSerializedModel = $this->unitOfWork->getDirtyData( + $newSerializedModel, + $oldSerializedModel, + $this->getClassMetadata() + ); } $data = $this->restClient->put( @@ -262,8 +286,11 @@ public function update($model, $serializationContext = [], $queryParams = []) * * @return object */ - public function persist($model, $serializationContext = [], $queryParams = []) - { + public function persist( + $model, + $serializationContext = [], + $queryParams = [] + ) { $mapping = $this->sdk->getMapping(); $prefix = $mapping->getIdPrefix(); $key = $mapping->getKeyFromModel($this->entityName); @@ -271,11 +298,17 @@ public function persist($model, $serializationContext = [], $queryParams = []) $path = empty($prefix) ? '/' . $key : $prefix . '/' . $key; $oldSerializedModel = $this->getClassMetadata()->getDefaultSerializedModel(); - $newSerializedModel = $this->sdk->getSerializer() - ->serialize($model, $this->entityName, $serializationContext); + $newSerializedModel = $this->sdk->getSerializer()->serialize( + $model, + $this->entityName, + $serializationContext + ); - $diff = $this->unitOfWork - ->getDirtyData($newSerializedModel, $oldSerializedModel, $this->getClassMetadata()); + $diff = $this->unitOfWork->getDirtyData( + $newSerializedModel, + $oldSerializedModel, + $this->getClassMetadata() + ); $data = $this->restClient->post( $this->addQueryParameter($path, $queryParams), @@ -381,31 +414,30 @@ private function convertQueryParameters($queryParameters) { $mapping = $this->sdk->getMapping(); - return array_map( - function ($item) use ($mapping) { - if (is_object($item)) { - $classname = get_class($item); + return array_map(function ($item) use ($mapping) { + if (is_object($item)) { + $classname = get_class($item); - if ($mapping->hasClassMetadata($classname)) { - $idAttr = $mapping->getClassMetadata($classname) - ->getIdentifierAttribute(); + if ($mapping->hasClassMetadata($classname)) { + $idAttr = $mapping->getClassMetadata( + $classname + )->getIdentifierAttribute(); - if ($idAttr) { - $idGetter = 'get' . ucfirst($idAttr->getAttributeName()); + if ($idAttr) { + $idGetter = + 'get' . ucfirst($idAttr->getAttributeName()); - return $item->{$idGetter}(); - } + return $item->{$idGetter}(); } + } - if (method_exists($item, 'getId')) { - return call_user_func([$item, 'getId']); - } + if (method_exists($item, 'getId')) { + return call_user_func([$item, 'getId']); } + } - return $item; - }, - $queryParameters - ); + return $item; + }, $queryParameters); } /** @@ -421,9 +453,9 @@ private function normalizeCacheKey($key) private function getClassMetadata() { if (!isset($this->classMetadata)) { - $this->classMetadataCache = $this->sdk - ->getMapping() - ->getClassMetadata($this->entityName); + $this->classMetadataCache = $this->sdk->getMapping()->getClassMetadata( + $this->entityName + ); } return $this->classMetadataCache; diff --git a/src/Helper/ArrayHelper.php b/src/Helper/ArrayHelper.php index ad1df2e..6f7bd26 100644 --- a/src/Helper/ArrayHelper.php +++ b/src/Helper/ArrayHelper.php @@ -81,7 +81,10 @@ public static function arrayDot($array, $prepend = '') $results = []; foreach ($array as $key => $value) { if (is_array($value) && !empty($value)) { - $results = array_merge($results, static::arrayDot($value, $prepend . $key . '.')); + $results = array_merge( + $results, + static::arrayDot($value, $prepend . $key . '.') + ); } else { $results[$prepend . $key] = $value; } @@ -92,7 +95,10 @@ public static function arrayDot($array, $prepend = '') public static function arrayDiffAssocRecursive($array1, $array2) { - return array_diff_assoc(static::arrayDot($array1), static::arrayDot($array2)); + return array_diff_assoc( + static::arrayDot($array1), + static::arrayDot($array2) + ); } public static function arraySame($array1, $array2) diff --git a/src/Mapping.php b/src/Mapping.php index dee6a7f..3010af7 100644 --- a/src/Mapping.php +++ b/src/Mapping.php @@ -12,9 +12,7 @@ */ class Mapping { - public const DEFAULT_CONFIG = [ - 'collectionKey' => 'hydra:member', - ]; + public const DEFAULT_CONFIG = ['collectionKey' => 'hydra:member']; /** * @var string @@ -79,10 +77,7 @@ public function getConfig() */ public function setConfig(array $config) { - $this->config = array_merge( - self::DEFAULT_CONFIG, - $config - ); + $this->config = array_merge(self::DEFAULT_CONFIG, $config); return $this; } @@ -122,12 +117,9 @@ public function getModelName($key) */ public function getMappingKeys() { - return array_map( - function (ClassMetadata $classMetadata) { - return $classMetadata->getKey(); - }, - $this->classMetadataList - ); + return array_map(function (ClassMetadata $classMetadata) { + return $classMetadata->getKey(); + }, $this->classMetadataList); } /** @@ -162,7 +154,9 @@ public function getKeyFromModel($modelName) } } - throw new MappingException('Model name ' . $modelName . ' not found in mapping'); + throw new MappingException( + 'Model name ' . $modelName . ' not found in mapping' + ); } /** @@ -273,8 +267,10 @@ private function checkMappingExistence($key, $subKey = null) if (!empty($subKey)) { $methodName = 'get' . ucfirst($subKey); - if (!$metadata->$methodName()) { - throw new MappingException($key . ' key is mapped but no ' . $subKey . ' found'); + if (!$metadata->{$methodName}()) { + throw new MappingException( + $key . ' key is mapped but no ' . $subKey . ' found' + ); } } } @@ -288,7 +284,10 @@ private function checkMappingExistence($key, $subKey = null) */ private function removePrefix($value) { - if (($this->idPrefixLength > 0) && (0 === strpos($value, $this->idPrefix))) { + if ( + ($this->idPrefixLength > 0) && + (0 === strpos($value, $this->idPrefix)) + ) { return substr($value, $this->idPrefixLength); } diff --git a/src/Mapping/ClassMetadata.php b/src/Mapping/ClassMetadata.php index 74d9a5e..4975771 100644 --- a/src/Mapping/ClassMetadata.php +++ b/src/Mapping/ClassMetadata.php @@ -122,7 +122,9 @@ public function setKey($key) */ public function getAttribute($name) { - return isset($this->attributeList[$name]) ? $this->attributeList[$name] : null; + return isset($this->attributeList[$name]) + ? $this->attributeList[$name] + : null; } /** @@ -240,8 +242,7 @@ public function getIdGetter() public function getIdSerializeKey() { if ($this->getIdentifierAttribute()) { - $idAttr = $this->getIdentifierAttribute() - ->getSerializedKey(); + $idAttr = $this->getIdentifierAttribute()->getSerializedKey(); return $idAttr; } else { @@ -279,8 +280,7 @@ public function getDefaultSerializedModel() private function getIdKey() { if ($this->getIdentifierAttribute()) { - $idAttr = $this->getIdentifierAttribute() - ->getAttributeName(); + $idAttr = $this->getIdentifierAttribute()->getAttributeName(); return $idAttr; } else { diff --git a/src/Mapping/Driver/AnnotationDriver.php b/src/Mapping/Driver/AnnotationDriver.php index 92acec6..4713d66 100644 --- a/src/Mapping/Driver/AnnotationDriver.php +++ b/src/Mapping/Driver/AnnotationDriver.php @@ -66,7 +66,10 @@ public function loadDirectory($path) $iterator = new \RegexIterator( new \RecursiveIteratorIterator( - new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS), + new \RecursiveDirectoryIterator( + $path, + \FilesystemIterator::SKIP_DOTS + ), \RecursiveIteratorIterator::LEAVES_ONLY ), '/^.+\.php$/i', @@ -136,7 +139,10 @@ private function getClassMetadataForClassname($classname) $reflClass = new \ReflectionClass($classname); /** @var Annotations\Entity */ - $classAnnotation = $reader->getClassAnnotation($reflClass, Annotations\Entity::class); + $classAnnotation = $reader->getClassAnnotation( + $reflClass, + Annotations\Entity::class + ); if (!$classAnnotation) { return null; @@ -147,7 +153,11 @@ private function getClassMetadataForClassname($classname) foreach ($reflClass->getProperties() as $property) { // manage attributes /** @var Annotations\Attribute */ - $propertyAnnotation = $this->getPropertyAnnotation($reader, $property, 'Attribute'); + $propertyAnnotation = $this->getPropertyAnnotation( + $reader, + $property, + 'Attribute' + ); if ($propertyAnnotation) { $isId = $this->getPropertyAnnotation($reader, $property, 'Id'); @@ -161,18 +171,35 @@ private function getClassMetadataForClassname($classname) } else { // manage relations /** @var Annotations\OneToMany */ - $relation = $this->getPropertyAnnotation($reader, $property, 'OneToMany'); + $relation = $this->getPropertyAnnotation( + $reader, + $property, + 'OneToMany' + ); if (!$relation) { /** @var Annotations\ManyToOne */ - $relation = $this->getPropertyAnnotation($reader, $property, 'ManyToOne'); + $relation = $this->getPropertyAnnotation( + $reader, + $property, + 'ManyToOne' + ); } if ($relation) { - $attributeList[] = new Attribute($relation->name, $property->getName()); + $attributeList[] = new Attribute( + $relation->name, + $property->getName() + ); $targetEntity = $relation->targetEntity; if (false === strpos($targetEntity, '/')) { - $targetEntity = substr($classname, 0, strrpos($classname, '\\') + 1) . $targetEntity; + $targetEntity = + substr( + $classname, + 0, + strrpos($classname, '\\') + 1 + ) . + $targetEntity; } $relationList[] = new Relation( diff --git a/src/Model/ModelHydrator.php b/src/Model/ModelHydrator.php index 74d05f7..9275071 100644 --- a/src/Model/ModelHydrator.php +++ b/src/Model/ModelHydrator.php @@ -85,8 +85,7 @@ public function hydrate($data, $modelName) */ public function hydrateList($data, $modelName) { - $collectionKey = $this->sdk->getMapping() - ->getConfig()['collectionKey']; + $collectionKey = $this->sdk->getMapping()->getConfig()['collectionKey']; if (is_array($data) && ArrayHelper::arrayHas($data, $collectionKey)) { return $this->deserializeAll($data, $modelName); @@ -105,15 +104,11 @@ public function hydrateList($data, $modelName) */ private function deserializeAll($data, $modelName) { - $collectionKey = $this->sdk->getMapping() - ->getConfig()['collectionKey']; + $collectionKey = $this->sdk->getMapping()->getConfig()['collectionKey']; - $itemList = array_map( - function ($member) use ($modelName) { - return $this->deserialize($member, $modelName); - }, - ArrayHelper::arrayGet($data, $collectionKey) - ); + $itemList = array_map(function ($member) use ($modelName) { + return $this->deserialize($member, $modelName); + }, ArrayHelper::arrayGet($data, $collectionKey)); $extraProperties = array_filter( $data, @@ -159,7 +154,8 @@ private function deserialize($data, $modelName) private function guessCollectionClassname($data) { switch (true) { - case !empty($data['@type']) && 'hydra:PagedCollection' === $data['@type']: + case !empty($data['@type']) && + 'hydra:PagedCollection' === $data['@type']: return HydraPaginatedCollection::class; case array_key_exists('_embedded', $data): diff --git a/src/Model/Serializer.php b/src/Model/Serializer.php index 71b89bd..ed81885 100644 --- a/src/Model/Serializer.php +++ b/src/Model/Serializer.php @@ -89,7 +89,9 @@ public function deserialize(array $data, $className) $classMetadata = $this->mapping->getClassMetadata($className); $identifierAttribute = $classMetadata->getIdentifierAttribute(); - $identifierAttrKey = $identifierAttribute ? $identifierAttribute->getSerializedKey() : null; + $identifierAttrKey = $identifierAttribute + ? $identifierAttribute->getSerializedKey() + : null; $attributeList = $classMetadata->getAttributeList(); @@ -113,23 +115,40 @@ public function deserialize(array $data, $className) $value = $this->sdk->createProxy($value); } elseif (is_array($value)) { if (isset($value[$identifierAttrKey])) { - $key = $this->mapping->getKeyFromId($value[$identifierAttrKey]); - $subClassMetadata = $this->getClassMetadataFromId($value[$identifierAttrKey]); - $value = $this->deserialize($value, $subClassMetadata->getModelName()); + $key = $this->mapping->getKeyFromId( + $value[$identifierAttrKey] + ); + $subClassMetadata = $this->getClassMetadataFromId( + $value[$identifierAttrKey] + ); + $value = $this->deserialize( + $value, + $subClassMetadata->getModelName() + ); } else { $list = []; foreach ($value as $item) { if (is_string($item)) { $list[] = $this->sdk->createProxy($item); - } elseif (is_array($item) && isset($item[$identifierAttrKey])) { + } elseif ( + is_array($item) && + isset($item[$identifierAttrKey]) + ) { // not tested for now // /the $identifierAttrKey is not the real identifier, as it is // the main object identifier, but we do not have the metadada for now // the thing we assume now is that every entity "may" have the same key // as identifier - $key = $this->mapping->getKeyFromId($item[$identifierAttrKey]); - $subClassMetadata = $this->getClassMetadataFromId($item[$identifierAttrKey]); - $list[] = $this->deserialize($item, $subClassMetadata->getModelName()); + $key = $this->mapping->getKeyFromId( + $item[$identifierAttrKey] + ); + $subClassMetadata = $this->getClassMetadataFromId( + $item[$identifierAttrKey] + ); + $list[] = $this->deserialize( + $item, + $subClassMetadata->getModelName() + ); } } @@ -143,12 +162,14 @@ public function deserialize(array $data, $className) $value = new \DateTime($value); } - $instance->$setter($value); + $instance->{$setter}($value); } } } - $identifier = $instance->{$this->getClassMetadata($instance)->getIdGetter()}(); + $identifier = $instance->{$this->getClassMetadata( + $instance + )->getIdGetter()}(); if ($identifier) { $this->unitOfWork->registerClean($identifier, $instance); } @@ -168,7 +189,9 @@ public function deserialize(array $data, $className) private function resolveRealClassName(array $data, $className) { if (!empty($data['@id'])) { - $classMetadata = $this->mapping->tryGetClassMetadataById($data['@id']); + $classMetadata = $this->mapping->tryGetClassMetadataById( + $data['@id'] + ); if ($classMetadata) { return $classMetadata->getModelName(); @@ -176,7 +199,6 @@ private function resolveRealClassName(array $data, $className) } // Real class name could also be retrieved from @type property. - return $className; } @@ -190,8 +212,12 @@ private function resolveRealClassName(array $data, $className) * * @return array|mixed */ - private function recursiveSerialize($entity, $modelName, $level = 0, $context = []) - { + private function recursiveSerialize( + $entity, + $modelName, + $level = 0, + $context = [] + ) { $classMetadata = $this->mapping->getClassMetadata($modelName); if ($level > 0 && empty($context['serializeRelation'])) { @@ -210,14 +236,21 @@ private function recursiveSerialize($entity, $modelName, $level = 0, $context = foreach ($attributeList as $attribute) { $method = 'get' . ucfirst($attribute->getAttributeName()); - if ($attribute->isIdentifier() && !$entity->$method()) { + if ($attribute->isIdentifier() && !$entity->{$method}()) { continue; } - $relation = $classMetadata->getRelation($attribute->getSerializedKey()); + $relation = $classMetadata->getRelation( + $attribute->getSerializedKey() + ); - $data = $entity->$method(); + $data = $entity->{$method}(); - if (null === $data && $relation && $relation->isManyToOne() && $level > 0) { + if ( + null === $data && + $relation && + $relation->isManyToOne() && + $level > 0 + ) { /* We only serialize the root many-to-one relations to prevent, hopefully, unlinked and/or duplicated content. For instance, a cart with cartItemList containing @@ -233,17 +266,23 @@ private function recursiveSerialize($entity, $modelName, $level = 0, $context = $data, PhoneNumberFormat::INTERNATIONAL ); - } elseif (is_object($data) - && $relation - && $this->mapping->hasClassMetadata($relation->getTargetEntity()) + } elseif ( + is_object($data) && + $relation && + $this->mapping->hasClassMetadata( + $relation->getTargetEntity() + ) ) { - $idAttribute = $this->mapping - ->getClassMetadata($relation->getTargetEntity()) + $idAttribute = $this->mapping->getClassMetadata( + $relation->getTargetEntity() + ) ->getIdentifierAttribute() ->getAttributeName(); $idGetter = 'get' . ucfirst($idAttribute); - if (method_exists($data, $idGetter) && $data->{$idGetter}()) { + if ( + method_exists($data, $idGetter) && $data->{$idGetter}() + ) { $data = $data->{$idGetter}(); } elseif ($relation->isManyToOne()) { if ($level > 0) { @@ -257,12 +296,19 @@ private function recursiveSerialize($entity, $modelName, $level = 0, $context = foreach ($data as $key => $item) { if ($item instanceof \DateTime) { $newData[$key] = $item->format('c'); - } elseif (is_object($item) && + } elseif ( + is_object($item) && $relation && - $this->mapping->hasClassMetadata($relation->getTargetEntity()) + $this->mapping->hasClassMetadata( + $relation->getTargetEntity() + ) ) { - $serializeRelation = !empty($context['serializeRelations']) - && in_array($relation->getSerializedKey(), $context['serializeRelations']); + $serializeRelation = + !empty($context['serializeRelations']) && + in_array( + $relation->getSerializedKey(), + $context['serializeRelations'] + ); $newData[$key] = $this->recursiveSerialize( $item, @@ -303,7 +349,6 @@ private function getClassMetadataFromId($id) private function getClassMetadata($entity) { - return $this->mapping - ->getClassMetadata(get_class($entity)); + return $this->mapping->getClassMetadata(get_class($entity)); } } diff --git a/src/RestClient.php b/src/RestClient.php index 7df6748..364470f 100644 --- a/src/RestClient.php +++ b/src/RestClient.php @@ -59,7 +59,9 @@ class RestClient public function __construct(ClientInterface $httpClient, $baseUrl = null) { $this->httpClient = $httpClient; - $this->baseUrl = '/' === substr($baseUrl, -1) ? substr($baseUrl, 0, -1) : $baseUrl; + $this->baseUrl = '/' === substr($baseUrl, -1) + ? substr($baseUrl, 0, -1) + : $baseUrl; $this->logHistory = false; $this->requestHistory = []; } @@ -127,9 +129,21 @@ public function get($path, $parameters = []) if (404 === $e->getResponse()->getStatusCode()) { return null; } - throw new RestClientException('Error while getting resource', $path, [], 7, $e); + throw new RestClientException( + 'Error while getting resource', + $path, + [], + 7, + $e + ); } catch (TransferException $e) { - throw new RestException('Error while getting resource', $path, [], 1, $e); + throw new RestException( + 'Error while getting resource', + $path, + [], + 1, + $e + ); } } @@ -147,7 +161,13 @@ public function delete($path) } catch (ClientException $e) { return; } catch (TransferException $e) { - throw new RestException('Error while deleting resource', $path, [], 2, $e); + throw new RestException( + 'Error while deleting resource', + $path, + [], + 2, + $e + ); } } @@ -165,11 +185,27 @@ public function post($path, $data, $parameters = []) { $parameters['json'] = $data; try { - return $this->executeRequest('POST', $this->baseUrl . $path, $parameters); + return $this->executeRequest( + 'POST', + $this->baseUrl . $path, + $parameters + ); } catch (ClientException $e) { - throw new RestClientException('Cannot create resource', $path, [], 3, $e); + throw new RestClientException( + 'Cannot create resource', + $path, + [], + 3, + $e + ); } catch (TransferException $e) { - throw new RestException('Error while posting resource', $path, [], 4, $e); + throw new RestException( + 'Error while posting resource', + $path, + [], + 4, + $e + ); } } @@ -188,11 +224,27 @@ public function put($path, $data, $parameters = []) $parameters['json'] = $data; try { - return $this->executeRequest('PUT', $this->baseUrl . $path, $parameters); + return $this->executeRequest( + 'PUT', + $this->baseUrl . $path, + $parameters + ); } catch (ClientException $e) { - throw new RestClientException('Cannot update resource', $path, [], 5, $e); + throw new RestClientException( + 'Cannot update resource', + $path, + [], + 5, + $e + ); } catch (TransferException $e) { - throw new RestException('Error while puting resource', $path, [], 6, $e); + throw new RestException( + 'Error while puting resource', + $path, + [], + 6, + $e + ); } } @@ -207,14 +259,10 @@ protected function mergeDefaultParameters(array $parameters) { $request = $this->getCurrentRequest(); - $defaultParameters = [ - 'version' => '1.0', - ]; + $defaultParameters = ['version' => '1.0']; if ($request) { - $defaultParameters['headers'] = [ - 'Referer' => $request->getUri(), - ]; + $defaultParameters['headers'] = ['Referer' => $request->getUri()]; } return array_replace_recursive($defaultParameters, $parameters); @@ -256,7 +304,13 @@ private function executeRequest($method, $url, $parameters = []) try { $response = $this->httpClient->request($method, $url, $parameters); - $this->logRequest($startTime, $method, $url, $parameters, $response); + $this->logRequest( + $startTime, + $method, + $url, + $parameters, + $response + ); } catch (TransferException $e) { $this->logRequest($startTime, $method, $url, $parameters); throw $e; @@ -269,7 +323,9 @@ private function executeRequest($method, $url, $parameters = []) if (isset($headers['Content-Type'])) { foreach ($jsonContentTypeList as $contentType) { - if (false !== stripos($headers['Content-Type'][0], $contentType)) { + if ( + false !== stripos($headers['Content-Type'][0], $contentType) + ) { $requestIsJson = true; break; } @@ -292,8 +348,13 @@ private function executeRequest($method, $url, $parameters = []) * @param array $parameters * @param ResponseInterface|null $response */ - private function logRequest($startTime, $method, $url, $parameters, ResponseInterface $response = null) - { + private function logRequest( + $startTime, + $method, + $url, + $parameters, + ResponseInterface $response = null + ) { if ($this->isHistoryLogged()) { $queryTime = microtime(true) - $startTime; @@ -302,7 +363,9 @@ private function logRequest($startTime, $method, $url, $parameters, ResponseInte 'url' => $url, 'parameters' => $parameters, 'response' => $response, - 'responseBody' => $response ? json_decode($response->getBody(), true) : null, + 'responseBody' => $response + ? json_decode($response->getBody(), true) + : null, 'queryTime' => $queryTime, 'backtrace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), ]; diff --git a/src/SdkClient.php b/src/SdkClient.php index 8fab041..846ad71 100644 --- a/src/SdkClient.php +++ b/src/SdkClient.php @@ -74,8 +74,12 @@ class SdkClient * @param Mapping $mapping * @param Serializer|null $serializer */ - public function __construct(RestClient $restClient, Mapping $mapping, UnitOfWork $unitOfWork, Serializer $serializer = null) - { + public function __construct( + RestClient $restClient, + Mapping $mapping, + UnitOfWork $unitOfWork, + Serializer $serializer = null + ) { $this->restClient = $restClient; $this->mapping = $mapping; $this->unitOfWork = $unitOfWork; @@ -95,8 +99,10 @@ public function __construct(RestClient $restClient, Mapping $mapping, UnitOfWork * * @return SdkClient */ - public function setCacheItemPool(CacheItemPoolInterface $cacheItemPool, $cachePrefix = '') - { + public function setCacheItemPool( + CacheItemPoolInterface $cacheItemPool, + $cachePrefix = '' + ) { $this->cacheItemPool = $cacheItemPool; $this->cachePrefix = $cachePrefix; @@ -142,8 +148,15 @@ public function getRepository($modelName) $modelName = $metadata->getModelName(); if (!isset($this->repositoryList[$modelName])) { - $repositoryName = $metadata->getRepositoryName() ?: '\Mapado\RestClientSdk\EntityRepository'; - $this->repositoryList[$modelName] = new $repositoryName($this, $this->restClient, $this->unitOfWork, $modelName); + $repositoryName = + $metadata->getRepositoryName() + ?: '\Mapado\RestClientSdk\EntityRepository'; + $this->repositoryList[$modelName] = new $repositoryName( + $this, + $this->restClient, + $this->unitOfWork, + $modelName + ); } return $this->repositoryList[$modelName]; @@ -219,28 +232,31 @@ public function createProxy($id) array $parameters, &$initializer, array $properties - ) use ( - $sdk, - $classMetadata, - $id, - $proxyModelName - ) { - $isAllowedMethod = 'jsonSerialize' === $method - || '__set' === $method; + ) use ($sdk, $classMetadata, $id, $proxyModelName) { + $isAllowedMethod = + 'jsonSerialize' === $method || '__set' === $method; if (!$isAllowedMethod) { $initializer = null; // disable initialization // load data and modify the object here if ($id) { - $repository = $sdk->getRepository($classMetadata->getModelName()); + $repository = $sdk->getRepository( + $classMetadata->getModelName() + ); $model = $repository->find($id); $attributeList = $classMetadata->getAttributeList(); foreach ($attributeList as $attribute) { - $getter = 'get' . ucfirst($attribute->getAttributeName()); - $value = $model->$getter(); - $properties['\0' . $proxyModelName . '\0' . $attribute->getAttributeName()] = $value; + $getter = + 'get' . ucfirst($attribute->getAttributeName()); + $value = $model->{$getter}(); + $properties[ + '\0' . + $proxyModelName . + '\0' . + $attribute->getAttributeName() + ] = $value; } } @@ -249,13 +265,9 @@ public function createProxy($id) }; // initialize the proxy instance - $instance = $factory->createProxy( - $modelName, - $initializer, - [ - 'skippedProperties' => [$proxyModelName . '\0id'], - ] - ); + $instance = $factory->createProxy($modelName, $initializer, [ + 'skippedProperties' => [$proxyModelName . '\0id'], + ]); // set the id of the object $idReflexion = new \ReflectionProperty( diff --git a/src/UnitOfWork.php b/src/UnitOfWork.php index 4693c4f..111e477 100644 --- a/src/UnitOfWork.php +++ b/src/UnitOfWork.php @@ -45,9 +45,16 @@ public function __construct(Mapping $mapping) * * @return array */ - public function getDirtyData(array $newSerializedModel, array $oldSerializedModel, ClassMetadata $classMetadata) - { - return $this->getDirtyFields($newSerializedModel, $oldSerializedModel, $classMetadata); + public function getDirtyData( + array $newSerializedModel, + array $oldSerializedModel, + ClassMetadata $classMetadata + ) { + return $this->getDirtyFields( + $newSerializedModel, + $oldSerializedModel, + $classMetadata + ); } /** @@ -109,8 +116,11 @@ public function clear($id) * * @return array */ - private function getDirtyFields(array $newSerializedModel, array $oldSerializedModel, ClassMetadata $classMetadata) - { + private function getDirtyFields( + array $newSerializedModel, + array $oldSerializedModel, + ClassMetadata $classMetadata + ) { $dirtyFields = []; foreach ($newSerializedModel as $key => $value) { @@ -122,30 +132,44 @@ private function getDirtyFields(array $newSerializedModel, array $oldSerializedM $oldValue = $oldSerializedModel[$key]; - $currentRelation = $classMetadata ? $classMetadata->getRelation($key) : null; + $currentRelation = $classMetadata + ? $classMetadata->getRelation($key) + : null; if (!$currentRelation) { - if (is_array($value) && !ArrayHelper::arraySame($value, $oldValue ?: []) - || $value !== $oldValue + if ( + is_array($value) && + !ArrayHelper::arraySame($value, $oldValue ?: []) || + $value !== $oldValue ) { $dirtyFields[$key] = $value; } continue; } - $currentClassMetadata = $this->mapping->getClassMetadata($currentRelation->getTargetEntity()); + $currentClassMetadata = $this->mapping->getClassMetadata( + $currentRelation->getTargetEntity() + ); - $idSerializedKey = $currentClassMetadata ? $currentClassMetadata->getIdSerializeKey() : null; + $idSerializedKey = $currentClassMetadata + ? $currentClassMetadata->getIdSerializeKey() + : null; if (Relation::MANY_TO_ONE === $currentRelation->getType()) { if ($value !== $oldValue) { if (is_string($value) || is_string($oldValue)) { $dirtyFields[$key] = $value; } else { - $recursiveDiff = $this->getDirtyFields($value, $oldValue, $currentClassMetadata); + $recursiveDiff = $this->getDirtyFields( + $value, + $oldValue, + $currentClassMetadata + ); if (!empty($recursiveDiff)) { - $recursiveDiff[$idSerializedKey] = self::getEntityId($value, $idSerializedKey); + $recursiveDiff[ + $idSerializedKey + ] = self::getEntityId($value, $idSerializedKey); $dirtyFields[$key] = $recursiveDiff; } } @@ -155,30 +179,51 @@ private function getDirtyFields(array $newSerializedModel, array $oldSerializedM } // ONE_TO_MANY relation - if (count($value ?? []) !== count($oldValue ?? [])) { // get all objects ids of new array - $dirtyFields[$key] = $this->addIdentifiers($value, [], $idSerializedKey); + $dirtyFields[$key] = $this->addIdentifiers( + $value, + [], + $idSerializedKey + ); } if (!empty($value)) { foreach ($value as $relationKey => $relationValue) { - $oldRelationValue = $this->findOldRelation($relationValue, $oldValue, $currentClassMetadata); + $oldRelationValue = $this->findOldRelation( + $relationValue, + $oldValue, + $currentClassMetadata + ); if ($relationValue !== $oldRelationValue) { - if (is_string($relationValue) || is_string($oldRelationValue)) { + if ( + is_string($relationValue) || + is_string($oldRelationValue) + ) { $dirtyFields[$key][$relationKey] = $relationValue; } else { - $recursiveDiff = $this->getDirtyFields($relationValue, $oldRelationValue, $currentClassMetadata); + $recursiveDiff = $this->getDirtyFields( + $relationValue, + $oldRelationValue, + $currentClassMetadata + ); if (!empty($recursiveDiff)) { $idSerializedKey = $currentClassMetadata->getIdSerializeKey(); - $entityId = self::getEntityId($relationValue, $idSerializedKey); + $entityId = self::getEntityId( + $relationValue, + $idSerializedKey + ); if (null !== $entityId) { - $recursiveDiff[$idSerializedKey] = $entityId; + $recursiveDiff[ + $idSerializedKey + ] = $entityId; } - $dirtyFields[$key][$relationKey] = $recursiveDiff; + $dirtyFields[$key][ + $relationKey + ] = $recursiveDiff; } } } @@ -199,8 +244,11 @@ private function getDirtyFields(array $newSerializedModel, array $oldSerializedM * * @return array */ - private function addIdentifiers($newSerializedModel, $dirtyFields, $idSerializedKey = null) - { + private function addIdentifiers( + $newSerializedModel, + $dirtyFields, + $idSerializedKey = null + ) { foreach ($newSerializedModel as $key => $value) { if ($idSerializedKey && isset($value[$idSerializedKey])) { $dirtyFields[$key][$idSerializedKey] = $value[$idSerializedKey]; @@ -212,14 +260,20 @@ private function addIdentifiers($newSerializedModel, $dirtyFields, $idSerialized return $dirtyFields; } - private function findOldRelation($relationValue, array $oldValue, ClassMetadata $classMetadata) - { + private function findOldRelation( + $relationValue, + array $oldValue, + ClassMetadata $classMetadata + ) { $idSerializedKey = $classMetadata->getIdSerializeKey(); $relationValueId = self::getEntityId($relationValue, $idSerializedKey); foreach ($oldValue as $oldRelationValue) { - $oldRelationValueId = self::getEntityId($oldRelationValue, $idSerializedKey); + $oldRelationValueId = self::getEntityId( + $oldRelationValue, + $idSerializedKey + ); if ($relationValueId === $oldRelationValueId) { return $oldRelationValue; @@ -241,7 +295,6 @@ private static function getEntityId($stringOrEntity, $idSerializedKey) return $stringOrEntity; } - return $stringOrEntity[$idSerializedKey] - ?? null; + return $stringOrEntity[$idSerializedKey] ?? null; } } diff --git a/yarn.lock b/yarn.lock index 92d4475..b5dfbdf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -16,6 +16,12 @@ esutils "^2.0.2" js-tokens "^3.0.0" +"@prettier/plugin-php@^0.1.0": + version "0.1.0" + resolved "https://registry.yarnpkg.com/@prettier/plugin-php/-/plugin-php-0.1.0.tgz#644e8d46a44813feb73c8ade8f312c15e610ef90" + dependencies: + php-parser glayzzle/php-parser#a8f10d8c9aacf8e90b283229f8bed76363b99fcf + abab@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/abab/-/abab-1.0.4.tgz#5faad9c2c07f60dd76770f71cf025b62a63cfd4e" @@ -1612,6 +1618,10 @@ performance-now@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" +"php-parser@github:glayzzle/php-parser#a8f10d8c9aacf8e90b283229f8bed76363b99fcf": + version "2.2.0" + resolved "https://codeload.github.com/glayzzle/php-parser/tar.gz/a8f10d8c9aacf8e90b283229f8bed76363b99fcf" + pify@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/pify/-/pify-3.0.0.tgz#e5a4acd2c101fdf3d9a4d07f0dbc4db49dd28176" @@ -1636,6 +1646,10 @@ preserve@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" +prettier@^1.11.1: + version "1.11.1" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.11.1.tgz#61e43fc4cd44e68f2b0dfc2c38cd4bb0fccdcc75" + pretty-format@^22.4.3: version "22.4.3" resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-22.4.3.tgz#f873d780839a9c02e9664c8a082e9ee79eaac16f"