From 37a390da093ae6c5082d309f4feb8ae42678697d Mon Sep 17 00:00:00 2001 From: Arhitector Date: Tue, 23 Aug 2016 01:57:59 +0300 Subject: [PATCH 1/4] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B3=D1=80=D0=B0=D0=BC=D0=BC=D0=B0?= =?UTF-8?q?=D1=82=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=B8=D1=85=20=D0=BE=D1=88?= =?UTF-8?q?=D0=B8=D0=B1=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 102 +++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 77 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 5883d12..9613a2d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,15 @@ ## Введение -Неофициальное PHP SDK для некоторых сервисов Яндекса:, поддерживаются сервисы: Яндекс.Диск. +Неофициальное PHP SDK для некоторых сервисов Яндекса: сервис Яндекс.Диск. + +## Список изменений + +23/08/2016 + +- метод `upload` поддерживает событие `progress`, слушатель принимает `float` значение в процентах. +- возвращена ранее удалённая опция `disable_redirects`. +- исправление грамматических ошибок в `README.md` ## Требования @@ -99,6 +107,8 @@ $removed = $resource->delete(); SDK вызывает исключения по каждой ситуации, следующий пример показывает как это можно использовать. ```php +try +{ try { /** @@ -156,7 +166,7 @@ $disk = new Arhitector\Yandex\Disk($client); $disk = new Arhitector\Yandex\Disk('OAuth-токен'); ``` -- Вариант 3. Инициализировать клиент Яндес.Диска без передачи Oauth-токена. +- Вариант 3. Инициализировать клиент Яндекс.Диска без передачи OAuth-токена. Вы можете установить или изменить OAuth-токен в ранее инициализированном объекте. @@ -380,7 +390,7 @@ public integer Объект::count( void ) **Примеры** ```php -// возвращает float свободное место +// Возвращает количество асинхронных операций экземпляра. $disk->count(); // в других случаях размер контейнера @@ -396,7 +406,7 @@ $resource->items->count(); > Примечание: возможно в будущем поведение метода будет упрощено. ```php -public boolean Объект::has([string $key = NULL]) +public bool Объект::has([string $key = NULL]) ``` `$key` - необязательный параметр, индекс. @@ -417,7 +427,7 @@ $resource->has(); // true #### Метод hasProperty -Метод является алиасом метода `has` но выполняет только одно действие - проверка свойства на существование и доступен только в контексте ресурса `Resource\\*` +Тоже самое что и метод `has`, но выполняет только одно действие - проверка свойства на существование и доступен только в контексте ресурса `Resource\\*` ```php public boolean Объект::hasProperty(string $key) @@ -854,7 +864,7 @@ $resource->move($resource2); Если ресурс уже существует будет вызвано исключение `AlreadyExists`. ```php -pubic $this Closed::create( void ) +public $this Closed::create( void ) ``` **Примеры** @@ -900,7 +910,7 @@ $resource->public_url; // URL адрес Метод `download` безопасен от переполнения памяти и может быть использован для скачивания файлов и папок (автоматически в виде zip-архива). ```php -public bool download(mixed $destination [, bool $overwrite = false]) +public bool Closed::download(mixed $destination [, bool $overwrite = false]) ``` `$destination` - позволяет указать куда будет сохранён ресурс. @@ -962,14 +972,14 @@ var_dump($stream->getSize()); Сделать копию ресурса. ```php -public bool copy(mixed $destination [,bool $overwrite = false]) +public bool Closed::copy(mixed $destination [,bool $overwrite = false]) ``` `$destination` - путь до нового ресурса. Может принимать значения: -- `string` - строка, путь от корня папки приложения или каорня Яндекс.Диска. +- `string` - строка, путь от корня папки приложения или корня Яндекс.Диска. - `Arhitector\Yandex\Disk\Resource\Closed` - инициализированный объект другого ресурса. `$overwrite` - признак перезаписи, если по указанному пути существует ресурс. Поведение по умолчанию `FALSE`. @@ -1060,10 +1070,8 @@ public Resource\Closed Disk::getPublishResource(string $public_key [, int $limit `$public_key` - публичный ключ или URL-адрес ресурса с открытым доступом. - `$limit` - Количество ресурсов в ответе, если это папка. - `$offset` - Смещение. Задаётся для списка всех файлов или если ресурс является папка, то задаёт смещение вложенных в папку ресурсов. **Примеры** @@ -1155,20 +1163,61 @@ $publicResource->getLink(); ``` ### 1.3.9.3. Скачивание публичного файла или папки. -/** - * Скачивание публичного файла или папки - * - * @param resource|StreamInterface|string $destination Путь, по которому будет сохранён файл - * StreamInterface будет записан в поток - * resource открытый на запись - * @param boolean $overwrite флаг перезаписи - * @param boolean $check_hash провести проверку целостности скачанного файла - * на основе хэша MD5 - * - * @return bool - */ - public function download($destination, $overwrite = false, $check_hash = false) - + +Скачивание публичного файла или папки (в виде zip-архива). + +```php +public bool Opened::download(mixed $destination [, bool $overwrite = false [, bool $check_hash = false]]) +``` + +`$destination` - Путь, по которому будет сохранён файл + +Принимает значения: + +- `string` - файловый путь. +- `resource` - открытый на запись дескриптор файла. +- `StreamInterface` - поток, открытый на запись. + +`$overwrite` - флаг перезаписи, если `$destination` является файловым путем. `FALSE` - поведение по умолчанию. + +`$check_hash` - провести проверку целостности скачанного файла. Значение `TRUE` позволяет проверить `md5` хеш скачанного файла. По умолчанию `FALSE`. + +**Примеры** + +```php +$publicResource->download(__DIR__.'/file.txt'); + +$publicResource->download(__DIR__.'/file.txt', true); + +$publicResource->download(__DIR__.'/file.txt', true, true); +``` + +Запись в открытый дескриптор. + +```php +// открыть любой дескриптор +$fp = fopen(__DIR__.'/файл.txt', 'wb+'); + +// или и т.д. +$fp = fopen('php://memory', 'r+b'); + +// true - провести проверку целостности скачанного файла +$publicResource->download($fp, false, true); + +// продолжить работу ... +fseek($fp, 0); +``` + +Использовать обертку над потоком так же просто. + +```php +$stream = new Stream('php://temp', 'r+'); + +$publicResource->download($stream); + +var_dump($stream->getSize()); +``` + ### 1.3.9.4. Есть ли доступ к этому файлу от имени владельца. /** @@ -1204,6 +1253,9 @@ $publicResource->getLink(); public function setPath($path) + + + ## 1.3.10. Работа с файлами в корзине. /** From 7636e6a85ea33cedf19a3fcdf344a4e1527a7bcc Mon Sep 17 00:00:00 2001 From: Arhitector Date: Tue, 23 Aug 2016 01:58:26 +0300 Subject: [PATCH 2/4] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20=D1=81=D0=BB=D1=83=D1=88=D0=B0=D1=82=D0=B5=D0=BB=D1=8C?= =?UTF-8?q?=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D0=BE=D1=82=D0=BE=D0=BA=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Client/Stream/Progress.php | 111 +++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 src/Client/Stream/Progress.php diff --git a/src/Client/Stream/Progress.php b/src/Client/Stream/Progress.php new file mode 100644 index 0000000..fd35129 --- /dev/null +++ b/src/Client/Stream/Progress.php @@ -0,0 +1,111 @@ +totalSize = $this->getSize(); + } + + /** + * Read data from the stream. + * + * @param int $length Read up to $length bytes from the object and return + * them. Fewer than $length bytes may be returned if underlying stream + * call returns fewer bytes. + * + * @return string Returns the data read from the stream, or an empty string + * if no bytes are available. + * @throws \RuntimeException if an error occurs. + */ + public function read($length) + { + $this->readSize += $length; + $percent = round(100 / $this->totalSize * $this->readSize, 2); + $this->emit('progress', min(100.0, $percent)); + + return parent::read($length); + } + + /** + * Returns the remaining contents in a string + * + * @return string + * @throws \RuntimeException if unable to read or an error occurs while + * reading. + */ + public function getContents() + { + $this->readSize = $this->totalSize; + $this->emit('progress', 100.0); + + return parent::getContents(); + } + + /** + * Seek to a position in the stream. + * + * @param int $offset Stream offset + * @param int $whence Specifies how the cursor position will be calculated + * based on the seek offset. Valid values are identical to the built-in + * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to + * offset bytes SEEK_CUR: Set position to current location plus offset + * SEEK_END: Set position to end-of-stream plus offset. + * + * @return bool + * @throws \RuntimeException on failure. + */ + public function seek($offset, $whence = SEEK_SET) + { + if (parent::seek($offset, $whence)) + { + $this->readSize = $offset; + + return true; + } + + return false; + } + +} \ No newline at end of file From 952296a3fd6271bacce68cc7133e0b091640c946 Mon Sep 17 00:00:00 2001 From: Arhitector Date: Tue, 23 Aug 2016 01:58:51 +0300 Subject: [PATCH 3/4] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20=D1=84=D0=B0=D0=B9=D0=BB=20.editorconfig?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .editorconfig | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..441d86a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,7 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +insert_final_newline = false From 9d98a66072e128eabcdf8ba1741175fab48dc14d Mon Sep 17 00:00:00 2001 From: Arhitector Date: Tue, 23 Aug 2016 02:00:02 +0300 Subject: [PATCH 4/4] =?UTF-8?q?=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5=D1=80=D0=B6?= =?UTF-8?q?=D0=BA=D0=B0=20=D1=81=D0=BE=D0=B1=D1=8B=D1=82=D0=B8=D1=8F=20'pr?= =?UTF-8?q?ogress'=20=D0=B4=D0=BB=D1=8F=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4?= =?UTF-8?q?=D0=B0=20'upload'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Disk/Resource/Closed.php | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/Disk/Resource/Closed.php b/src/Disk/Resource/Closed.php index fa066bf..946db48 100644 --- a/src/Disk/Resource/Closed.php +++ b/src/Disk/Resource/Closed.php @@ -12,12 +12,13 @@ */ namespace Arhitector\Yandex\Disk\Resource; - use Arhitector\Yandex\Client\Container; use Arhitector\Yandex\Client\Exception\NotFoundException; +use Arhitector\Yandex\Client\Stream\Progress; use Arhitector\Yandex\Disk; use Arhitector\Yandex\Disk\AbstractResource; use Arhitector\Yandex\Disk\Exception\AlreadyExistsException; +use League\Event\Event; use Psr\Http\Message\StreamInterface; use Zend\Diactoros\Request; use Zend\Diactoros\Stream; @@ -165,7 +166,7 @@ public function getProperties() * @param mixed $meta строка либо массив значений * @param mixed $value NULL чтобы удалить определённую метаинформаию когда $meta строка * - * @return \Arhitector\Yandex\Disk + * @return Closed * @throws \LengthException */ public function set($meta, $value = null) @@ -581,7 +582,8 @@ public function upload($file_path, $overwrite = false, $disable_redirects = fals $response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources/upload') ->withQuery(http_build_query([ 'url' => $file_path, - 'path' => $this->getPath() + 'path' => $this->getPath(), + 'disable_redirects' => (int) $disable_redirects ], null, '&')), 'POST')); } catch (AlreadyExistsException $exc) @@ -632,8 +634,19 @@ public function upload($file_path, $overwrite = false, $disable_redirects = fals // $this->client->setRetries = 1 throw new \RuntimeException('Не возможно загрузить локальный файл - не получено разрешение.'); } + + if ($this->getEmitter()->hasListeners('progress')) + { + $stream = new Progress($file_path, 'rb'); + $stream->addListener('progress', function (Event $event, $percent) { + $this->emit('progress', $percent); + }); + } + else + { + $stream = new Stream($file_path, 'rb'); + } - $stream = new Stream($file_path, 'rb'); $response = $this->client->send((new Request($access_upload['href'], 'PUT', $stream))); $this->emit('uploaded', $this, $this->client); $this->client->emit('uploaded', $this, $this->client); @@ -669,4 +682,4 @@ protected function createDocViewerUrl() return false; } -} \ No newline at end of file +}