Skip to content

Commit

Permalink
files support and small fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
bessudnov committed May 14, 2023
1 parent d2220fc commit fb7aa9c
Show file tree
Hide file tree
Showing 20 changed files with 576 additions and 93 deletions.
152 changes: 79 additions & 73 deletions README.md

Large diffs are not rendered by default.

43 changes: 41 additions & 2 deletions examples/files_actions.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<?php

use AmoCRM\AmoCRM\Models\Files\FileModel;
use AmoCRM\AmoCRM\Models\Files\FileUploadModel;
use AmoCRM\Collections\FileLinksCollection;
use AmoCRM\Models\FileLinkModel;
use AmoCRM\Models\Files\FileModel;
use AmoCRM\Models\Files\FileUploadModel;
use AmoCRM\Collections\CustomFieldsValuesCollection;
use AmoCRM\Enum\Chats\Templates\Attachment\TypesEnum;
use AmoCRM\Exceptions\AmoCRMApiException;
Expand Down Expand Up @@ -164,3 +166,40 @@ function (AccessTokenInterface $accessToken, string $baseDomain) {
//} catch (AmoCRMApiException $e) {
// printError($e);
//}


//Привяжем файл к сделке с ID 21825653, чтобы он отображался во вкладке файлы
try {
$result = $apiClient->entityFiles(EntityTypesInterface::LEADS, 21825653)->add(
(new FileLinksCollection())
->add(
(new FileLinkModel())
->setFileUuid($file->getUuid())
)
);
var_dump($result);
} catch (AmoCRMApiException $e) {
printError($e);
}

// Получим все файлы, связанные со сделкой 21825653
try {
$result = $apiClient->entityFiles(EntityTypesInterface::LEADS, 21825653)->get();
var_dump($result);
} catch (AmoCRMApiException $e) {
printError($e);
}

//Отвяжем файл от сделки с ID 21825653
try {
$result = $apiClient->entityFiles(EntityTypesInterface::LEADS, 21825653)->delete(
(new FileLinksCollection())
->add(
(new FileLinkModel())
->setFileUuid($file->getUuid())
)
);
var_dump($result);
} catch (AmoCRMApiException $e) {
printError($e);
}
17 changes: 17 additions & 0 deletions src/AmoCRM/Client/AmoCRMApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use AmoCRM\EntitiesServices\Customers\Transactions;
use AmoCRM\EntitiesServices\CustomFieldGroups;
use AmoCRM\EntitiesServices\CustomFields;
use AmoCRM\EntitiesServices\EntityFiles;
use AmoCRM\EntitiesServices\EntityNotes;
use AmoCRM\EntitiesServices\Files;
use AmoCRM\EntitiesServices\Sources;
Expand Down Expand Up @@ -388,6 +389,22 @@ public function files(?string $domain = null): Files
return new Files($request);
}

/**
* Метод вернет объект для работы со связями файлов с сущностями
*
* @param string $entityType
* @param int $entityId
*
* @return EntityFiles
* @throws InvalidArgumentException|AmoCRMMissedTokenException
*/
public function entityFiles(string $entityType, int $entityId): EntityFiles
{
return (new EntityFiles($this->buildRequest()))
->setEntityType($entityType)
->setEntityId($entityId);
}

/**
* Метод вернет объект ролей пользователей
*
Expand Down
89 changes: 89 additions & 0 deletions src/AmoCRM/Client/AmoCRMApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
class AmoCRMApiRequest
{
public const POST_REQUEST = 'POST';
public const PUT_REQUEST = 'PUT';
public const GET_REQUEST = 'GET';
public const PATCH_REQUEST = 'PATCH';
public const DELETE_REQUEST = 'DELETE';
Expand Down Expand Up @@ -205,6 +206,94 @@ public function post(
return $response;
}

/**
* @param string $method
* @param array|mixed $body
* @param array $queryParams
* @param array $headers
* @param bool $needToRefresh
* @param bool $isFullPath
*
* @return array
* @throws AmoCRMApiConnectExceptionException
* @throws AmoCRMApiException
* @throws AmoCRMApiHttpClientException
* @throws AmoCRMApiNoContentException
* @throws AmoCRMApiTooManyRedirectsException
* @throws AmoCRMoAuthApiException
*/
public function put(
string $method,
$body = [],
array $queryParams = [],
array $headers = [],
bool $needToRefresh = false,
bool $isFullPath = false
): array {
if ($this->accessToken->hasExpired()) {
$needToRefresh = true;
}

if ($needToRefresh) {
$this->refreshAccessToken();
}

$headers = array_merge($headers, $this->getBaseHeaders());

$this->lastHttpMethod = self::PUT_REQUEST;
$this->lastMethod = $isFullPath ? $method : $this->getUrl() . $method;
$this->lastBody = $body;
$this->lastQueryParams = $queryParams;

$requestOptions = [
'connect_timeout' => self::CONNECT_TIMEOUT,
'headers' => $headers,
'http_errors' => false,
'query' => $queryParams,
'timeout' => self::REQUEST_TIMEOUT,
];

if (is_array($body)) {
$requestOptions['json'] = $body;
} else {
$requestOptions['body'] = $body;
}

try {
$response = $this->httpClient->request(
self::PUT_REQUEST,
$isFullPath ? $method : $this->getUrl() . $method,
$requestOptions
);
} catch (ConnectException $e) {
throw new AmoCRMApiConnectExceptionException($e->getMessage(), $e->getCode(), $this->getLastRequestInfo());
} catch (TooManyRedirectsException $e) {
throw new AmoCRMApiTooManyRedirectsException($e->getMessage(), $e->getCode(), $this->getLastRequestInfo());
} catch (GuzzleException $e) {
throw new AmoCRMApiHttpClientException($e->getMessage(), $e->getCode(), $this->getLastRequestInfo());
}

if (!empty($response->getHeader('X-Request-Id'))) {
$this->lastRequestId = $response->getHeader('X-Request-Id')[0];
}

/**
* В случае получения ошибки авторизации, пробуем обновить токен 1 раз,
* если не получилось, то тогда уже выкидываем Exception
*/
try {
$response = $this->parseResponse($response);
} catch (AmoCRMoAuthApiException $e) {
if ($needToRefresh) {
throw $e;
}

return $this->post($method, $body, $queryParams, $headers, true);
}

return $response;
}

/**
* @param string $method
* @param array $body
Expand Down
1 change: 1 addition & 0 deletions src/AmoCRM/Collections/CustomFieldsValuesCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
* @method CustomFieldsValuesCollection prepend(BaseCustomFieldValuesModel $value)
* @method CustomFieldsValuesCollection add(BaseCustomFieldValuesModel $value)
* @method null|BaseCustomFieldValuesModel getBy($key, $value)
* @method static CustomFieldsValuesCollection fromArray(array $value)
*/
class CustomFieldsValuesCollection extends BaseApiCollection
{
Expand Down
30 changes: 30 additions & 0 deletions src/AmoCRM/Collections/FileLinksCollection.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace AmoCRM\Collections;

use AmoCRM\Models\FileLinkModel;

/**
* Class LinksCollection
*
* @package AmoCRM\Collections
*
* @method null|FileLinkModel current()
* @method null|FileLinkModel last()
* @method null|FileLinkModel first()
* @method null|FileLinkModel offsetGet($offset)
* @method void offsetSet($offset, FileLinkModel $value)
* @method FileLinksCollection prepend(FileLinkModel $value)
* @method FileLinksCollection add(FileLinkModel $value)
* @method null|FileLinkModel getBy($key, $value)
*/
class FileLinksCollection extends BaseApiCollection
{
/**
* Класс модели
* @var string
*/
public const ITEM_CLASS = FileLinkModel::class;
}
2 changes: 1 addition & 1 deletion src/AmoCRM/Collections/FilePreviewsCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace AmoCRM\Collections;

use AmoCRM\AmoCRM\Models\Files\FilePreviewModel;
use AmoCRM\Models\Files\FilePreviewModel;
use AmoCRM\Collections\Interfaces\HasPagesInterface;
use AmoCRM\Collections\Traits\PagesTrait;

Expand Down
3 changes: 1 addition & 2 deletions src/AmoCRM/Collections/FilesCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@

namespace AmoCRM\Collections;

use AmoCRM\AmoCRM\Models\Files\FileModel;
use AmoCRM\Models\Files\FileModel;
use AmoCRM\Collections\Interfaces\HasPagesInterface;
use AmoCRM\Collections\Traits\PagesTrait;
use AmoCRM\Models\BaseApiModel;

/**
* Class FilesCollection
Expand Down
3 changes: 1 addition & 2 deletions src/AmoCRM/EntitiesServices/BaseEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,9 +189,8 @@ protected function processAdd(BaseApiCollection $collection, array $response): B
public function add(BaseApiCollection $collection): BaseApiCollection
{
$response = $this->request->post($this->getMethod(), $collection->toApi());
$collection = $this->processAdd($collection, $response);

return $collection;
return $this->processAdd($collection, $response);
}

/**
Expand Down
54 changes: 54 additions & 0 deletions src/AmoCRM/EntitiesServices/BaseEntityTypeEntityIdEntity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);

namespace AmoCRM\EntitiesServices;

use AmoCRM\Exceptions\InvalidArgumentException;

/**
* Class BaseEntityTypeEntityIdEntity
*
* @package AmoCRM\EntitiesServices
*/
abstract class BaseEntityTypeEntityIdEntity extends BaseEntityIdEntity
{
protected $entityType = '';

/**
* @param string $entityType
*
* @return string
* @throws InvalidArgumentException
*/
abstract protected function validateEntityType(string $entityType): string;

/**
* @param string $entityType
* @return $this
* @throws InvalidArgumentException
*/
public function setEntityType(string $entityType): self
{
$entityType = $this->validateEntityType($entityType);
$this->entityType = $entityType;

return $this;
}

/**
* @return string
*/
public function getEntityType(): string
{
return $this->entityType;
}

/**
* @return string
*/
protected function getMethod(): string
{
return sprintf($this->method, $this->getEntityType(), $this->getEntityId());
}
}
2 changes: 1 addition & 1 deletion src/AmoCRM/EntitiesServices/Currencies.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class Currencies extends BaseEntity implements HasPageMethodsInterface
*/
protected function getEntitiesFromResponse(array $response): array
{
return (array) ($response[AmoCRMApiRequest::EMBEDDED][EntityTypesInterface::CURRENCIES] ?? []);
return (array)($response[AmoCRMApiRequest::EMBEDDED][EntityTypesInterface::CURRENCIES] ?? []);
}

/**
Expand Down
Loading

0 comments on commit fb7aa9c

Please sign in to comment.