From 41c24a23fd561abafc54f7f9ccacdd483656da8c Mon Sep 17 00:00:00 2001 From: Rene Schmidt Date: Tue, 25 Jun 2024 22:32:40 +0200 Subject: [PATCH] chore: fixed many issues --- composer.json | 3 +- phpstan-baseline.neon | 10 - phpstan.neon | 2 +- rector.php | 58 +++++ src/Http/Client.php | 6 - src/Resource/Account.php | 18 +- src/Resource/Auth.php | 2 +- src/Resource/Avatar.php | 3 +- src/Resource/Directory.php | 49 ++-- src/Resource/File.php | 173 ++++++------- src/Resource/Group.php | 2 +- src/Resource/Library.php | 18 +- src/Resource/Multi.php | 37 ++- src/Resource/Resource.php | 18 +- src/Resource/ShareLinks.php | 18 +- src/Resource/StarredFile.php | 31 +-- src/Type/Account.php | 47 ++-- src/Type/Avatar.php | 6 +- src/Type/DirectoryItem.php | 22 +- src/Type/FileHistoryItem.php | 4 +- src/Type/Group.php | 12 +- src/Type/SharedLink.php | 18 +- src/Type/SharedLinkPermissions.php | 5 +- src/Type/Type.php | 11 +- src/Type/TypeInterface.php | 5 - test/bootstrap.php | 6 +- test/functional/FunctionalTestCase.php | 24 +- test/functional/Resource/AccountTest.php | 34 +-- test/functional/Resource/FileTest.php | 71 +++--- test/functional/Resource/GroupTest.php | 13 +- test/functional/Resource/ShareLinksTest.php | 32 +-- test/functional/Resource/StarredFileTest.php | 39 ++- test/unit/Http/ClientUnitTest.php | 8 +- test/unit/Resource/AccountTest.php | 50 ++-- test/unit/Resource/AvatarTest.php | 24 +- test/unit/Resource/DirectoryTest.php | 125 ++++----- test/unit/Resource/FileTest.php | 254 ++++++++----------- test/unit/Resource/GroupTest.php | 3 +- test/unit/Resource/LibraryTest.php | 59 ++--- test/unit/Resource/MultiTest.php | 40 ++- test/unit/Resource/ResourceTest.php | 16 +- test/unit/Resource/ShareLinksTest.php | 48 ++-- test/unit/Resource/StarredFileTest.php | 90 +++---- test/unit/Stubs/FileResourceStub.php | 18 +- test/unit/Type/DirectoryItemUnitTest.php | 13 +- test/unit/Type/TypeUnitTest.php | 68 ++--- test/unit/UnitTestCase.php | 8 +- 47 files changed, 713 insertions(+), 908 deletions(-) create mode 100644 rector.php diff --git a/composer.json b/composer.json index 39d743d..0206933 100644 --- a/composer.json +++ b/composer.json @@ -33,7 +33,8 @@ "squizlabs/php_codesniffer": "~3.7", "phpunit/php-timer": "~5.0", "fzaninotto/faker": "~1.5", - "phpstan/phpstan": "^1.11" + "phpstan/phpstan": "^1.11", + "rector/rector": "^1.1" }, "type": "library", "autoload": { diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 6fcfd50..59114f6 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -35,11 +35,6 @@ parameters: count: 1 path: src/Resource/File.php - - - message: "#^Parameter \\#2 \\$uri of method GuzzleHttp\\\\Client\\:\\:request\\(\\) expects Psr\\\\Http\\\\Message\\\\UriInterface\\|string, array\\\\|string given\\.$#" - count: 1 - path: src/Resource/File.php - - message: "#^Method Seafile\\\\Client\\\\Resource\\\\Library\\:\\:decrypt\\(\\) has parameter \\$options with no value type specified in iterable type array\\.$#" count: 1 @@ -70,11 +65,6 @@ parameters: count: 1 path: src/Resource/Multi.php - - - message: "#^PHPDoc tag @return with type mixed is not subtype of native type string\\.$#" - count: 1 - path: src/Resource/Resource.php - - message: "#^PHPDoc tag @return with type mixed is not subtype of native type string\\.$#" count: 1 diff --git a/phpstan.neon b/phpstan.neon index d11daea..5f99112 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -2,4 +2,4 @@ includes: - phpstan-baseline.neon parameters: - level: 7 \ No newline at end of file + level: 7 diff --git a/rector.php b/rector.php new file mode 100644 index 0000000..5c04965 --- /dev/null +++ b/rector.php @@ -0,0 +1,58 @@ +paths([ + __DIR__ . '/src', + __DIR__ . '/test', + ]); + + $rectorConfig->phpVersion(PhpVersion::PHP_82); + + $rectorConfig->sets([ + LevelSetList::UP_TO_PHP_82, + SetList::CODE_QUALITY, + SetList::CODING_STYLE, + SetList::DEAD_CODE, + SetList::NAMING, + SetList::PRIVATIZATION, + SetList::STRICT_BOOLEANS, + DoctrineSetList::ANNOTATIONS_TO_ATTRIBUTES, + FOSRestSetList::ANNOTATIONS_TO_ATTRIBUTES, + SensiolabsSetList::ANNOTATIONS_TO_ATTRIBUTES, + SymfonySetList::ANNOTATIONS_TO_ATTRIBUTES, + SetList::TYPE_DECLARATION, // https://getrector.com/blog/new-in-rector-015-complete-safe-and-known-type-declarations + ]); + + $rectorConfig->rules([ + CountArrayToEmptyArrayComparisonRector::class, + DateFuncCallToCarbonRector::class, + LongArrayToShortArrayRector::class, + RenameVariableToMatchMethodCallReturnTypeRector::class, + SymplifyQuoteEscapeRector::class, + ExceptionHandlerTypehintRector::class + ]); + + $rectorConfig->importNames(); + $rectorConfig->autoloadPaths([ + __DIR__ . '/vendor/autoload.php', + ]); + + $rectorConfig->parallel(); +}; diff --git a/src/Http/Client.php b/src/Http/Client.php index d2db6bc..bb2c967 100644 --- a/src/Http/Client.php +++ b/src/Http/Client.php @@ -43,8 +43,6 @@ public function __construct(array $config = []) /** * @param string|UriInterface $uri URI for request - * @param array $options - * @return ResponseInterface * @throws GuzzleException */ public function get($uri, array $options = []): ResponseInterface @@ -54,8 +52,6 @@ public function get($uri, array $options = []): ResponseInterface /** * @param string|UriInterface $uri URI for request - * @param array $options - * @return ResponseInterface * @throws GuzzleException */ public function put($uri, array $options = []): ResponseInterface @@ -65,8 +61,6 @@ public function put($uri, array $options = []): ResponseInterface /** * @param string|UriInterface $uri URI for request - * @param array $options - * @return ResponseInterface * @throws GuzzleException */ public function delete($uri, array $options = []): ResponseInterface diff --git a/src/Resource/Account.php b/src/Resource/Account.php index 1a75487..688e3b8 100644 --- a/src/Resource/Account.php +++ b/src/Resource/Account.php @@ -3,6 +3,7 @@ namespace Seafile\Client\Resource; use Exception; +use GuzzleHttp\Exception\GuzzleException; use Seafile\Client\Type\Type; use \Seafile\Client\Type\Account as AccountType; use Seafile\Client\Type\TypeInterface; @@ -18,7 +19,7 @@ */ class Account extends Resource { - const API_VERSION = '2'; + public const API_VERSION = '2'; /** * List accounts @@ -27,6 +28,7 @@ class Account extends Resource * * @return AccountType[] * @throws Exception + * @throws GuzzleException */ public function getAll(): array { @@ -50,8 +52,8 @@ public function getAll(): array * * @param string $emailAddress Email address * - * @return AccountType * @throws Exception + * @throws GuzzleException */ public function getByEmail(string $emailAddress): AccountType { @@ -71,8 +73,8 @@ public function getByEmail(string $emailAddress): AccountType * * @param string $emailAddress Email address to get info of * - * @return AccountType|TypeInterface * @throws Exception + * @throws GuzzleException */ public function getInfo(string $emailAddress): TypeInterface { @@ -93,8 +95,8 @@ public function getInfo(string $emailAddress): TypeInterface * * @param AccountType $accountType AccountType instance with data for new account * - * @return bool * @throws Exception + * @throws GuzzleException */ public function create(AccountType $accountType): bool { @@ -128,7 +130,6 @@ public function create(AccountType $accountType): bool * * @param AccountType $accountType AccountType instance with updated data * - * @return bool * @throws Exception */ public function update(AccountType $accountType): bool @@ -212,8 +213,8 @@ public function update(AccountType $accountType): bool * * @param string $email Email address * - * @return bool * @throws Exception + * @throws GuzzleException */ public function removeByEmail(string $email): bool { @@ -226,12 +227,11 @@ public function removeByEmail(string $email): bool * Requires admin permissions * * @param AccountType $accountType Account to remove - * - * @return bool + * @throws GuzzleException */ public function remove(AccountType $accountType): bool { - if (empty($accountType->email)) { + if ($accountType->email === null || $accountType->email === '' || $accountType->email === '0') { return false; } diff --git a/src/Resource/Auth.php b/src/Resource/Auth.php index 3dec459..41b3505 100644 --- a/src/Resource/Auth.php +++ b/src/Resource/Auth.php @@ -13,5 +13,5 @@ */ class Auth extends Resource implements ResourceInterface { - const API_VERSION = '2'; + public const API_VERSION = '2'; } diff --git a/src/Resource/Avatar.php b/src/Resource/Avatar.php index 6ac7150..bedf2de 100644 --- a/src/Resource/Avatar.php +++ b/src/Resource/Avatar.php @@ -72,7 +72,7 @@ public function getGroupAvatar(GroupType $groupType, int $size = 80) */ protected function getAvatar(Type $type, int $size) { - if (!is_int($size) || $size < 1) { + if ($size < 1) { throw new Exception('Illegal avatar size'); } @@ -104,7 +104,6 @@ protected function getAvatar(Type $type, int $size) * * @param AccountType $accountType AccountType instance with data for new account * - * @return bool * @throws Exception */ public function createUserAvatar(AccountType $accountType): bool diff --git a/src/Resource/Directory.php b/src/Resource/Directory.php index a15afa9..95d7ddc 100644 --- a/src/Resource/Directory.php +++ b/src/Resource/Directory.php @@ -18,25 +18,25 @@ */ class Directory extends Resource { - const API_VERSION = '2'; + public const API_VERSION = '2'; /** * Get all items of a directory in a library * - * @param LibraryType $library Library type + * @param LibraryType $libraryType Library type * @param string $dir Directory path * * @return DirectoryItem[] * @throws Exception * @throws GuzzleException */ - public function getAll(LibraryType $library, string $dir = '/') + public function getAll(LibraryType $libraryType, string $dir = '/'): array { $clippedBaseUri = $this->clipUri($this->getApiBaseUrl()); $response = $this->client->request( 'GET', - $clippedBaseUri . '/repos/' . $library->id . '/dir/', + $clippedBaseUri . '/repos/' . $libraryType->id . '/dir/', [ 'query' => ['p' => $dir], ] @@ -63,17 +63,16 @@ public function getAll(LibraryType $library, string $dir = '/') /** * Check if $dirName exists within $parentDir * - * @param LibraryType $library Library instance + * @param LibraryType $libraryType Library instance * @param string $dirItemName DirectoryItem name * @param string $parentDir Parent directory * - * @return bool * @throws Exception * @throws GuzzleException */ - public function exists(LibraryType $library, string $dirItemName, string $parentDir = '/') + public function exists(LibraryType $libraryType, string $dirItemName, string $parentDir = '/'): bool { - $directoryItems = $this->getAll($library, $parentDir); + $directoryItems = $this->getAll($libraryType, $parentDir); foreach ($directoryItems as $directoryItem) { if ($directoryItem->name === $dirItemName) { @@ -87,7 +86,7 @@ public function exists(LibraryType $library, string $dirItemName, string $parent /** * Create directory within $parentDir * - * @param LibraryType $library Library instance + * @param LibraryType $libraryType Library instance * @param string $dirName Directory name * @param string $parentDir Parent directory * @param bool $recursive Recursive create @@ -96,7 +95,7 @@ public function exists(LibraryType $library, string $dirItemName, string $parent * @throws Exception * @throws GuzzleException */ - public function create(LibraryType $library, string $dirName, string $parentDir = '/', bool $recursive = false) + public function create(LibraryType $libraryType, string $dirName, string $parentDir = '/', bool $recursive = false) { if ($recursive) { $response = false; @@ -107,8 +106,8 @@ public function create(LibraryType $library, string $dirName, string $parentDir $parentPath = '/' . implode('/', $tmp); $tmp[] = $part; - if ($this->exists($library, $part, $parentPath) === false) { - $response = $this->create($library, $part, $parentPath, false); + if ($this->exists($libraryType, $part, $parentPath) === false) { + $response = $this->create($libraryType, $part, $parentPath, false); } } @@ -116,19 +115,19 @@ public function create(LibraryType $library, string $dirName, string $parentDir } // only create folder which is not empty to prevent wrong implementation - if (empty($dirName)) { + if ($dirName === '' || $dirName === '0') { return false; } // Do not create folders that already exist - if ($this->exists($library, $dirName, $parentDir)) { + if ($this->exists($libraryType, $dirName, $parentDir)) { return false; } $uri = sprintf( '%s/repos/%s/dir/?p=%s/%s', $this->clipUri($this->getApiBaseUrl()), - $library->id, + $libraryType->id, rtrim($parentDir, '/'), $dirName ); @@ -153,22 +152,20 @@ public function create(LibraryType $library, string $dirName, string $parentDir /** * Remove a directory * - * @param LibraryType $library Library instance + * @param LibraryType $libraryType Library instance * @param string $directoryPath Directory path - * - * @return bool */ - public function remove(LibraryType $library, string $directoryPath) + public function remove(LibraryType $libraryType, string $directoryPath): bool { // don't allow empty paths - if (empty($directoryPath)) { + if ($directoryPath === '' || $directoryPath === '0') { return false; } $uri = sprintf( '%s/repos/%s/dir/?p=%s', $this->clipUri($this->getApiBaseUrl()), - $library->id, + $libraryType->id, rtrim($directoryPath, '/') ); @@ -186,23 +183,21 @@ public function remove(LibraryType $library, string $directoryPath) /** * Rename a directory * - * @param LibraryType $library Library object + * @param LibraryType $libraryType Library object * @param string $directoryPath Directory path * @param string $newDirectoryName New directory name - * - * @return bool */ - public function rename(LibraryType $library, string $directoryPath, string $newDirectoryName) + public function rename(LibraryType $libraryType, string $directoryPath, string $newDirectoryName): bool { // don't allow empty paths - if (empty($directoryPath) || empty($newDirectoryName)) { + if ($directoryPath === '' || $directoryPath === '0' || ($newDirectoryName === '' || $newDirectoryName === '0')) { return false; } $uri = sprintf( '%s/repos/%s/dir/?p=%s', $this->clipUri($this->getApiBaseUrl()), - $library->id, + $libraryType->id, rtrim($directoryPath, '/') ); diff --git a/src/Resource/File.php b/src/Resource/File.php index 50b793f..04b56c2 100644 --- a/src/Resource/File.php +++ b/src/Resource/File.php @@ -4,8 +4,6 @@ use Exception; use GuzzleHttp\Exception\GuzzleException; -use GuzzleHttp\Psr7\Response; -use http\Env\Request; use InvalidArgumentException; use Psr\Http\Message\ResponseInterface; use Seafile\Client\Type\DirectoryItem; @@ -23,77 +21,73 @@ */ class File extends Resource { - const API_VERSION = '2'; + public const API_VERSION = '2'; /** * Mode of operation: copy */ - const OPERATION_COPY = 1; + public const OPERATION_COPY = 1; /** * Mode of operation: move */ - const OPERATION_MOVE = 2; + public const OPERATION_MOVE = 2; /** * Mode of operation: create */ - const OPERATION_CREATE = 3; + public const OPERATION_CREATE = 3; /** * Get download URL of a file * - * @param LibraryType $library Library instance - * @param DirectoryItem $item Item instance + * @param LibraryType $libraryType Library instance + * @param DirectoryItem $directoryItem Item instance * @param string $dir Dir string * @param int $reuse Reuse more than once per hour * - * @return string * @throws GuzzleException */ - public function getDownloadUrl(LibraryType $library, DirectoryItem $item, string $dir = '/', int $reuse = 1) + public function getDownloadUrl(LibraryType $libraryType, DirectoryItem $directoryItem, string $dir = '/', int $reuse = 1): ?string { $url = $this->getApiBaseUrl() . '/repos/' - . $library->id + . $libraryType->id . '/file/' . '?reuse=' . $reuse - . '&p=' . $this->urlEncodePath($dir . $item->name); + . '&p=' . $this->urlEncodePath($dir . $directoryItem->name); $response = $this->client->request('GET', $url); $downloadUrl = (string)$response->getBody(); - return preg_replace("/\"/", '', $downloadUrl); + return preg_replace('/"/', '', $downloadUrl); } /** * URL-encode path string * * @param string $path Path string - * - * @return string */ - protected function urlEncodePath(string $path) + protected function urlEncodePath(string $path): string { - return implode('/', array_map('rawurlencode', explode('/', (string)$path))); + return implode('/', array_map('rawurlencode', explode('/', $path))); } /** * Get download URL of a file from a Directory item * - * @param LibraryType $library Library instance - * @param DirectoryItem $item Item instance + * @param LibraryType $libraryType Library instance + * @param DirectoryItem $directoryItem Item instance * @param string $localFilePath Save file to path * @param string $dir Dir string * @param int $reuse Reuse more than once per hour * - * @return ResponseInterface * @throws Exception * @throws GuzzleException */ public function downloadFromDir( - LibraryType $library, - DirectoryItem $item, + LibraryType $libraryType, + DirectoryItem $directoryItem, string $localFilePath, string $dir, int $reuse = 1 @@ -103,7 +97,7 @@ public function downloadFromDir( throw new Exception('File already exists'); } - $downloadUrl = $this->getDownloadUrl($library, $item, $dir, $reuse); + $downloadUrl = $this->getDownloadUrl($libraryType, $directoryItem, $dir, $reuse); return $this->client->request('GET', $downloadUrl, ['save_to' => $localFilePath]); } @@ -111,64 +105,62 @@ public function downloadFromDir( /** * Get download URL of a file * - * @param LibraryType $library Library instance + * @param LibraryType $libraryType Library instance * @param string $filePath Save file to path * @param string $localFilePath Local file path * @param int $reuse Reuse more than once per hour * - * @return ResponseInterface * @throws Exception * @throws GuzzleException */ - public function download(LibraryType $library, string $filePath, string $localFilePath, int $reuse = 1) + public function download(LibraryType $libraryType, string $filePath, string $localFilePath, int $reuse = 1): ResponseInterface { - $item = new DirectoryItem(); - $item->name = basename($filePath); + $directoryItem = new DirectoryItem(); + $directoryItem->name = basename($filePath); $dir = str_replace("\\", "/", dirname($filePath)); // compatibility for windows - return $this->downloadFromDir($library, $item, $localFilePath, $dir, $reuse); + return $this->downloadFromDir($libraryType, $directoryItem, $localFilePath, $dir, $reuse); } /** * Update file * - * @param LibraryType $library Library instance + * @param LibraryType $libraryType Library instance * @param string $localFilePath Local file path * @param string $dir Library dir * @param mixed $filename File name, or false to use the name from $localFilePath * - * @return ResponseInterface * @throws Exception * @throws GuzzleException */ - public function update(LibraryType $library, string $localFilePath, string $dir = '/', $filename = false): ResponseInterface + public function update(LibraryType $libraryType, string $localFilePath, string $dir = '/', mixed $filename = false): ResponseInterface { - return $this->upload($library, $localFilePath, $dir, $filename, false); + return $this->upload($libraryType, $localFilePath, $dir, $filename, false); } /** * Get upload URL * - * @param LibraryType $library Library instance + * @param LibraryType $libraryType Library instance * @param bool $newFile Is new file (=upload) or not (=update) * @param string $dir Directory to upload to * * @return String Upload link * @throws GuzzleException */ - public function getUploadUrl(LibraryType $library, bool $newFile = true, string $dir = "/"): string + public function getUploadUrl(LibraryType $libraryType, bool $newFile = true, string $dir = "/"): string { $url = $this->getApiBaseUrl() . '/repos/' - . $library->id + . $libraryType->id . '/' . ($newFile ? 'upload' : 'update') . '-link/' . '?p=' . $dir; $response = $this->client->request('GET', $url); $uploadLink = (string)$response->getBody(); - return preg_replace("/\"/", '', $uploadLink); + return preg_replace('/"/', '', $uploadLink); } /** @@ -178,21 +170,15 @@ public function getUploadUrl(LibraryType $library, bool $newFile = true, string * @param string $dir Library dir * @param bool $newFile Is new file (=upload) or not (=update) * @param mixed $newFilename New file name, or false to use the name from $localFilePath - * - * @return array */ public function getMultiPartParams( string $localFilePath, string $dir, bool $newFile = true, - $newFilename = false + mixed $newFilename = false ): array { - if ($newFilename === false) { - $fileBaseName = basename($localFilePath); - } else { - $fileBaseName = $newFilename; - } + $fileBaseName = $newFilename === false ? basename($localFilePath) : $newFilename; $multiPartParams = [ [ @@ -228,21 +214,20 @@ public function getMultiPartParams( /** * Upload file * - * @param LibraryType $library Library instance + * @param LibraryType $libraryType Library instance * @param string $localFilePath Local file path * @param string $dir Library dir * @param mixed $newFilename New file name, or false to use the name from $localFilePath * @param bool $newFile Is new file (=upload) or not (=update) * - * @return ResponseInterface * @throws Exception * @throws GuzzleException */ public function upload( - LibraryType $library, + LibraryType $libraryType, string $localFilePath, string $dir = '/', - $newFilename = false, + mixed $newFilename = false, bool $newFile = true ): ResponseInterface { @@ -252,7 +237,7 @@ public function upload( return $this->client->request( 'POST', - $this->getUploadUrl($library, $newFile, $dir), + $this->getUploadUrl($libraryType, $newFile, $dir), [ 'headers' => ['Accept' => '*/*'], 'multipart' => $this->getMultiPartParams($localFilePath, $dir, $newFile, $newFilename), @@ -263,18 +248,17 @@ public function upload( /** * Get file detail * - * @param LibraryType $library Library instance + * @param LibraryType $libraryType Library instance * @param string $remoteFilePath Remote file path * - * @return DirectoryItem * @throws GuzzleException * @throws Exception */ - public function getFileDetail(LibraryType $library, string $remoteFilePath): DirectoryItem + public function getFileDetail(LibraryType $libraryType, string $remoteFilePath): DirectoryItem { $url = $this->getApiBaseUrl() . '/repos/' - . $library->id + . $libraryType->id . '/file/detail/' . '?p=' . $this->urlEncodePath($remoteFilePath); @@ -288,23 +272,22 @@ public function getFileDetail(LibraryType $library, string $remoteFilePath): Dir /** * Remove a file * - * @param LibraryType $library Library object + * @param LibraryType $libraryType Library object * @param string $filePath File path * - * @return bool * @throws GuzzleException */ - public function remove(LibraryType $library, string $filePath): bool + public function remove(LibraryType $libraryType, string $filePath): bool { // do not allow empty paths - if (empty($filePath)) { + if ($filePath === '' || $filePath === '0') { return false; } $uri = sprintf( '%s/repos/%s/file/?p=%s', $this->clipUri($this->getApiBaseUrl()), - $library->id, + $libraryType->id, $this->urlEncodePath($filePath) ); @@ -322,29 +305,28 @@ public function remove(LibraryType $library, string $filePath): bool /** * Rename a file * - * @param LibraryType $library Library object - * @param DirectoryItem $dirItem Directory item to rename + * @param LibraryType $libraryType Library object + * @param DirectoryItem $directoryItem Directory item to rename * @param string $newFilename New file name; see "Issues" in the readme * - * @return bool * @throws GuzzleException */ - public function rename(LibraryType $library, DirectoryItem $dirItem, string $newFilename): bool + public function rename(LibraryType $libraryType, DirectoryItem $directoryItem, string $newFilename): bool { - $filePath = $dirItem->dir . $dirItem->name; + $filePath = $directoryItem->dir . $directoryItem->name; - if (empty($filePath)) { + if ($filePath === '' || $filePath === '0') { throw new InvalidArgumentException('Invalid file path: must not be empty'); } - if (empty($newFilename) || strpos($newFilename, '/') === 0) { + if ($newFilename === '' || $newFilename === '0' || str_starts_with($newFilename, '/')) { throw new InvalidArgumentException('Invalid new file name: length must be >0 and must not start with /'); } $uri = sprintf( '%s/repos/%s/file/?p=%s', $this->clipUri($this->getApiBaseUrl()), - $library->id, + $libraryType->id, $this->urlEncodePath($filePath) ); @@ -369,7 +351,7 @@ public function rename(LibraryType $library, DirectoryItem $dirItem, string $new $success = $response->getStatusCode() === 200; if ($success) { - $dirItem->name = $newFilename; + $directoryItem->name = $newFilename; } return $success; @@ -384,7 +366,6 @@ public function rename(LibraryType $library, DirectoryItem $dirItem, string $new * @param string $dstDirectoryPath Destination directory path * @param int $operation Operation mode * - * @return bool * @throws GuzzleException */ public function copy( @@ -396,7 +377,7 @@ public function copy( ): bool { // do not allow empty paths - if (empty($srcFilePath) || empty($dstDirectoryPath)) { + if ($srcFilePath === '' || $srcFilePath === '0' || ($dstDirectoryPath === '' || $dstDirectoryPath === '0')) { return false; } @@ -448,7 +429,6 @@ public function copy( * @param LibraryType $dstLibrary Destination library object * @param string $dstDirectoryPath Destination directory path * - * @return bool * @throws GuzzleException */ public function move( @@ -464,50 +444,48 @@ public function move( /** * Get file revision download URL * - * @param LibraryType $library Source library object - * @param DirectoryItem $dirItem Item instance + * @param LibraryType $libraryType Source library object + * @param DirectoryItem $directoryItem Item instance * @param FileHistoryItem $fileHistoryItem FileHistory item instance * - * @return string|string[] * @throws GuzzleException */ public function getFileRevisionDownloadUrl( - LibraryType $library, - DirectoryItem $dirItem, + LibraryType $libraryType, + DirectoryItem $directoryItem, FileHistoryItem $fileHistoryItem - ) + ): ?string { $url = $this->getApiBaseUrl() . '/repos/' - . $library->id + . $libraryType->id . '/file/revision/' - . '?p=' . $this->urlEncodePath($dirItem->path . $dirItem->name) + . '?p=' . $this->urlEncodePath($directoryItem->path . $directoryItem->name) . '&commit_id=' . $fileHistoryItem->id; $response = $this->client->request('GET', $url); - return preg_replace("/\"/", '', (string)$response->getBody()); + return preg_replace('/"/', '', (string)$response->getBody()); } /** * Download file revision * - * @param LibraryType $library Source library object - * @param DirectoryItem $dirItem Item instance + * @param LibraryType $libraryType Source library object + * @param DirectoryItem $directoryItem Item instance * @param FileHistoryItem $fileHistoryItem FileHistory item instance * @param string $localFilePath Save file to path. Existing files will be overwritten without warning * - * @return ResponseInterface * @throws GuzzleException */ public function downloadRevision( - LibraryType $library, - DirectoryItem $dirItem, + LibraryType $libraryType, + DirectoryItem $directoryItem, FileHistoryItem $fileHistoryItem, string $localFilePath ): ResponseInterface { - $downloadUrl = $this->getFileRevisionDownloadUrl($library, $dirItem, $fileHistoryItem); + $downloadUrl = $this->getFileRevisionDownloadUrl($libraryType, $directoryItem, $fileHistoryItem); return $this->client->request('GET', $downloadUrl, ['save_to' => $localFilePath]); } @@ -515,20 +493,20 @@ public function downloadRevision( /** * Get history of a file DirectoryItem * - * @param LibraryType $library Library instance - * @param DirectoryItem $item Item instance + * @param LibraryType $libraryType Library instance + * @param DirectoryItem $directoryItem Item instance * * @return FileHistoryItem[] * @throws GuzzleException * @throws Exception */ - public function getHistory(LibraryType $library, DirectoryItem $item) + public function getHistory(LibraryType $libraryType, DirectoryItem $directoryItem): array { $url = $this->getApiBaseUrl() . '/repos/' - . $library->id + . $libraryType->id . '/file/history/' - . '?p=' . $this->urlEncodePath($item->path . $item->name); + . '?p=' . $this->urlEncodePath($directoryItem->path . $directoryItem->name); $response = $this->client->request('GET', $url); @@ -546,24 +524,23 @@ public function getHistory(LibraryType $library, DirectoryItem $item) /** * Create empty file on Seafile server * - * @param LibraryType $library Library instance - * @param DirectoryItem $item Item instance + * @param LibraryType $libraryType Library instance + * @param DirectoryItem $directoryItem Item instance * - * @return bool * @throws GuzzleException */ - public function create(LibraryType $library, DirectoryItem $item): bool + public function create(LibraryType $libraryType, DirectoryItem $directoryItem): bool { // do not allow empty paths - if (empty($item->path)) { + if (empty($directoryItem->path)) { return false; } $uri = sprintf( '%s/repos/%s/file/?p=%s', $this->clipUri($this->getApiBaseUrl()), - $library->id, - $this->urlEncodePath($item->path . $item->name) + $libraryType->id, + $this->urlEncodePath($directoryItem->path . $directoryItem->name) ); $response = $this->client->request( diff --git a/src/Resource/Group.php b/src/Resource/Group.php index 8f8416a..6573034 100644 --- a/src/Resource/Group.php +++ b/src/Resource/Group.php @@ -16,7 +16,7 @@ */ class Group extends Resource { - const API_VERSION = '2'; + public const API_VERSION = '2'; /** * List groups diff --git a/src/Resource/Library.php b/src/Resource/Library.php index 892fd4d..0d62d37 100644 --- a/src/Resource/Library.php +++ b/src/Resource/Library.php @@ -17,7 +17,7 @@ */ class Library extends Resource { - const API_VERSION = '2'; + public const API_VERSION = '2'; /** * List libraries @@ -45,10 +45,9 @@ public function getAll(): array * * @param string $libraryId Library ID * - * @return LibraryType * @throws Exception */ - public function getById($libraryId): LibraryType + public function getById(string $libraryId): LibraryType { $response = $this->client->request( 'GET', @@ -70,7 +69,7 @@ public function getById($libraryId): LibraryType * * @throws Exception */ - public function decrypt($libraryId, array $options): bool + public function decrypt(string $libraryId, array $options): bool { $hasQueryParams = array_key_exists('query', $options); $hasPassword = $hasQueryParams && array_key_exists('password', $options['query']); @@ -94,7 +93,6 @@ public function decrypt($libraryId, array $options): bool * @param string $value Library name * @param string $attribute Attribute name of library * - * @return bool * @throws Exception * @throws GuzzleException */ @@ -102,8 +100,8 @@ public function exists($value, $attribute = 'name'): bool { $libraries = $this->getAll(); - foreach ($libraries as $lib) { - if (isset($lib->{$attribute}) && $lib->{$attribute} === $value) { + foreach ($libraries as $library) { + if (isset($library->{$attribute}) && $library->{$attribute} === $value) { return true; } } @@ -118,7 +116,6 @@ public function exists($value, $attribute = 'name'): bool * @param string $description Library description * @param string $password false means no encryption, any other string is used as password * - * @return bool * @throws Exception * @throws GuzzleException */ @@ -174,7 +171,6 @@ public function create($name, $description = "new repo", $password = ''): bool * * @param string $libraryId Library ID * - * @return bool * @throws GuzzleException */ public function remove($libraryId): bool @@ -207,8 +203,6 @@ public function remove($libraryId): bool * @param string $libraryId Library ID * @param array $users Comma separated list of user email addresses * @param string $permission The permission of the shared library - * - * @return bool */ public function sharePersonal($libraryId, array $users, string $permission = Resource::PERMISSION_R): bool { @@ -216,7 +210,7 @@ public function sharePersonal($libraryId, array $users, string $permission = Res '%s/shared-repos/%s/?share_type=personal&users=%s&permission=%s', $this->clipUri($this->getApiBaseUrl()), $libraryId, - join(',', $users), + implode(',', $users), $permission ); diff --git a/src/Resource/Multi.php b/src/Resource/Multi.php index ab7884b..341c750 100644 --- a/src/Resource/Multi.php +++ b/src/Resource/Multi.php @@ -16,17 +16,17 @@ */ class Multi extends Resource { - const API_VERSION = '2'; + public const API_VERSION = '2'; /** * Mode of operation: copy */ - const OPERATION_COPY = 1; + public const OPERATION_COPY = 1; /** * Mode of operation: move */ - const OPERATION_MOVE = 2; + public const OPERATION_MOVE = 2; /** * Move multiple files or folders @@ -36,7 +36,6 @@ class Multi extends Resource * @param LibraryType $dstLibrary Destination library object * @param string $dstDirectoryPath Destination directory Path * - * @return bool * @throws GuzzleException */ public function move( @@ -58,7 +57,6 @@ public function move( * @param string $dstDirectoryPath Destination directory Path * @param int $operation self::OPERATION_COPY or self::OPERATION_MOVE * - * @return bool * @throws GuzzleException */ public function copy( @@ -70,7 +68,7 @@ public function copy( ): bool { // do not allow empty paths - if (empty($srcPaths) || empty($dstDirectoryPath)) { + if ($srcPaths === [] || ($dstDirectoryPath === '' || $dstDirectoryPath === '0')) { return false; } @@ -78,11 +76,11 @@ public function copy( // get the source folder path // this path must be the same for all files! - $srcFolderPath = dirname($srcPaths[0]); + $srcFolderPath = dirname((string) $srcPaths[0]); $dstFileNames = $this->preparePaths($srcFolderPath, $srcPaths); - if (empty($dstFileNames)) { + if ($dstFileNames === '' || $dstFileNames === '0') { return false; } @@ -127,19 +125,19 @@ public function copy( * @param string $folder Folder path * @param array $paths Paths of files * @param string $fileNames Optional file names - * - * @return string */ protected function preparePaths(string $folder, array $paths, string $fileNames = ''): string { foreach ($paths as $path) { - if (dirname($path) != $folder) { + if (dirname((string) $path) !== $folder) { return ''; // all source paths must be the same } - if ($fileNames != '') { + + if ($fileNames !== '') { $fileNames .= ':'; } - $fileNames .= basename($path); + + $fileNames .= basename((string) $path); } return $fileNames; @@ -148,26 +146,25 @@ protected function preparePaths(string $folder, array $paths, string $fileNames /** * Delete multiple files or folders * - * @param LibraryType $library Library object + * @param LibraryType $libraryType Library object * @param array $paths Array with file and folder paths (they must be in the same folder) * - * @return bool * @throws GuzzleException */ - public function delete(LibraryType $library, array $paths): bool + public function delete(LibraryType $libraryType, array $paths): bool { // do not allow empty paths - if (empty($paths)) { + if ($paths === []) { return false; } // get the folder path // this path must be the same for all files! - $folderPath = dirname($paths[0]); + $folderPath = dirname((string) $paths[0]); $fileNames = $this->preparePaths($folderPath, $paths); - if (empty($fileNames)) { + if ($fileNames === '' || $fileNames === '0') { return false; } @@ -176,7 +173,7 @@ public function delete(LibraryType $library, array $paths): bool $uri = sprintf( '%s/repos/%s/fileops/delete/?p=%s', $this->clipUri($this->getApiBaseUrl()), - $library->id, + $libraryType->id, $folderPath ); diff --git a/src/Resource/Resource.php b/src/Resource/Resource.php index 64ddc29..40835a4 100644 --- a/src/Resource/Resource.php +++ b/src/Resource/Resource.php @@ -15,33 +15,25 @@ */ abstract class Resource implements ResourceInterface { - const API_VERSION = '2.1'; + public const API_VERSION = '2.1'; /** Represents 'read' permission (in whatever context) */ - const PERMISSION_R = 'r'; + public const PERMISSION_R = 'r'; /** Represents 'read and write' permission (in whatever context) */ - const PERMISSION_RW = 'rw'; - - /** - * @var Client - */ - protected $client; + public const PERMISSION_RW = 'rw'; /** * Constructor * * @param Client $client Client instance */ - public function __construct(Client $client) + public function __construct(protected Client $client) { - $this->client = $client; } /** * Get the actual API base URL depending on the resource - * - * @return string */ public function getApiBaseUrl(): string { @@ -52,8 +44,6 @@ public function getApiBaseUrl(): string * Clip tailing slash * * @param string $uri URI string - * - * @return mixed|string */ public function clipUri(string $uri): string { diff --git a/src/Resource/ShareLinks.php b/src/Resource/ShareLinks.php index acafb66..a3c512d 100644 --- a/src/Resource/ShareLinks.php +++ b/src/Resource/ShareLinks.php @@ -45,8 +45,6 @@ public function getAll(): array * Remove shared link * * @param SharedLinkType $sharedLinkType SharedLinkType instance - * - * @return bool */ public function remove(SharedLinkType $sharedLinkType): bool { @@ -76,20 +74,18 @@ public function remove(SharedLinkType $sharedLinkType): bool /** * Create share link * - * @param LibraryType $library Library instance + * @param LibraryType $libraryType Library instance * @param string $path Path - * @param SharedLinkPermissions $permissions * @param int|null $expire Expire in such many days * @param string|null $password Optional password string * - * @return SharedLinkType|null * @throws GuzzleException * @throws Exception */ public function create( - LibraryType $library, + LibraryType $libraryType, string $path, - SharedLinkPermissions $permissions, + SharedLinkPermissions $sharedLinkPermissions, int $expire = null, string $password = null ): ?SharedLinkType @@ -100,19 +96,19 @@ public function create( ); $multiPartParams = [ - ['name' => 'repo_id', 'contents' => $library->id], + ['name' => 'repo_id', 'contents' => $libraryType->id], ['name' => 'path', 'contents' => $path], [ 'name' => 'permissions', 'contents' => json_encode([ - 'can_edit' => $permissions->is(SharedLinkPermissions::CAN_EDIT), - 'can_download' => $permissions->is(SharedLinkPermissions::CAN_DOWNLOAD) + 'can_edit' => $sharedLinkPermissions->is(SharedLinkPermissions::CAN_EDIT), + 'can_download' => $sharedLinkPermissions->is(SharedLinkPermissions::CAN_DOWNLOAD) ]) ] ]; if (!is_null($expire)) { - $multiPartParams[] = ['name' => 'expire_days', 'contents' => "$expire"]; + $multiPartParams[] = ['name' => 'expire_days', 'contents' => '' . $expire]; } if (!is_null($password)) { diff --git a/src/Resource/StarredFile.php b/src/Resource/StarredFile.php index 972514f..a7559f0 100644 --- a/src/Resource/StarredFile.php +++ b/src/Resource/StarredFile.php @@ -21,12 +21,9 @@ */ class StarredFile extends Resource { - const API_VERSION = '2'; + public const API_VERSION = '2'; - /** - * @var string - */ - protected $resourceUri = ''; + protected string $resourceUri; /** * Constructor @@ -65,15 +62,15 @@ public function getAll(): array /** * Create directory within $parentDir * - * @param LibraryType $library Library instance - * @param DirectoryItem $dirItem DirectoryItem instance to star + * @param LibraryType $libraryType Library instance + * @param DirectoryItem $directoryItem DirectoryItem instance to star * * @return string URL of starred file list * @throws Exception */ - public function star(LibraryType $library, DirectoryItem $dirItem): string + public function star(LibraryType $libraryType, DirectoryItem $directoryItem): string { - if ($dirItem->type !== 'file') { + if ($directoryItem->type !== 'file') { throw new Exception('Cannot star other items than files.'); } @@ -85,11 +82,11 @@ public function star(LibraryType $library, DirectoryItem $dirItem): string 'multipart' => [ [ 'name' => 'repo_id', - 'contents' => $library->id, + 'contents' => $libraryType->id, ], [ 'name' => 'p', - 'contents' => $dirItem->path, + 'contents' => $directoryItem->path, ], ], ] @@ -105,18 +102,16 @@ public function star(LibraryType $library, DirectoryItem $dirItem): string /** * Unstar a file * - * @param LibraryType $library Library instance - * @param DirectoryItem $dirItem DirectoryItem instance - * - * @return bool + * @param LibraryType $libraryType Library instance + * @param DirectoryItem $directoryItem DirectoryItem instance */ - public function unstar(LibraryType $library, DirectoryItem $dirItem): bool + public function unstar(LibraryType $libraryType, DirectoryItem $directoryItem): bool { $uri = sprintf( '%s/?repo_id=%s&p=%s', $this->resourceUri, - $library->id, - $dirItem->path + $libraryType->id, + $directoryItem->path ); $response = $this->client->request('DELETE', $uri); diff --git a/src/Type/Account.php b/src/Type/Account.php index c3517fb..0f9ac08 100644 --- a/src/Type/Account.php +++ b/src/Type/Account.php @@ -18,83 +18,68 @@ */ class Account extends Type { - /** - * @var string|null - */ - public $contactEmail = null; + public ?string $contactEmail = null; - /** - * @var DateTime|null - */ - public $createTime = null; + public ?DateTime $createTime = null; - /** - * @var string|null - */ - public $department = null; + public ?string $department = null; - /** - * @var string|null - */ - public $email = null; + public ?string $email = null; - /** - * @var int|null - */ - public $id = null; + public ?int $id = null; /** * @var string|null */ - public $institution = null; + public $institution; /** * @var bool|null */ - public $isStaff = null; + public $isStaff; /** * @var bool|null */ - public $isActive = null; + public $isActive; /** * @var string|null */ - public $loginId = null; + public $loginId; /** * @var string|null */ - public $name = null; + public $name; /** * @var string|null */ - public $note = null; + public $note; /** * @var string|null */ - public $password = null; + public $password; /** * @var int|null */ - public $storage = null; + public $storage; /** * @var int|null */ - public $spaceQuota = null; + public $spaceQuota; /** * @var int|null */ - public $total = null; + public $total; /** * @var int|null */ - public $usage = null; + public $usage; } diff --git a/src/Type/Avatar.php b/src/Type/Avatar.php index 97dad36..4b3fc0a 100644 --- a/src/Type/Avatar.php +++ b/src/Type/Avatar.php @@ -21,15 +21,15 @@ class Avatar extends Type /** * @var string|null */ - public $url = null; + public $url; /** * @var bool|null */ - public $isDefault = null; + public $isDefault; /** * @var DateTime|null */ - public $mtime = null; + public $mtime; } diff --git a/src/Type/DirectoryItem.php b/src/Type/DirectoryItem.php index 456eafe..7e3a41e 100644 --- a/src/Type/DirectoryItem.php +++ b/src/Type/DirectoryItem.php @@ -41,17 +41,17 @@ class DirectoryItem extends Type /** * @var int|null */ - public $org = null; + public $org; /** * @var string|null */ - public $path = null; + public $path; /** * @var string|null */ - public $repo = null; + public $repo; /** * @var string @@ -63,15 +63,15 @@ class DirectoryItem extends Type */ public $type = ""; - const TYPE_DIR = 'dir'; - const TYPE_FILE = 'file'; + public const TYPE_DIR = 'dir'; + + public const TYPE_FILE = 'file'; /** * Populate from array * * @param array $fromArray Create from array * - * @return DirectoryItem * @throws Exception */ public function fromArray(array $fromArray): DirectoryItem @@ -79,15 +79,15 @@ public function fromArray(array $fromArray): DirectoryItem $typeExists = array_key_exists('type', $fromArray); $dirExists = array_key_exists('dir', $fromArray); - if ($typeExists === false && $dirExists === true && is_bool($fromArray['dir'])) { - $fromArray['type'] = $fromArray['dir'] === true ? self::TYPE_DIR : self::TYPE_FILE; + if ($typeExists === false && $dirExists && is_bool($fromArray['dir'])) { + $fromArray['type'] = $fromArray['dir'] ? self::TYPE_DIR : self::TYPE_FILE; } /** - * @var self $dirItem + * @var self $type */ - $dirItem = parent::fromArray($fromArray); + $type = parent::fromArray($fromArray); - return $dirItem; + return $type; } } diff --git a/src/Type/FileHistoryItem.php b/src/Type/FileHistoryItem.php index 557b930..aa36f89 100644 --- a/src/Type/FileHistoryItem.php +++ b/src/Type/FileHistoryItem.php @@ -31,7 +31,7 @@ class FileHistoryItem extends Type /** * @var DateTime|null */ - public $ctime = null; + public $ctime; /** * @var string @@ -95,5 +95,5 @@ class FileHistoryItem extends Type /** * @var int|null */ - public $secondParentId = null; + public $secondParentId; } diff --git a/src/Type/Group.php b/src/Type/Group.php index 0ef91c5..8e7e50f 100644 --- a/src/Type/Group.php +++ b/src/Type/Group.php @@ -21,30 +21,30 @@ class Group extends Type /** * @var int|null */ - public $ctime = null; + public $ctime; /** * @var AccountType|null */ - public $creator = null; + public $creator; /** * @var int|null */ - public $msgnum = null; + public $msgnum; /** * @var int|null */ - public $mtime = null; + public $mtime; /** * @var int|null */ - public $id = null; + public $id; /** * @var string|null */ - public $name = null; + public $name; } diff --git a/src/Type/SharedLink.php b/src/Type/SharedLink.php index c8ae61b..4e8b695 100644 --- a/src/Type/SharedLink.php +++ b/src/Type/SharedLink.php @@ -23,56 +23,56 @@ class SharedLink extends Type * * @var int|null */ - public $viewCnt = null; + public $viewCnt; /** * Token * * @var string|null */ - public $token = null; + public $token; /** * Creation time * * @var DateTime|null */ - public $ctime = null; + public $ctime; /** * Path * * @var string|null */ - public $path = null; + public $path; /** * Repo ID * * @var string|null */ - public $repoId = null; + public $repoId; /** * User name * * @var string|null */ - public $username = null; + public $username; /** * URL * * @var string|null */ - public $url = null; + public $url; /** * Link, same as URL * * @var string|null */ - public $link = null; + public $link; /** * @var array @@ -98,5 +98,5 @@ class SharedLink extends Type /** * @var DateTime|null */ - public $expireDate = null; + public $expireDate; } diff --git a/src/Type/SharedLinkPermissions.php b/src/Type/SharedLinkPermissions.php index 54fd4ef..babd689 100644 --- a/src/Type/SharedLinkPermissions.php +++ b/src/Type/SharedLinkPermissions.php @@ -12,6 +12,7 @@ */ class SharedLinkPermissions extends AbstractBitmask { - const CAN_DOWNLOAD = 1; - const CAN_EDIT = 2; + public const CAN_DOWNLOAD = 1; + + public const CAN_EDIT = 2; } \ No newline at end of file diff --git a/src/Type/Type.php b/src/Type/Type.php index 88a9eb8..78a2bdb 100644 --- a/src/Type/Type.php +++ b/src/Type/Type.php @@ -22,12 +22,12 @@ abstract class Type implements TypeInterface /** * Associative array mode */ - const ARRAY_ASSOC = 1; + public const ARRAY_ASSOC = 1; /** * Multipart array mode */ - const ARRAY_MULTI_PART = 2; + public const ARRAY_MULTI_PART = 2; /** * Constructor @@ -38,7 +38,7 @@ abstract class Type implements TypeInterface */ public function __construct(array $fromArray = []) { - if (is_array($fromArray) && !empty($fromArray)) { + if ($fromArray !== []) { $this->fromArray($fromArray); } } @@ -87,8 +87,6 @@ public function fromArray(array $fromArray) // type is given in derived class * it's microseconds. You never know. * * @param int $value Int time stamp, either seconds or microseconds - * - * @return DateTime */ public function getDateTime(int $value): DateTime { @@ -119,7 +117,6 @@ public function fromJson(stdClass $jsonResponse) // type is given in derived cla * * @param int $mode Array mode * - * @return array * @throws Exception */ public function toArray(int $mode = self::ARRAY_ASSOC): array @@ -135,7 +132,7 @@ public function toArray(int $mode = self::ARRAY_ASSOC): array $val = $val->format('U'); } - $multiPart[] = ['name' => $caseHelper->toSnakeCase($key), 'contents' => "$val"]; + $multiPart[] = ['name' => $caseHelper->toSnakeCase($key), 'contents' => $val]; } $array = $multiPart; diff --git a/src/Type/TypeInterface.php b/src/Type/TypeInterface.php index 9a10c53..61d2d43 100644 --- a/src/Type/TypeInterface.php +++ b/src/Type/TypeInterface.php @@ -21,14 +21,11 @@ interface TypeInterface * @throws Exception */ public function fromArray(array $fromArray); // type is given in implementing class - /** * Time stamps vary a lot in Seafile. Sometimes it's seconds from 1970-01-01 00:00:00, sometimes * it's microseconds. You never know. * * @param int $value Int time stamp, either seconds or microseconds - * - * @return DateTime */ public function getDateTime(int $value): DateTime; @@ -41,13 +38,11 @@ public function getDateTime(int $value): DateTime; * @throws Exception */ public function fromJson(stdClass $jsonResponse); // type is given in implementing class - /** * Return instance as array * * @param int $mode Array mode * - * @return array * @throws Exception */ public function toArray(int $mode = Type::ARRAY_ASSOC): array; diff --git a/test/bootstrap.php b/test/bootstrap.php index dd80b64..1619c5e 100644 --- a/test/bootstrap.php +++ b/test/bootstrap.php @@ -3,7 +3,7 @@ use Seafile\Client\Http\Client; use Seafile\Client\Resource\Auth; -require_once 'vendor/autoload.php'; +require_once __DIR__ . '/../vendor/autoload.php'; $functionalTestsCredentialsComplete = ( $_ENV['ALLOW_LIVE_DATA_MANIPULATION_ON_TEST_SERVER'] === '1' @@ -53,6 +53,6 @@ try { $GLOBALS['FAKER_SEED'] = random_int(0, 1000000); // @todo Make tests repeatable -} catch (Exception $e) { - die($e->getMessage()); +} catch (Exception $exception) { + die($exception->getMessage()); } diff --git a/test/functional/FunctionalTestCase.php b/test/functional/FunctionalTestCase.php index bb2dcf4..05a423d 100644 --- a/test/functional/FunctionalTestCase.php +++ b/test/functional/FunctionalTestCase.php @@ -30,16 +30,16 @@ class FunctionalTestCase extends TestCase { /** @var Client|null */ - protected $client = null; + protected $client; /** @var Logger|null */ - protected $logger = null; + protected $logger; /** @var LibraryType|null */ - protected $testLib = null; + protected $testLib; /** @var Generator|null|Internet|Lorem|Person */ - protected $faker = null; + protected $faker; /** * Skip functional tests when they do not have been set up correctly. Please refer to README.md on how to set them up. @@ -48,7 +48,7 @@ class FunctionalTestCase extends TestCase * * @beforeClass */ - public static function checkFunctionalTestsSetUpCorrectly() + public static function checkFunctionalTestsSetUpCorrectly(): void { if ($GLOBALS['RUN_FUNCTIONAL_TESTS'] !== true) { self::markTestSkipped(); @@ -56,7 +56,6 @@ public static function checkFunctionalTestsSetUpCorrectly() } /** - * @return Logger * @throws Exception */ protected function getLogger(): Logger @@ -69,7 +68,6 @@ protected function getLogger(): Logger } /** - * @return Client * @throws Exception */ protected function getClient(): Client @@ -79,7 +77,7 @@ protected function getClient(): Client $stack->push( Middleware::log( $this->getLogger(), - new MessageFormatter("{hostname} {req_header_Authorization} - {req_header_User-Agent} - [{date_common_log}] \"{method} {host}{target} HTTP/{version}\" {code} {res_header_Content-Length} req_body: {req_body} response_body: {res_body}") + new MessageFormatter('{hostname} {req_header_Authorization} - {req_header_User-Agent} - [{date_common_log}] "{method} {host}{target} HTTP/{version}" {code} {res_header_Content-Length} req_body: {req_body} response_body: {res_body}') ) ); @@ -111,7 +109,6 @@ protected function setUp(): void } /** - * @return Generator * @throws Exception */ protected function getFaker(): Generator @@ -119,25 +116,24 @@ protected function getFaker(): Generator if (is_null($this->faker)) { $this->faker = FakerFactory::create(); $this->faker->seed($GLOBALS['FAKER_SEED']); - $this->getLogger()->info("Random generator seed: {$GLOBALS['FAKER_SEED']}"); + $this->getLogger()->info('Random generator seed: ' . $GLOBALS['FAKER_SEED']); } return $this->faker; } /** - * @return LibraryType * @throws Exception */ protected function getTestLibraryType(): LibraryType { if (is_null($this->testLib)) { $libId = $_ENV['TEST_LIB_ENCRYPTED_ID']; - $libraryResource = new Library($this->client); - $this->testLib = $libraryResource->getById($libId); + $library = new Library($this->client); + $this->testLib = $library->getById($libId); if ($this->testLib->encrypted === true && array_key_exists('TEST_LIB_ENCRYPTED_PASSWORD', $_ENV)) { - self::assertTrue($libraryResource->decrypt( + self::assertTrue($library->decrypt( $libId, [ 'query' => ['password' => $_ENV['TEST_LIB_ENCRYPTED_PASSWORD']], diff --git a/test/functional/Resource/AccountTest.php b/test/functional/Resource/AccountTest.php index fa99fd5..385c908 100644 --- a/test/functional/Resource/AccountTest.php +++ b/test/functional/Resource/AccountTest.php @@ -4,6 +4,7 @@ use DateTime; use Exception; +use GuzzleHttp\Exception\GuzzleException; use Seafile\Client\Resource\Account; use Seafile\Client\Type\Account as AccountType; use Seafile\Client\Tests\Functional\FunctionalTestCase; @@ -19,21 +20,19 @@ */ class AccountTest extends FunctionalTestCase { - /** @var string */ - private $emailAddress = ''; + private string $emailAddress = ''; - /** @var Account|null */ - private $accountResource = null; + private ?Account $account; /** * @throws Exception */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); - $this->emailAddress = 'seafile_php_sdk_functional_test_' . (string)random_int(0, 1000) . $this->faker->safeEmail; - $this->accountResource = new Account($this->client); + $this->emailAddress = 'seafile_php_sdk_functional_test_' . random_int(0, 1000) . $this->faker->safeEmail; + $this->account = new Account($this->client); } /** @@ -49,14 +48,15 @@ public function setUp(): void * and successfully so that's postponed for now. * * @throws Exception + * @throws GuzzleException */ - public function testAccount() + public function testAccount(): void { $this->logger->debug("#################### Get all users"); - $accountTypes = $this->accountResource->getAll(); + $accountTypes = $this->account->getAll(); self::assertIsArray($accountTypes); - self::assertTrue(count($accountTypes) > 0); + self::assertTrue($accountTypes !== []); foreach ($accountTypes as $accountType) { $this->logger->debug($accountType->email); @@ -64,14 +64,14 @@ public function testAccount() self::assertInstanceOf(AccountType::class, $accountType); self::assertIsString( filter_var($accountType->email, FILTER_VALIDATE_EMAIL), - "Expected a valid email address but got '{$accountType->email}'" + sprintf("Expected a valid email address but got '%s'", $accountType->email) ); } $fullUserName = $this->faker->name(); $note = $this->faker->sentence(); - $this->logger->debug("#################### Create random account: {$this->emailAddress}"); + $this->logger->debug('#################### Create random account: ' . $this->emailAddress); $newAccountType = (new AccountType)->fromArray([ 'email' => $this->emailAddress, @@ -82,11 +82,11 @@ public function testAccount() //'institution' => 'Duff Beer Inc.', ]); - self::assertTrue($this->accountResource->create($newAccountType)); + self::assertTrue($this->account->create($newAccountType)); // get info on specific user - $this->logger->debug("#################### Get AccountType instance by email address: {$this->emailAddress}"); - $accountType = $this->accountResource->getByEmail($this->emailAddress); + $this->logger->debug('#################### Get AccountType instance by email address: ' . $this->emailAddress); + $accountType = $this->account->getByEmail($this->emailAddress); self::assertInstanceOf(AccountType::class, $accountType); self::assertSame($this->emailAddress, $accountType->email); @@ -99,8 +99,8 @@ public function testAccount() } } - $this->logger->debug("#################### Get Account info by email address: {$this->emailAddress}"); - $accountType = $this->accountResource->getInfo($this->emailAddress); + $this->logger->debug('#################### Get Account info by email address: ' . $this->emailAddress); + $accountType = $this->account->getInfo($this->emailAddress); self::assertInstanceOf(AccountType::class, $accountType); self::assertSame($this->emailAddress, $accountType->email); diff --git a/test/functional/Resource/FileTest.php b/test/functional/Resource/FileTest.php index 548b7da..229ba2f 100644 --- a/test/functional/Resource/FileTest.php +++ b/test/functional/Resource/FileTest.php @@ -2,6 +2,7 @@ namespace Seafile\Client\Tests\Functional\Resource; +use Carbon\Carbon; use Exception; use GuzzleHttp\Exception\GuzzleException; use Seafile\Client\Resource\Directory; @@ -21,20 +22,18 @@ */ class FileTest extends FunctionalTestCase { - /** @var File|null */ - private $fileResource = null; + private ?File $file; - /** @var Library|null */ - private $libraryResource = null; + private ?\Seafile\Client\Type\Library $library = null; /** * @throws Exception */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); - $this->fileResource = new File($this->client); + $this->file = new File($this->client); } /** @@ -43,13 +42,13 @@ public function setUp(): void * @throws Exception * @throws GuzzleException */ - public function testCreate() + public function testCreate(): void { $this->logger->debug("#################### Create empty file on Seafile server."); - $dirItem = (new DirectoryItem())->fromArray(['path' => '/', 'name' => uniqid('some_name_', true) . '.txt']); + $directoryItem = (new DirectoryItem())->fromArray(['path' => '/', 'name' => uniqid('some_name_', true) . '.txt']); - self::assertTrue($this->fileResource->create($this->getTestLibraryType(), $dirItem)); + self::assertTrue($this->file->create($this->getTestLibraryType(), $directoryItem)); } /** @@ -69,41 +68,41 @@ public function testCreate() * @throws GuzzleException * @throws Exception */ - public function testHistory() + public function testHistory(): void { - $lib = $this->getTestLibraryType(); + $library = $this->getTestLibraryType(); - $this->logger->debug("#################### Getting lib with ID " . $lib->id); + $this->logger->debug("#################### Getting lib with ID " . $library->id); // upload a Hello World file and random file name (note: this seems not to work at this time when you are not logged into the Seafile web frontend). $newFilename = tempnam($GLOBALS['BUILD_TMP'], 'Seafile-PHP-SDK_Test_File_History_Upload_'); rename($newFilename, $newFilename . '.txt'); $newFilename .= '.txt'; - file_put_contents($newFilename, 'Hello World: ' . date('Y-m-d H:i:s')); + file_put_contents($newFilename, 'Hello World: ' . Carbon::now()->format('Y-m-d H:i:s')); $this->logger->debug("#################### Uploading file " . $newFilename); - $response = $this->fileResource->upload($lib, $newFilename, '/'); + $response = $this->file->upload($library, $newFilename, '/'); self::assertSame(200, $response->getStatusCode()); // Update file $this->logger->debug("#################### Updating file " . $newFilename); file_put_contents($newFilename, ' - UPDATED!', FILE_APPEND); - $response = $this->fileResource->update($lib, $newFilename, '/'); + $response = $this->file->update($library, $newFilename, '/'); self::assertSame(200, $response->getStatusCode()); // Get file detail $this->logger->debug("#################### Getting file detail of " . $newFilename); - $dirItem = $this->fileResource->getFileDetail($lib, basename($newFilename)); + $directoryItem = $this->file->getFileDetail($library, basename($newFilename)); - if ($dirItem->path === null) { - $dirItem->path = '/'; + if ($directoryItem->path === null) { + $directoryItem->path = '/'; } // Get file history $this->logger->debug("#################### Getting file history of " . $newFilename); - $fileHistoryItems = $this->fileResource->getHistory($lib, $dirItem); + $fileHistoryItems = $this->file->getHistory($library, $directoryItem); $this->logger->debug("#################### Listing file history of " . $newFilename); @@ -116,12 +115,12 @@ public function testHistory() $firstFileRevision = array_slice($fileHistoryItems, -1)[0]; $localFilePath = $GLOBALS['BUILD_TMP'] . '/yo.txt'; - $response = $this->fileResource->downloadRevision($lib, $dirItem, $firstFileRevision, $localFilePath); + $response = $this->file->downloadRevision($library, $directoryItem, $firstFileRevision, $localFilePath); self::assertSame(200, $response->getStatusCode()); $this->logger->debug( - "#### First file revision of " . $dirItem->name . " downloaded to " . $localFilePath + "#### First file revision of " . $directoryItem->name . " downloaded to " . $localFilePath ); } @@ -131,19 +130,19 @@ public function testHistory() * @throws GuzzleException * @throws Exception */ - public function testList() + public function testList(): void { $desiredDirectoryPath = '/'; - $lib = $this->getTestLibraryType(); + $library = $this->getTestLibraryType(); // get all directory items and list them one by one. $directory = new Directory($this->client); - $items = $directory->getAll($lib, $desiredDirectoryPath); + $items = $directory->getAll($library, $desiredDirectoryPath); $this->logger->debug("############################################### Result:"); self::assertIsArray($items); - self::assertTrue(count($items) > 0); + self::assertTrue($items !== []); foreach ($items as $item) { $this->logger->debug(sprintf("(%s) %s/%s (%d bytes)\n", $item->type, $item->path, $item->name, $item->size)); @@ -157,14 +156,14 @@ public function testList() * @throws Exception * @throws GuzzleException */ - public function testRename() + public function testRename(): void { - $this->libraryResource = $this->getTestLibraryType(); + $this->library = $this->getTestLibraryType(); $libId = $_ENV['TEST_LIB_ENCRYPTED_ID']; - $lib = $this->getTestLibraryType(); + $library = $this->getTestLibraryType(); - if ($lib->encrypted === true && isset($cfg->testLibPassword)) { - $success = $this->libraryResource->decrypt($libId, ['query' => ['password' => $_ENV['TEST_LIB_ENCRYPTED_PASSWORD']]]); + if ($library->encrypted === true && isset($cfg->testLibPassword)) { + $success = $this->library->decrypt($libId, ['query' => ['password' => $_ENV['TEST_LIB_ENCRYPTED_PASSWORD']]]); self::assertTrue($success); } @@ -174,20 +173,20 @@ public function testRename() $fileName = 'test.txt'; $dirItem = (new DirectoryItem())->fromArray(['path' => '/', 'name' => $fileName]); - $success = $this->fileResource->create($lib, $dirItem); + $success = $this->file->create($library, $dirItem); self::assertTrue($success); - $newFilename = 'test_' . date('U') . '.txt'; - $dirItem = $this->fileResource->getFileDetail($lib, $path . $fileName); + $newFilename = 'test_' . Carbon::now()->format('U') . '.txt'; + $dirItem = $this->file->getFileDetail($library, $path . $fileName); $this->logger->debug("#################### File to be renamed: " . $path . $dirItem->name); - $success = $this->fileResource->rename($lib, $dirItem, $newFilename); + $success = $this->file->rename($library, $dirItem, $newFilename); self::assertTrue($success); $this->logger->debug("#################### File renamed from " . $path . $fileName . ' to ' . $newFilename); - $newFilename = 'even_newer_file_name_test_' . date('U') . '.txt'; - $success = $this->fileResource->rename($lib, $dirItem, $newFilename); + $newFilename = 'even_newer_file_name_test_' . Carbon::now()->format('U') . '.txt'; + $success = $this->file->rename($library, $dirItem, $newFilename); self::assertTrue($success); $this->logger->debug("#################### File renamed from " . $dirItem->name . ' to ' . $newFilename); diff --git a/test/functional/Resource/GroupTest.php b/test/functional/Resource/GroupTest.php index 2ba97f2..93b2d3d 100644 --- a/test/functional/Resource/GroupTest.php +++ b/test/functional/Resource/GroupTest.php @@ -18,17 +18,16 @@ */ class GroupTest extends FunctionalTestCase { - /** @var Group|null */ - private $groupResource = null; + private ?Group $group; /** * @throws Exception */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); - $this->groupResource = new Group($this->client); + $this->group = new Group($this->client); } /** @@ -36,14 +35,14 @@ public function setUp(): void * * @throws Exception */ - public function testGetAll() + public function testGetAll(): void { $this->logger->debug("#################### Get all groups "); - $groups = $this->groupResource->getAll(); + $groups = $this->group->getAll(); self::assertIsArray($groups); - self::assertTrue(count($groups) > 0); + self::assertTrue($groups !== []); foreach ($groups as $group) { $this->logger->debug("#################### " . sprintf("Group name: %s", $group->name)); diff --git a/test/functional/Resource/ShareLinksTest.php b/test/functional/Resource/ShareLinksTest.php index 25404cc..6a68a9a 100644 --- a/test/functional/Resource/ShareLinksTest.php +++ b/test/functional/Resource/ShareLinksTest.php @@ -2,6 +2,7 @@ namespace Seafile\Client\Tests\Functional\Resource; +use Carbon\Carbon; use Exception; use Seafile\Client\Resource\File; use Seafile\Client\Resource\Library; @@ -22,17 +23,16 @@ */ class ShareLinksTest extends FunctionalTestCase { - /** @var ShareLinksAlias|null */ - private $shareLinksResource = null; + private ?ShareLinksAlias $shareLinksAlias; /** * @throws Exception */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); - $this->shareLinksResource = new ShareLinksAlias($this->client); + $this->shareLinksAlias = new ShareLinksAlias($this->client); } /** @@ -44,14 +44,14 @@ public function setUp(): void * * @throws Exception */ - public function testShareLinks() + public function testShareLinks(): void { - $libraryResource = new Library($this->client); - $fileResource = new File($this->client); + $library = new Library($this->client); + $file = new File($this->client); // get all libraries available $this->logger->debug("#################### Getting all libraries"); - $libs = $libraryResource->getAll(); + $libs = $library->getAll(); foreach ($libs as $lib) { self::assertInstanceOf(LibraryType::class, $lib); @@ -62,43 +62,43 @@ public function testShareLinks() // get specific library $this->logger->debug("#################### Getting lib with ID " . $libId); - $lib = $libraryResource->getById($libId); + $lib = $library->getById($libId); // upload a Hello World file and random file name (note: this seems not to work at this time when you are not logged into the Seafile web frontend). $newFilename = $GLOBALS['BUILD_TMP'] . '/Seafile-PHP-SDK_Test_Upload.txt'; if (!file_exists($newFilename)) { - file_put_contents($newFilename, 'Hello World: ' . date('Y-m-d H:i:s')); + file_put_contents($newFilename, 'Hello World: ' . Carbon::now()->format('Y-m-d H:i:s')); } $this->logger->debug("#################### Uploading file " . $newFilename); - $response = $fileResource->upload($lib, $newFilename, '/'); + $response = $file->upload($lib, $newFilename, '/'); self::assertSame(200, $response->getStatusCode()); // create share link for a file $this->logger->debug("#################### Create share link for a file"); $expire = 5; - $permissions = new SharedLinkPermissions(SharedLinkPermissions::CAN_DOWNLOAD); + $sharedLinkPermissions = new SharedLinkPermissions(SharedLinkPermissions::CAN_DOWNLOAD); $p = "/" . basename($newFilename); if ($lib->encrypted) { - $shareLinkType = $this->shareLinksResource->create($lib, $p, $permissions, $expire, $lib->password); + $shareLinkType = $this->shareLinksAlias->create($lib, $p, $sharedLinkPermissions, $expire, $lib->password); } else { - $shareLinkType = $this->shareLinksResource->create($lib, $p, $permissions, $expire); + $shareLinkType = $this->shareLinksAlias->create($lib, $p, $sharedLinkPermissions, $expire); } self::assertInstanceOf(SharedLink::class, $shareLinkType); $this->logger->debug("#################### Get all shared links"); - $shareLinks = $this->shareLinksResource->getAll(); + $shareLinks = $this->shareLinksAlias->getAll(); self::assertIsArray($shareLinks); $this->logger->debug("#################### Sleeping 10s before deleting the shared link"); sleep(1); - $success = $this->shareLinksResource->remove($shareLinkType); + $success = $this->shareLinksAlias->remove($shareLinkType); self::assertTrue($success); $this->logger->debug("#################### Shared link deleted"); diff --git a/test/functional/Resource/StarredFileTest.php b/test/functional/Resource/StarredFileTest.php index 546c3d8..e0d996a 100644 --- a/test/functional/Resource/StarredFileTest.php +++ b/test/functional/Resource/StarredFileTest.php @@ -23,17 +23,16 @@ */ class StarredFileTest extends FunctionalTestCase { - /** @var StarredFile|null */ - private $starredFileResource = null; + private ?StarredFile $starredFile; /** * @throws Exception */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); - $this->starredFileResource = new StarredFile($this->client); + $this->starredFile = new StarredFile($this->client); } /** @@ -46,38 +45,38 @@ public function setUp(): void * @throws Exception * @throws GuzzleException */ - public function testStarFile() + public function testStarFile(): void { - $fileResource = new File($this->client); - $libraryResource = new Library($this->client); + $file = new File($this->client); + $library = new Library($this->client); - $dirItem = (new DirectoryItem())->fromArray(['path' => '/', 'name' => uniqid('some_name_', true) . '.txt']); - self::assertTrue($fileResource->create($this->getTestLibraryType(), $dirItem)); - $dirItem->type = DirectoryItem::TYPE_FILE; - $dirItem->path .= $dirItem->name; // @todo This needs to be done automatically - $result = $this->starredFileResource->star($this->getTestLibraryType(), $dirItem); + $directoryItem = (new DirectoryItem())->fromArray(['path' => '/', 'name' => uniqid('some_name_', true) . '.txt']); + self::assertTrue($file->create($this->getTestLibraryType(), $directoryItem)); + $directoryItem->type = DirectoryItem::TYPE_FILE; + $directoryItem->path .= $directoryItem->name; // @todo This needs to be done automatically + $result = $this->starredFile->star($this->getTestLibraryType(), $directoryItem); self::assertIsString($result); // get all starred files $this->logger->debug("#################### Getting all starred files"); - $dirItems = $this->starredFileResource->getAll(); + $dirItems = $this->starredFile->getAll(); self::assertIsArray($dirItems); - self::assertTrue(count($dirItems) > 0); // we just have created one so there must not be 0 items + self::assertTrue($dirItems !== []); // we just have created one so there must not be 0 items - foreach ($dirItems as $dirItem) { - self::assertInstanceOf(DirectoryItem::class, $dirItem); + foreach ($dirItems as $directoryItem) { + self::assertInstanceOf(DirectoryItem::class, $directoryItem); } $this->logger->debug("#################### Unstarring files..."); foreach ($dirItems as $dirItem) { - $lib = $libraryResource->getById($dirItem->repo); - $this->starredFileResource->unstar($lib, $dirItem); + $lib = $library->getById($dirItem->repo); + $this->starredFile->unstar($lib, $dirItem); } // get all starred files, there must be none $this->logger->debug("#################### Getting all starred files"); - $dirItems = $this->starredFileResource->getAll(); - self::assertFalse(count($dirItems) > 0); + $dirItems = $this->starredFile->getAll(); + self::assertFalse($dirItems !== []); } } diff --git a/test/unit/Http/ClientUnitTest.php b/test/unit/Http/ClientUnitTest.php index f0be3ff..6f12d2f 100644 --- a/test/unit/Http/ClientUnitTest.php +++ b/test/unit/Http/ClientUnitTest.php @@ -19,10 +19,8 @@ class ClientUnitTest extends UnitTestCase { /** * Test that base_uri is empty by default. - * - * @return void */ - public function testBaseUriEmpty() + public function testBaseUriEmpty(): void { $client = new Client(); self::assertEmpty((string)$client->getConfig('base_uri')); @@ -30,10 +28,8 @@ public function testBaseUriEmpty() /** * Test that base_uri not empty when a value has been set. - * - * @return void */ - public function testBaseUriNotEmpty() + public function testBaseUriNotEmpty(): void { $client = new Client(['base_uri' => 'http://example.com']); self::assertSame('http://example.com', (string)$client->getConfig('base_uri')); diff --git a/test/unit/Resource/AccountTest.php b/test/unit/Resource/AccountTest.php index 2ca19cc..add0046 100644 --- a/test/unit/Resource/AccountTest.php +++ b/test/unit/Resource/AccountTest.php @@ -3,6 +3,7 @@ namespace Seafile\Client\Tests\Unit\Resource; use DateTime; +use DateTimeInterface; use Exception; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Psr7\Response; @@ -27,13 +28,12 @@ class AccountTest extends UnitTestCase /** * Test getAll() * - * @return void * @throws GuzzleException * @throws Exception */ - public function testGetAll() + public function testGetAll(): void { - $accountResource = new Account($this->getMockedClient( + $account = new Account($this->getMockedClient( new Response( 200, ['Content-Type' => 'application/json'], @@ -41,7 +41,7 @@ public function testGetAll() ) )); - $libs = $accountResource->getAll(); + $libs = $account->getAll(); self::assertIsArray($libs); @@ -54,12 +54,10 @@ public function testGetAll() * Test getByEmail() * * @param string $method Name of method to be tested - * - * @return void */ - public function testGetByEmail(string $method = 'getByEmail') + public function testGetByEmail(string $method = 'getByEmail'): void { - $accountResource = new Account($this->getMockedClient( + $account = new Account($this->getMockedClient( new Response( 200, ['Content-Type' => 'application/json'], @@ -69,20 +67,18 @@ public function testGetByEmail(string $method = 'getByEmail') $email = 'test-5690113abbceb4.93776759@example.com'; - $accountType = $accountResource->{$method}($email); + $accountType = $account->{$method}($email); self::assertInstanceOf(AccountType::class, $accountType); self::assertSame($email, $accountType->email); self::assertInstanceOf(DateTime::class, $accountType->createTime); - self::assertSame('2016-01-08T19:42:50+0000', $accountType->createTime->format(DATE_ISO8601)); + self::assertSame('2016-01-08T19:42:50+00:00', $accountType->createTime->format(DateTimeInterface::ATOM)); } /** * Test getInfo() - * - * @return void */ - public function testGetInfo() + public function testGetInfo(): void { $this->testGetByEmail('getInfo'); } @@ -90,19 +86,16 @@ public function testGetInfo() /** * Test create() with missing attribute values * - * @return void * @throws Exception */ - public function testCreateIllegal() + public function testCreateIllegal(): void { - $accountResource = new Account($this->getMockedClient(new Response(200))); - self::assertFalse($accountResource->create(new AccountType())); + $account = new Account($this->getMockedClient(new Response(200))); + self::assertFalse($account->create(new AccountType())); } /** * Data Provider for testCreate() - * - * @return array */ public static function dataProviderCreateUpdate(): array { @@ -123,10 +116,9 @@ public static function dataProviderCreateUpdate(): array * * @param array $data DataProvider data * - * @return void * @throws Exception */ - public function testCreateUpdate(array $data) + public function testCreateUpdate(array $data): void { $baseUri = 'https://example.com'; @@ -148,27 +140,24 @@ public function testCreateUpdate(array $data) ->with('base_uri') ->willReturn($baseUri); - $accountResource = new Account($mockedClient); + $account = new Account($mockedClient); - self::assertSame($data['result'], $accountResource->{$data['method']}($accountType)); + self::assertSame($data['result'], $account->{$data['method']}($accountType)); } /** * Test update() with missing attribute values * - * @return void * @throws Exception */ - public function testUpdateIllegal() + public function testUpdateIllegal(): void { - $accountResource = new Account($this->getMockedClient(new Response(200))); - self::assertFalse($accountResource->update(new AccountType())); + $account = new Account($this->getMockedClient(new Response(200))); + self::assertFalse($account->update(new AccountType())); } /** * Data Provider for testRemove() - * - * @return array */ public static function dataProviderRemove(): array { @@ -185,10 +174,9 @@ public static function dataProviderRemove(): array * * @param array $data DataProvider data * - * @return void * @throws Exception */ - public function testRemove(array $data) + public function testRemove(array $data): void { $baseUri = 'https://example.com'; diff --git a/test/unit/Resource/AvatarTest.php b/test/unit/Resource/AvatarTest.php index 0666652..12cd432 100644 --- a/test/unit/Resource/AvatarTest.php +++ b/test/unit/Resource/AvatarTest.php @@ -27,10 +27,8 @@ class AvatarTest extends UnitTestCase { /** * Test getUserAvatarByEmail() - * - * @return void */ - public function testGetUserAvatarByEmail() + public function testGetUserAvatarByEmail(): void { $baseUri = 'https://example.com'; $resource = 'user'; @@ -42,10 +40,8 @@ public function testGetUserAvatarByEmail() /** * Test getAvatar() with illegal avatar size - * - * @return void */ - public function testGetAvatarIllegalSize() + public function testGetAvatarIllegalSize(): void { $baseUri = 'https://example.com'; $resource = 'user'; @@ -60,10 +56,9 @@ public function testGetAvatarIllegalSize() /** * Test getGroupAvatarByEmail() * - * @return void * @throws Exception */ - public function testGetGroupAvatarByEmail() + public function testGetGroupAvatarByEmail(): void { $baseUri = 'https://example.com'; $resource = 'group'; @@ -107,9 +102,9 @@ protected function doGetAvatar(string $method, string $baseUri, string $resource ->with('base_uri') ->willReturn($baseUri); - $avatarResource = new AvatarResource($mockedClient); + $avatar = new AvatarResource($mockedClient); - $avatarType = $avatarResource->{$method}($entity, $size); + $avatarType = $avatar->{$method}($entity, $size); self::assertInstanceOf(Avatar::class, $avatarType); self::assertInstanceOf(DateTime::class, $avatarType->mtime); @@ -119,28 +114,27 @@ protected function doGetAvatar(string $method, string $baseUri, string $resource /** * Test getAvatar() with illegal type instance * - * @return void * @throws Exception */ - public function testGetAvatarIllegalType() + public function testGetAvatarIllegalType(): void { $baseUri = 'https://example.com'; /** @var SeafileHttpClient|MockObject $mockedClient */ $mockedClient = $this->getMockBuilder(SeafileHttpClient::class)->getMock(); - $libraryType = new LibraryType(); + $library = new LibraryType(); $mockedClient->expects(self::any()) ->method('getConfig') ->with('base_uri') ->willReturn($baseUri); - $avatarResource = new AvatarResource($mockedClient); + $avatar = new AvatarResource($mockedClient); $this->expectException('Exception'); $this->expectExceptionMessage('Unsupported type to retrieve avatar information for.'); - $this->invokeMethod($avatarResource, 'getAvatar', [$libraryType, 80]); + $this->invokeMethod($avatar, 'getAvatar', [$library, 80]); } } diff --git a/test/unit/Resource/DirectoryTest.php b/test/unit/Resource/DirectoryTest.php index 92faba9..5bc48e3 100644 --- a/test/unit/Resource/DirectoryTest.php +++ b/test/unit/Resource/DirectoryTest.php @@ -27,12 +27,11 @@ class DirectoryTest extends UnitTestCase /** * Test getAll() * - * @return void * @throws GuzzleException */ - public function testGetAll() + public function testGetAll(): void { - $directoryResource = new Directory($this->getMockedClient( + $directory = new Directory($this->getMockedClient( new Response( 200, ['Content-Type' => 'application/json'], @@ -40,7 +39,7 @@ public function testGetAll() ) )); - $directoryItems = $directoryResource->getAll(new Library()); + $directoryItems = $directory->getAll(new Library()); self::assertIsArray($directoryItems); @@ -52,10 +51,9 @@ public function testGetAll() /** * Test getAll() with directory path * - * @return void * @throws GuzzleException */ - public function testGetAllWithDir() + public function testGetAllWithDir(): void { $rootDir = '/' . uniqid('test_', true); @@ -78,21 +76,20 @@ public function testGetAllWithDir() self::equalTo(['query' => ['p' => $rootDir]]) )->willReturn($response); - $directoryResource = new Directory($mockedClient); - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $directory = new Directory($mockedClient); + $library = new Library(); + $library->id = 'some-crazy-id'; - $directoryResource->getAll($lib, $rootDir); + $directory->getAll($library, $rootDir); } /** * Test exists() * - * @return void * @throws GuzzleException * @throws Exception */ - public function testExists() + public function testExists(): void { $rootDir = '/' . uniqid('test_', true); @@ -116,23 +113,21 @@ public function testExists() self::equalTo(['query' => ['p' => $rootDir]]) )->willReturn($response); - $directoryResource = new Directory($mockedClient); + $directory = new Directory($mockedClient); - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; - self::assertFalse($directoryResource->exists($lib, 'does_not_exist', $rootDir)); // ...2nd request... + self::assertFalse($directory->exists($library, 'does_not_exist', $rootDir)); // ...2nd request... // ...3rd request. For 'test_dir' see mock response json file, it's there - self::assertTrue($directoryResource->exists($lib, 'test_dir', $rootDir)); + self::assertTrue($directory->exists($library, 'test_dir', $rootDir)); } /** * Data provider for testCreateNonRecursive() - * - * @return array */ - public function createNonRecursiveDataProvider() + public function createNonRecursiveDataProvider(): array { return [[201], [500]]; } @@ -143,10 +138,9 @@ public function createNonRecursiveDataProvider() * @param int $expectResponseCode Expected mkdir request response code * * @dataProvider createNonRecursiveDataProvider - * @return void * @throws GuzzleException */ - public function testCreateNonRecursive(int $expectResponseCode) + public function testCreateNonRecursive(int $expectResponseCode): void { $getAllResponse = new Response( 200, @@ -157,13 +151,13 @@ public function testCreateNonRecursive(int $expectResponseCode) $mkdirResponse = new Response($expectResponseCode, ['Content-Type' => 'text/plain']); $directoryResource = $this->getDirectoryResource($getAllResponse, $mkdirResponse); - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; if ($expectResponseCode === 201) { - self::assertTrue($directoryResource->create($lib, 'new_dir', '/', false)); + self::assertTrue($directoryResource->create($library, 'new_dir', '/', false)); } else { - self::assertFalse($directoryResource->create($lib, 'new_dir', '/', false)); + self::assertFalse($directoryResource->create($library, 'new_dir', '/', false)); } } @@ -172,10 +166,8 @@ public function testCreateNonRecursive(int $expectResponseCode) * * @param Response $getAllResponse Response on "get all" request * @param Response $mkdirResponse Response on actual operation - * - * @return Directory */ - protected function getDirectoryResource(Response $getAllResponse, Response $mkdirResponse) + protected function getDirectoryResource(Response $getAllResponse, Response $mkdirResponse): Directory { /** @var SeafileHttpClient|MockObject $mockedClient */ $mockedClient = $this->getMockBuilder(SeafileHttpClient::class)->getMock(); @@ -205,10 +197,9 @@ function ($method) use ($getAllResponse, $mkdirResponse) { /** * Test create() non-recursively, directory exists. Must yield boolean false. * - * @return void * @throws GuzzleException */ - public function testCreateDirectoryExists() + public function testCreateDirectoryExists(): void { $getAllResponse = new Response( 200, @@ -225,30 +216,27 @@ public function testCreateDirectoryExists() ->method('request') // Return what was passed to offsetGet as a new instance ->will(self::returnCallback( - function () use ($getAllResponse) { - return $getAllResponse; - } + fn(): Response => $getAllResponse )); - $directoryResource = new Directory($mockedClient); + $directory = new Directory($mockedClient); - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; - self::assertFalse($directoryResource->create($lib, 'test_dir', '/', false)); + self::assertFalse($directory->create($library, 'test_dir', '/', false)); } /** * test create() with empty dirName. Must yield boolean false. * - * @return void * @throws GuzzleException */ - public function testCreateEmptyDirName() + public function testCreateEmptyDirName(): void { - $directoryResource = new Directory(new SeafileHttpClient()); + $directory = new Directory(new SeafileHttpClient()); - self::assertFalse($directoryResource->create( + self::assertFalse($directory->create( new Library(), '' )); @@ -257,10 +245,9 @@ public function testCreateEmptyDirName() /** * Test create() recursively * - * @return void * @throws GuzzleException */ - public function testCreateRecursive() + public function testCreateRecursive(): void { $getAllResponse = new Response( 200, @@ -271,34 +258,32 @@ public function testCreateRecursive() $mkdirResponse = new Response(201, ['Content-Type' => 'text/plain']); $directoryResource = $this->getDirectoryResource($getAllResponse, $mkdirResponse); - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; - self::assertTrue($directoryResource->create($lib, 'a/b', '/', true)); + self::assertTrue($directoryResource->create($library, 'a/b', '/', true)); } /** * Test rename(), with invalid directory name * - * @return void * @throws GuzzleException */ - public function testRenameInvalidDirectoryName() + public function testRenameInvalidDirectoryName(): void { - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; - $directoryResource = new Directory(new SeafileHttpClient()); - self::assertFalse($directoryResource->rename($lib, '', '')); + $directory = new Directory(new SeafileHttpClient()); + self::assertFalse($directory->rename($library, '', '')); } /** * Test rename() * - * @return void * @throws GuzzleException */ - public function testRename() + public function testRename(): void { $getAllResponse = new Response( 200, @@ -349,36 +334,34 @@ function ($method, $uri, $params) use ($getAllResponse, $mkdirResponse, $expectU } )); - $directoryResource = new Directory($mockedClient); + $directory = new Directory($mockedClient); - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; - self::assertTrue($directoryResource->rename($lib, 'test_dir', 'test_dir_renamed')); + self::assertTrue($directory->rename($library, 'test_dir', 'test_dir_renamed')); } /** * Test remove(), with invalid directory name * - * @return void * @throws GuzzleException */ - public function testRemoveInvalidDirectoryName() + public function testRemoveInvalidDirectoryName(): void { - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; - $directoryResource = new Directory(new SeafileHttpClient()); - self::assertFalse($directoryResource->remove($lib, '')); + $directory = new Directory(new SeafileHttpClient()); + self::assertFalse($directory->remove($library, '')); } /** * Test remove() * - * @return void * @throws GuzzleException */ - public function testRemove() + public function testRemove(): void { $getAllResponse = new Response( 200, @@ -419,11 +402,11 @@ function ($method, $uri, $params) use ($getAllResponse, $mkdirResponse, $expectU } )); - $directoryResource = new Directory($mockedClient); + $directory = new Directory($mockedClient); - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; - self::assertTrue($directoryResource->remove($lib, 'test_dir')); + self::assertTrue($directory->remove($library, 'test_dir')); } } diff --git a/test/unit/Resource/FileTest.php b/test/unit/Resource/FileTest.php index 3245161..3b5de33 100644 --- a/test/unit/Resource/FileTest.php +++ b/test/unit/Resource/FileTest.php @@ -31,16 +31,15 @@ class FileTest extends UnitTestCase /** * Test getDownloadUrl() * - * @return void * @throws GuzzleException */ - public function testGetDownloadUrl() + public function testGetDownloadUrl(): void { - $fileResource = new File($this->getMockedClient( + $file = new File($this->getMockedClient( new Response(200, ['Content-Type' => 'application/json'], '"https://some.example.com/some/url"') )); - $downloadLink = $fileResource->getDownloadUrl(new Library(), new DirectoryItem()); + $downloadLink = $file->getDownloadUrl(new Library(), new DirectoryItem()); // encapsulating quotes must be gone self::assertSame('https://some.example.com/some/url', $downloadLink); @@ -48,8 +47,6 @@ public function testGetDownloadUrl() /** * Data provider for testUrlEncodePath() - * - * @return array */ public static function dataProviderTestUrlEncodePath(): array { @@ -69,18 +66,17 @@ public static function dataProviderTestUrlEncodePath(): array * @param string $path Path to encode * @param string $expectEncodedPath Expected encoded path * - * @return void * @dataProvider dataProviderTestUrlEncodePath * @throws ReflectionException */ - public function testUrlEncodePath(string $path, string $expectEncodedPath) + public function testUrlEncodePath(string $path, string $expectEncodedPath): void { - $fileResource = $this->getMockBuilder(File::class) + $mock = $this->getMockBuilder(File::class) ->disableOriginalConstructor() ->addMethods([]) ->getMock(); - $actualEncodedPath = $this->invokeMethod($fileResource, 'urlencodePath', [$path]); + $actualEncodedPath = $this->invokeMethod($mock, 'urlencodePath', [$path]); self::assertSame($expectEncodedPath, $actualEncodedPath); } @@ -88,16 +84,15 @@ public function testUrlEncodePath(string $path, string $expectEncodedPath) /** * Test getUploadUrl() * - * @return void * @throws GuzzleException */ - public function testGetUploadLink() + public function testGetUploadLink(): void { - $fileResource = new File($this->getMockedClient( + $file = new File($this->getMockedClient( new Response(200, ['Content-Type' => 'application/json'], '"https://some.example.com/some/url"') )); - $uploadUrl = $fileResource->getUploadUrl(new Library()); + $uploadUrl = $file->getUploadUrl(new Library()); // encapsulating quotes must be gone self::assertSame('https://some.example.com/some/url', $uploadUrl); @@ -107,11 +102,10 @@ public function testGetUploadLink() * Test getUploadUrl() with subdirectory. Expect the mocked client's `request` gets called with the parent_dir * parameter "p". * - * @return void * @throws GuzzleException * @throws Exception */ - public function testGetUploadLinkWithSubDirectory() + public function testGetUploadLinkWithSubDirectory(): void { $libId = "lib_id"; $uploadDir = "/Somedir"; @@ -128,11 +122,11 @@ public function testGetUploadLinkWithSubDirectory() self::equalTo('http://example.com/index.html/api' . File::API_VERSION . '/repos/' . $libId . '/upload-link/?p=' . $uploadDir) ); - $fileResource = new File($mockedClient); + $file = new File($mockedClient); - $lib = new Library(['id' => $libId]); + $library = new Library(['id' => $libId]); - $uploadUrl = $fileResource->getUploadUrl($lib, true, $uploadDir); + $uploadUrl = $file->getUploadUrl($library, true, $uploadDir); self::assertSame('https://some.example.com/some/url', $uploadUrl); } @@ -140,17 +134,16 @@ public function testGetUploadLinkWithSubDirectory() /** * Download a file, local destination path is already occupied * - * @return void * @throws GuzzleException */ - public function testDownloadFromDirFileExists() + public function testDownloadFromDirFileExists(): void { $newFilename = tempnam($GLOBALS['BUILD_TMP'], uniqid()); - $fileResource = new File($this->getMockedClient(new Response())); + $file = new File($this->getMockedClient(new Response())); try { $this->expectException('Exception'); - $fileResource->downloadFromDir(new Library(), new DirectoryItem(), $newFilename, '/'); + $file->downloadFromDir(new Library(), new DirectoryItem(), $newFilename, '/'); $this->fail('Exception expected'); } finally { unlink($newFilename); @@ -160,29 +153,27 @@ public function testDownloadFromDirFileExists() /** * Try to upload a non-existent local file * - * @return void * @throws GuzzleException */ - public function testUploadDoesNotExist() + public function testUploadDoesNotExist(): void { $filename = uniqid(); - $fileResource = new File($this->getMockedClient(new Response())); + $file = new File($this->getMockedClient(new Response())); $this->expectException('Exception'); - $fileResource->upload(new Library(), $filename); + $file->upload(new Library(), $filename); $this->fail('Exception expected'); } /** * Test downloadFromDir() * - * @return void * @throws GuzzleException */ - public function testDownloadFromDir() + public function testDownloadFromDir(): void { - $fileResource = new FileResourceStub($this->getMockedClient(new Response())); - $response = $fileResource->downloadFromDir(new Library(), new DirectoryItem(), '/some/path', '/', 1); + $fileResourceStub = new FileResourceStub($this->getMockedClient(new Response())); + $response = $fileResourceStub->downloadFromDir(new Library(), new DirectoryItem(), '/some/path', '/', 1); self::assertInstanceOf(Response::class, $response); } @@ -190,13 +181,12 @@ public function testDownloadFromDir() /** * Test download() * - * @return void * @throws GuzzleException */ - public function testDownload() + public function testDownload(): void { - $fileResource = new FileResourceStub($this->getMockedClient(new Response())); - $response = $fileResource->download(new Library(), '/some/path', '/some/file', 1); + $fileResourceStub = new FileResourceStub($this->getMockedClient(new Response())); + $response = $fileResourceStub->download(new Library(), '/some/path', '/some/file', 1); // @todo Assert request query params self::assertInstanceOf(Response::class, $response); @@ -205,13 +195,12 @@ public function testDownload() /** * Test upload() * - * @return void * @throws GuzzleException */ - public function testUpload() + public function testUpload(): void { - $fileResource = new FileResourceStub($this->getMockedClient(new Response())); - $response = $fileResource->upload(new Library(), $GLOBALS['BUILD_TMP'], '/'); + $fileResourceStub = new FileResourceStub($this->getMockedClient(new Response())); + $response = $fileResourceStub->upload(new Library(), $GLOBALS['BUILD_TMP'], '/'); self::assertInstanceOf(Response::class, $response); } @@ -219,13 +208,12 @@ public function testUpload() /** * Test update() * - * @return void * @throws GuzzleException */ - public function testUpdate() + public function testUpdate(): void { - $fileResource = new FileResourceStub($this->getMockedClient(new Response())); - $response = $fileResource->update(new Library(), $GLOBALS['BUILD_TMP'], '/'); + $fileResourceStub = new FileResourceStub($this->getMockedClient(new Response())); + $response = $fileResourceStub->update(new Library(), $GLOBALS['BUILD_TMP'], '/'); self::assertInstanceOf(Response::class, $response); } @@ -233,53 +221,50 @@ public function testUpdate() /** * test getFileDetail() * - * @return void * @throws GuzzleException */ - public function testGetFileDetail() + public function testGetFileDetail(): void { - $fileResource = new File($this->getMockedClient(new Response( + $file = new File($this->getMockedClient(new Response( 200, ['Content-Type' => 'application/json'], '{"id": "cd8ec413c72388149911c84b046642da2ca4b935", "mtime": 1444760758, "type": "file", ' . '"name": "Seafile-PHP-SDK_Test_Upload_jt64pq.txt", "size": 32}' ))); - $response = $fileResource->getFileDetail(new Library(), '/Seafile-PHP-SDK_Test_Upload_jt64pq.txt'); + $directoryItem = $file->getFileDetail(new Library(), '/Seafile-PHP-SDK_Test_Upload_jt64pq.txt'); - self::assertInstanceOf(DirectoryItem::class, $response); - self::assertInstanceOf(DateTime::class, $response->mtime); - self::assertSame('Seafile-PHP-SDK_Test_Upload_jt64pq.txt', $response->name); - self::assertSame('file', $response->type); - self::assertequals('32', $response->size); + self::assertInstanceOf(DirectoryItem::class, $directoryItem); + self::assertInstanceOf(DateTime::class, $directoryItem->mtime); + self::assertSame('Seafile-PHP-SDK_Test_Upload_jt64pq.txt', $directoryItem->name); + self::assertSame('file', $directoryItem->type); + self::assertequals('32', $directoryItem->size); } /** * Test getMultiPartParams() for update - * - * @return void */ - public function testUpdateMultiPartParams() + public function testUpdateMultiPartParams(): void { $localFilePath = $GLOBALS['BUILD_TMP'] . '/' . uniqid('test_', true) . '.txt'; file_put_contents($localFilePath, '0'); try { $dir = '/'; - $fileResource = new FileResourceStub($this->getMockedClient(new Response())); + $fileResourceStub = new FileResourceStub($this->getMockedClient(new Response())); self::assertContains( [ 'name' => 'parent_dir', 'contents' => $dir, ], - $fileResource->getMultiPartParams($localFilePath, $dir, true) + $fileResourceStub->getMultiPartParams($localFilePath, $dir, true) ); self::assertNotContains( [ 'name' => 'target_file', 'contents' => $dir . basename($localFilePath), ], - $fileResource->getMultiPartParams($localFilePath, $dir, true) + $fileResourceStub->getMultiPartParams($localFilePath, $dir, true) ); } finally { if (is_writable($localFilePath)) { @@ -290,18 +275,16 @@ public function testUpdateMultiPartParams() /** * Test getMultiPartParams() with new file name - * - * @return void */ - public function testUpdateMultiPartParamsNewFilename() + public function testUpdateMultiPartParamsNewFilename(): void { $dir = '/'; $localFilePath = $GLOBALS['BUILD_TMP'] . '/' . uniqid('test_', true) . '.txt'; - $fileResource = new File($this->getMockedClient(new Response())); + $file = new File($this->getMockedClient(new Response())); $newFilename = $GLOBALS['BUILD_TMP'] . '/' . uniqid('test_', true) . '.txt'; file_put_contents($localFilePath, 'abc'); - $params = $fileResource->getMultiPartParams($localFilePath, $dir, true, $newFilename); + $params = $file->getMultiPartParams($localFilePath, $dir, true, $newFilename); $params[0]['contents'] = get_resource_type($params[0]['contents']); @@ -331,30 +314,28 @@ public function testUpdateMultiPartParamsNewFilename() /** * Test getMultiPartParams() for upload - * - * @return void */ - public function testUploadMultiPartParams() + public function testUploadMultiPartParams(): void { $localFilePath = $GLOBALS['BUILD_TMP'] . '/' . uniqid('test_', true) . '.txt'; file_put_contents($localFilePath, '0'); try { $dir = '/'; - $fileResource = new FileResourceStub($this->getMockedClient(new Response())); + $fileResourceStub = new FileResourceStub($this->getMockedClient(new Response())); self::assertNotContains( [ 'name' => 'parent_dir', 'contents' => $dir, ], - $fileResource->getMultiPartParams($localFilePath, $dir, false) + $fileResourceStub->getMultiPartParams($localFilePath, $dir, false) ); self::assertContains( [ 'name' => 'target_file', 'contents' => $dir . basename($localFilePath), ], - $fileResource->getMultiPartParams($localFilePath, $dir, false) + $fileResourceStub->getMultiPartParams($localFilePath, $dir, false) ); } finally { if (is_writable($localFilePath)) { @@ -366,26 +347,23 @@ public function testUploadMultiPartParams() /** * Test remove() with invalid file name * - * @return void * @throws GuzzleException */ - public function testRemoveInvalidFilename() + public function testRemoveInvalidFilename(): void { /** @var SeafileHttpClient|MockObject $mockedClient */ $mockedClient = $this->getMockBuilder(SeafileHttpClient::class)->getMock(); - $fileResource = new File($mockedClient); + $file = new File($mockedClient); - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; - self::assertFalse($fileResource->remove($lib, '')); + self::assertFalse($file->remove($library, '')); } /** * Data provider for testRenameInvalidFilename() - * - * @return array */ public static function dataProviderTestRenameInvalidFilename(): array { @@ -403,32 +381,29 @@ public static function dataProviderTestRenameInvalidFilename(): array * @param string $invalidFilePath Invalid file path * @param string $invalidNewFilename Invalid new file name * - * @return void * @dataProvider dataProviderTestRenameInvalidFilename * @throws GuzzleException * @throws Exception */ - public function testRenameInvalidFilename(string $invalidFilePath, string $invalidNewFilename) + public function testRenameInvalidFilename(string $invalidFilePath, string $invalidNewFilename): void { self::expectException('\InvalidArgumentException'); /** @var SeafileHttpClient|MockObject $mockedClient */ $mockedClient = $this->getMockBuilder(SeafileHttpClient::class)->getMock(); - $fileResource = new File($mockedClient); + $file = new File($mockedClient); - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; - $dirItem = new DirectoryItem(['dir' => $invalidFilePath]); + $directoryItem = new DirectoryItem(['dir' => $invalidFilePath]); - $fileResource->rename($lib, $dirItem, $invalidNewFilename); + $file->rename($library, $directoryItem, $invalidNewFilename); } /** * Data provider for testCopyInvalid() - * - * @return array */ public static function dataProviderCopyInvalid(): array { @@ -451,15 +426,14 @@ public static function dataProviderCopyInvalid(): array * * @param array $data Test data * - * @return void * @throws GuzzleException */ - public function testCopyInvalid(array $data) + public function testCopyInvalid(array $data): void { /** @var SeafileHttpClient|MockObject $mockedClient */ $mockedClient = $this->getMockBuilder(SeafileHttpClient::class)->getMock(); - $fileResource = new File($mockedClient); + $file = new File($mockedClient); $srcLib = $data[0]; $srcFilePath = $data[1]; @@ -467,16 +441,15 @@ public function testCopyInvalid(array $data) $dstFilePath = $data[3]; $expected = $data[4]; - self::assertSame($expected, $fileResource->copy($srcLib, $srcFilePath, $dstLib, $dstFilePath)); + self::assertSame($expected, $file->copy($srcLib, $srcFilePath, $dstLib, $dstFilePath)); } /** * Test remove() * - * @return void * @throws GuzzleException */ - public function testRemove() + public function testRemove(): void { $getAllResponse = new Response( 200, @@ -517,22 +490,21 @@ function ($method, $uri, $params) use ($getAllResponse, $deleteResponse, $expect } )); - $fileResource = new File($mockedClient); + $file = new File($mockedClient); - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; - self::assertTrue($fileResource->remove($lib, 'test_dir')); + self::assertTrue($file->remove($library, 'test_dir')); } /** * Test rename() * - * @return void * @throws GuzzleException * @throws Exception */ - public function testRename() + public function testRename(): void { new Response( 200, @@ -576,18 +548,16 @@ function ($method, $uri, $params) use ($renameResponse, $expectUri, $expectParam } )); - $fileResource = new File($mockedClient); + $file = new File($mockedClient); - $lib = new Library(['id' => 'some-crazy-id']); - $dirItem = new DirectoryItem(['name' => 'test_file']); + $library = new Library(['id' => 'some-crazy-id']); + $directoryItem = new DirectoryItem(['name' => 'test_file']); - self::assertTrue($fileResource->rename($lib, $dirItem, $newFilename)); + self::assertTrue($file->rename($library, $directoryItem, $newFilename)); } /** * Data provider for testCopy() and testMove() - * - * @return array */ public static function dataProviderCopyMove(): array { @@ -603,10 +573,8 @@ public static function dataProviderCopyMove(): array * @dataProvider dataProviderCopyMove * * @param array $data Data provided - * - * @return void */ - public function testCopyMove(array $data) + public function testCopyMove(array $data): void { $sourceLib = new Library(); $sourceLib->id = 'some-crazy-id'; @@ -670,26 +638,25 @@ function ($method, $uri, $params) use ($getAllResponse, $response, $expectUri, $ } )); - $fileResource = new File($mockedClient); + $file = new File($mockedClient); - self::assertTrue($fileResource->{$data['operation']}($sourceLib, $srcPath, $destLib, $dstPath)); + self::assertTrue($file->{$data['operation']}($sourceLib, $srcPath, $destLib, $dstPath)); } /** * Test move() with invalid destination dir * - * @return void * @throws GuzzleException */ - public function testMoveInvalidDestination() + public function testMoveInvalidDestination(): void { /** @var SeafileHttpClient|MockObject $mockedClient */ $mockedClient = $this->getMockBuilder(SeafileHttpClient::class)->getMock(); - $fileResource = new File($mockedClient); + $file = new File($mockedClient); self::assertFalse( - $fileResource->move( + $file->move( new Library(), '', new Library(), @@ -701,26 +668,25 @@ public function testMoveInvalidDestination() /** * Test getFileRevisionDownloadUrl() * - * @return void * @throws GuzzleException */ - public function testGetFileRevisionDownloadUrl() + public function testGetFileRevisionDownloadUrl(): void { - $fileResource = new File($this->getMockedClient( + $file = new File($this->getMockedClient( new Response(200, ['Content-Type' => 'application/json'], '"https://some.example.com/some/url"') )); $library = new Library(); $library->id = 123; - $dirItem = new DirectoryItem(); - $dirItem->path = '/'; - $dirItem->name = 'some_test.txt'; + $directoryItem = new DirectoryItem(); + $directoryItem->path = '/'; + $directoryItem->name = 'some_test.txt'; $fileHistoryItem = new FileHistoryItem(); $fileHistoryItem->id = 345; - $downloadUrl = $fileResource->getFileRevisionDownloadUrl($library, $dirItem, $fileHistoryItem); + $downloadUrl = $file->getFileRevisionDownloadUrl($library, $directoryItem, $fileHistoryItem); // encapsulating quotes must be gone self::assertSame('https://some.example.com/some/url', $downloadUrl); @@ -731,23 +697,22 @@ public function testGetFileRevisionDownloadUrl() /** * Test downloadRevision() * - * @return void * @throws GuzzleException */ - public function testDownloadRevision() + public function testDownloadRevision(): void { $library = new Library(); $library->id = 123; - $dirItem = new DirectoryItem(); - $dirItem->path = '/'; - $dirItem->name = 'some_test.txt'; + $directoryItem = new DirectoryItem(); + $directoryItem->path = '/'; + $directoryItem->name = 'some_test.txt'; $fileHistoryItem = new FileHistoryItem(); $fileHistoryItem->id = 345; - $fileResource = new FileResourceStub($this->getMockedClient(new Response())); - $response = $fileResource->downloadRevision($library, $dirItem, $fileHistoryItem, '/tmp/yo.txt'); + $fileResourceStub = new FileResourceStub($this->getMockedClient(new Response())); + $response = $fileResourceStub->downloadRevision($library, $directoryItem, $fileHistoryItem, '/tmp/yo.txt'); self::assertInstanceOf(Response::class, $response); @@ -757,12 +722,11 @@ public function testDownloadRevision() /** * Test getHistory() * - * @return void * @throws GuzzleException */ - public function testGetHistory() + public function testGetHistory(): void { - $fileResource = new File($this->getMockedClient( + $file = new File($this->getMockedClient( new Response( 200, ['Content-Type' => 'application/json'], @@ -770,10 +734,10 @@ public function testGetHistory() ) )); - $lib = new Library(); - $lib->id = 123; + $library = new Library(); + $library->id = 123; - $fileHistoryItems = $fileResource->getHistory($lib, new DirectoryItem()); + $fileHistoryItems = $file->getHistory($library, new DirectoryItem()); self::assertIsArray($fileHistoryItems); @@ -785,23 +749,21 @@ public function testGetHistory() /** * Test create() with invalid DirectoryItem * - * @return void * @throws GuzzleException */ - public function testCreateInvalid() + public function testCreateInvalid(): void { - $fileResource = new File($this->getMockedClient(new Response())); + $file = new File($this->getMockedClient(new Response())); - self::assertFalse($fileResource->create(new Library, new DirectoryItem)); + self::assertFalse($file->create(new Library, new DirectoryItem)); } /** * Test create() with valid DirectoryItem * - * @return void * @throws GuzzleException */ - public function testCreate() + public function testCreate(): void { $clientMock = $this->getMockedClient( new Response( @@ -824,15 +786,15 @@ public function testCreate() 'success' ))); - $fileResource = new File($clientMock); + $file = new File($clientMock); - $lib = new Library; - $lib->id = 123; + $library = new Library; + $library->id = 123; - $dirItem = new DirectoryItem; - $dirItem->path = '/'; - $dirItem->name = 'some_name.txt'; + $directoryItem = new DirectoryItem; + $directoryItem->path = '/'; + $directoryItem->name = 'some_name.txt'; - self::assertTrue($fileResource->create($lib, $dirItem)); + self::assertTrue($file->create($library, $directoryItem)); } } diff --git a/test/unit/Resource/GroupTest.php b/test/unit/Resource/GroupTest.php index 02986dc..f1403cc 100644 --- a/test/unit/Resource/GroupTest.php +++ b/test/unit/Resource/GroupTest.php @@ -23,10 +23,9 @@ class GroupTest extends UnitTestCase /** * Test getAll() * - * @return void * @throws GuzzleException */ - public function testGetAll() + public function testGetAll(): void { $groupResource = new Group($this->getMockedClient( new Response( diff --git a/test/unit/Resource/LibraryTest.php b/test/unit/Resource/LibraryTest.php index 12ff84e..04cefae 100644 --- a/test/unit/Resource/LibraryTest.php +++ b/test/unit/Resource/LibraryTest.php @@ -27,12 +27,11 @@ class LibraryTest extends UnitTestCase /** * Test getAll() * - * @return void * @throws Exception */ - public function testGetAll() + public function testGetAll(): void { - $libraryResource = new Library($this->getMockedClient( + $library = new Library($this->getMockedClient( new Response( 200, ['Content-Type' => 'application/json'], @@ -40,7 +39,7 @@ public function testGetAll() ) )); - $libs = $libraryResource->getAll(); + $libs = $library->getAll(); self::assertIsArray($libs); @@ -52,12 +51,11 @@ public function testGetAll() /** * getById() * - * @return void * @throws Exception */ - public function testGetById() + public function testGetById(): void { - $libraryResource = new Library($this->getMockedClient( + $library = new Library($this->getMockedClient( new Response( 200, ['Content-Type' => 'application/json'], @@ -65,16 +63,15 @@ public function testGetById() ) )); - self::assertInstanceOf(LibraryType::class, $libraryResource->getById('some_id')); + self::assertInstanceOf(LibraryType::class, $library->getById('some_id')); } /** * Try to decrypt without query parameters. Must fail of course. * - * @return void * @throws Exception */ - public function testDecryptMissingQuery() + public function testDecryptMissingQuery(): void { $library = new Library($this->getMockedClient(new Response)); $this->expectException('Exception'); @@ -84,10 +81,9 @@ public function testDecryptMissingQuery() /** * Try to decrypt without password. Must fail of course. * - * @return void * @throws Exception */ - public function testDecryptMissingPassword() + public function testDecryptMissingPassword(): void { $library = new Library($this->getMockedClient(new Response)); $this->expectException('Exception'); @@ -97,10 +93,9 @@ public function testDecryptMissingPassword() /** * Decryption fails * - * @return void * @throws Exception */ - public function testDecryptUnsuccessfully() + public function testDecryptUnsuccessfully(): void { $library = new Library($this->getMockedClient( new Response( @@ -121,10 +116,9 @@ public function testDecryptUnsuccessfully() /** * Decryption succeeds * - * @return void * @throws Exception */ - public function testDecryptSuccessfully() + public function testDecryptSuccessfully(): void { $library = new Library($this->getMockedClient( new Response( @@ -144,8 +138,6 @@ public function testDecryptSuccessfully() /** * Data provider for testExists() - * - * @return array */ public static function dataProviderExists(): array { @@ -164,12 +156,11 @@ public static function dataProviderExists(): array * * @param array $data Test data * - * @return void * @throws GuzzleException */ - public function testExists(array $data) + public function testExists(array $data): void { - $libraryResource = new Library($this->getMockedClient( + $library = new Library($this->getMockedClient( new Response( 200, ['Content-Type' => 'application/json'], @@ -177,13 +168,11 @@ public function testExists(array $data) ) )); - self::assertSame($data[2], $libraryResource->exists($data[0], $data[1])); + self::assertSame($data[2], $library->exists($data[0], $data[1])); } /** * DataProvider for testCreateInvalid() - * - * @return array */ public static function dataProviderCreateInvalid(): array { @@ -200,12 +189,11 @@ public static function dataProviderCreateInvalid(): array * * @param array $data Test data * - * @return void * @throws GuzzleException */ - public function testCreateInvalid(array $data) + public function testCreateInvalid(array $data): void { - $libraryResource = new Library($this->getMockedClient( + $library = new Library($this->getMockedClient( new Response( 200, ['Content-Type' => 'application/json'], @@ -213,18 +201,17 @@ public function testCreateInvalid(array $data) ) )); - self::assertSame($data[1], $libraryResource->create($data[0])); + self::assertSame($data[1], $library->create($data[0])); } /** * Test remove(), provide invalid parameters, expect failure * - * @return void * @throws GuzzleException */ - public function testRemoveInvalid() + public function testRemoveInvalid(): void { - $libraryResource = new Library($this->getMockedClient( + $library = new Library($this->getMockedClient( new Response( 200, ['Content-Type' => 'application/json'], @@ -232,13 +219,11 @@ public function testRemoveInvalid() ) )); - self::assertFalse($libraryResource->remove('')); + self::assertFalse($library->remove('')); } /** * DataProvider for create() - * - * @return array */ public static function dataProviderCreate(): array { @@ -257,10 +242,9 @@ public static function dataProviderCreate(): array * * @param array $data Test data * - * @return void * @throws GuzzleException */ - public function testCreate(array $data) + public function testCreate(array $data): void { $getAllResponse = new Response( 200, @@ -333,11 +317,10 @@ function ($method, $uri, $params) use ($getAllResponse, $createResponse, $expect /** * Test remove() * - * @return void * @throws Exception * @throws GuzzleException */ - public function testRemove() + public function testRemove(): void { $getAllResponse = new Response( 200, diff --git a/test/unit/Resource/MultiTest.php b/test/unit/Resource/MultiTest.php index 1f6329d..a768bda 100644 --- a/test/unit/Resource/MultiTest.php +++ b/test/unit/Resource/MultiTest.php @@ -26,47 +26,43 @@ class MultiTest extends UnitTestCase /** * Test delete() with empty paths * - * @return void * @throws GuzzleException * @throws Exception */ - public function testDeleteEmpty() + public function testDeleteEmpty(): void { /** @var SeafileHttpClient|MockObject $mockedClient */ $mockedClient = $this->getMockBuilder(SeafileHttpClient::class)->getMock(); - $multiResource = new Multi($mockedClient); + $multi = new Multi($mockedClient); - $lib = new Library(); + $library = new Library(); - self::assertFalse($multiResource->delete($lib, [])); + self::assertFalse($multi->delete($library, [])); } /** * Test copy() and move() with empty paths * - * @return void * @throws GuzzleException * @throws Exception */ - public function testCopyMoveEmpty() + public function testCopyMoveEmpty(): void { /** @var SeafileHttpClient|MockObject $mockedClient */ $mockedClient = $this->getMockBuilder(SeafileHttpClient::class)->getMock(); - $multiResource = new Multi($mockedClient); + $multi = new Multi($mockedClient); - $lib = new Library(); + $library = new Library(); foreach (['copy', 'move'] as $operation) { - self::assertFalse($multiResource->{$operation}($lib, [], $lib, '')); + self::assertFalse($multi->{$operation}($library, [], $library, '')); } } /** * Data provider for testDelete() - * - * @return array */ public static function dataProviderDelete(): array { @@ -109,11 +105,10 @@ public static function dataProviderDelete(): array * * @param array $data DataProvider data * - * @return void * @throws GuzzleException * @throws Exception */ - public function testDelete(array $data) + public function testDelete(array $data): void { $getAllResponse = new Response( 200, @@ -163,18 +158,16 @@ function ($method, $uri, $params) use ($getAllResponse, $deleteResponse, $expect } )); - $fileResource = new Multi($mockedClient); + $multi = new Multi($mockedClient); - $lib = new Library(); - $lib->id = 'some-crazy-id'; + $library = new Library(); + $library->id = 'some-crazy-id'; - self::assertSame($data['assert'], $fileResource->delete($lib, $deletePaths)); + self::assertSame($data['assert'], $multi->delete($library, $deletePaths)); } /** * Data provider for testCopyMove() - * - * @return array */ public static function dataProviderCopyMove(): array { @@ -249,11 +242,10 @@ public static function dataProviderCopyMove(): array * * @param array $data DataProvider data * - * @return void * @throws GuzzleException * @throws Exception */ - public function testCopyMove(array $data) + public function testCopyMove(array $data): void { $getAllResponse = new Response( 200, @@ -318,11 +310,11 @@ function ($method, $uri, $params) use ($getAllResponse, $deleteResponse, $expect } )); - $fileResource = new Multi($mockedClient); + $multi = new Multi($mockedClient); self::assertSame( $data['assert'], - $fileResource->{$data['operation']}($srcLib, $filePaths, $dstLib, $destDir) + $multi->{$data['operation']}($srcLib, $filePaths, $dstLib, $destDir) ); } } diff --git a/test/unit/Resource/ResourceTest.php b/test/unit/Resource/ResourceTest.php index 515efe7..4c66ccb 100644 --- a/test/unit/Resource/ResourceTest.php +++ b/test/unit/Resource/ResourceTest.php @@ -24,12 +24,10 @@ class ResourceTest extends UnitTestCase { /** * Test that clipUri() will consistently return URIs without trailing slash. - * - * @return void */ - public function testClipUri() + public function testClipUri(): void { - $directoryResource = new Directory($this->getMockedClient( + $directory = new Directory($this->getMockedClient( new Response(200, ['Content-Type' => 'application/json'], '') )); @@ -41,16 +39,14 @@ public function testClipUri() ]; foreach ($uris as $uri => $clippedUri) { - self::assertSame($clippedUri, $directoryResource->clipUri($uri)); + self::assertSame($clippedUri, $directory->clipUri($uri)); } } /** * Test that getApiBaseUrl() returns the actual API base url depending on the resource. - * - * @return void */ - public function testGetApiBaseUrl() + public function testGetApiBaseUrl(): void { /** @var Client|MockObject $mockedClient */ $mockedClient = $this->getMockBuilder(Client::class)->getMock(); @@ -67,7 +63,7 @@ public function testGetApiBaseUrl() ->method('getConfig') ->willReturn('https://example.com/seafile'); - $shareLinkResource = new ShareLinks($mockedClient); - self::assertSame('http://example.com/seafile/api/v2.1', $shareLinkResource->getApiBaseUrl()); + $shareLinks = new ShareLinks($mockedClient); + self::assertSame('http://example.com/seafile/api/v2.1', $shareLinks->getApiBaseUrl()); } } diff --git a/test/unit/Resource/ShareLinksTest.php b/test/unit/Resource/ShareLinksTest.php index 386a35d..e5d76d7 100644 --- a/test/unit/Resource/ShareLinksTest.php +++ b/test/unit/Resource/ShareLinksTest.php @@ -28,13 +28,12 @@ class ShareLinksTest extends UnitTestCase /** * Test getAll() * - * @return void * @throws GuzzleException * @throws Exception */ - public function testGetAll() + public function testGetAll(): void { - $sharedLinkResource = new ShareLinks($this->getMockedClient( + $shareLinks = new ShareLinks($this->getMockedClient( new Response( 200, ['Content-Type' => 'application/json'], @@ -42,7 +41,7 @@ public function testGetAll() ) )); - $sharedLinks = $sharedLinkResource->getAll(); + $sharedLinks = $shareLinks->getAll(); self::assertIsArray($sharedLinks); @@ -53,14 +52,13 @@ public function testGetAll() /** * Provide test data for remove() - * @return array */ public static function dataProviderRemove(): array { // removeResponseCode, responseBody, expectedResult return [ - [200, "{\"success\":true}", true], // test normal success case - [200, "{\"success\":false}", false], // test 'soft' error + [200, '{"success":true}', true], // test normal success case + [200, '{"success":false}', false], // test 'soft' error [500, "", false] // test 'hard' error ]; } @@ -70,14 +68,10 @@ public static function dataProviderRemove(): array * * @dataProvider dataProviderRemove * - * @param int $removeResponseCode - * @param string $responseBody - * @param bool $expectedResult * - * @return void * @throws Exception */ - public function testRemove(int $removeResponseCode, string $responseBody, bool $expectedResult) + public function testRemove(int $removeResponseCode, string $responseBody, bool $expectedResult): void { $removeResponse = new Response( $removeResponseCode, @@ -94,19 +88,17 @@ public function testRemove(int $removeResponseCode, string $responseBody, bool $ ->method('request') ->willReturn($removeResponse); - $shareLinksResource = new ShareLinks($mockedClient); + $shareLinks = new ShareLinks($mockedClient); $sharedLink = new SharedLink(); $sharedLink->url = 'https://seafile.example.com/f/abc/'; $sharedLink->token = 'some_token'; - self::assertSame($expectedResult, $shareLinksResource->remove($sharedLink)); + self::assertSame($expectedResult, $shareLinks->remove($sharedLink)); } /** * DataProvider for create() - * - * @return array */ public static function dataProviderCreate(): array { @@ -114,7 +106,7 @@ public static function dataProviderCreate(): array return [ [ // test normal successful case 200, - 'Seafile\Client\Type\SharedLink', + SharedLink::class, file_get_contents(__DIR__ . '/../../assets/ShareLinksTest_create.json') ], [ // test error handling @@ -135,13 +127,9 @@ public static function dataProviderCreate(): array * * @dataProvider dataProviderCreate * - * @param int $createResponseCode - * @param string|null $returnType - * @param string $responseBody - * @return void * @throws Exception */ - public function testCreate(int $createResponseCode, ?string $returnType, string $responseBody) + public function testCreate(int $createResponseCode, ?string $returnType, string $responseBody): void { $headers = [ 'Content-Type' => 'application/json', @@ -162,24 +150,24 @@ public function testCreate(int $createResponseCode, ?string $returnType, string ->with('base_uri') ->willReturn('http://example.com'); - $sharedLinkResource = new ShareLinks($mockedClient); + $shareLinks = new ShareLinks($mockedClient); - $sharedLinkType = new SharedLink(); - $sharedLinkType->url = 'https://seafile.example.com/f/abc/'; + $sharedLink = new SharedLink(); + $sharedLink->url = 'https://seafile.example.com/f/abc/'; - $libraryType = new LibraryType(); - $libraryType->id = 'decaf-deadbeef-dad'; + $library = new LibraryType(); + $library->id = 'decaf-deadbeef-dad'; - $permissions = new SharedLinkPermissions(SharedLinkPermissions::CAN_DOWNLOAD); + $sharedLinkPermissions = new SharedLinkPermissions(SharedLinkPermissions::CAN_DOWNLOAD); if (is_null($returnType)) { self::assertNull( - $sharedLinkResource->create($libraryType, '/abc', $permissions, 123, 'pa55word') + $shareLinks->create($library, '/abc', $sharedLinkPermissions, 123, 'pa55word') ); } else { self::assertInstanceOf( $returnType, - $sharedLinkResource->create($libraryType, '/abc', $permissions, 123, 'pa55word') + $shareLinks->create($library, '/abc', $sharedLinkPermissions, 123, 'pa55word') ); } } diff --git a/test/unit/Resource/StarredFileTest.php b/test/unit/Resource/StarredFileTest.php index d7a7ac4..ebda192 100644 --- a/test/unit/Resource/StarredFileTest.php +++ b/test/unit/Resource/StarredFileTest.php @@ -27,13 +27,12 @@ class StarredFileTest extends UnitTestCase /** * Test getAll() * - * @return void * @throws GuzzleException * @throws Exception */ - public function testGetAll() + public function testGetAll(): void { - $starredFileResource = new StarredFile($this->getMockedClient( + $starredFile = new StarredFile($this->getMockedClient( new Response( 200, ['Content-Type' => 'application/json'], @@ -41,7 +40,7 @@ public function testGetAll() ) )); - $starredDirItems = $starredFileResource->getAll(); + $starredDirItems = $starredFile->getAll(); self::assertIsArray($starredDirItems); @@ -53,35 +52,33 @@ public function testGetAll() /** * Test star() with wrong DirItem type * - * @return void * @throws GuzzleException * @throws Exception */ - public function testStarWrongType() + public function testStarWrongType(): void { - $starredFileResource = new StarredFile($this->getMockedClient(new Response())); + $starredFile = new StarredFile($this->getMockedClient(new Response())); $this->expectException('Exception'); $this->expectExceptionMessage('Cannot star other items than files.'); - $starredFileResource->star(new LibraryType(), new DirectoryItem()); + $starredFile->star(new LibraryType(), new DirectoryItem()); } /** * Test star() * - * @return void * @throws GuzzleException * @throws Exception */ - public function testStar() + public function testStar(): void { - $lib = new LibraryType(); - $lib->id = 123; + $library = new LibraryType(); + $library->id = 123; - $dirItem = new DirectoryItem(); - $dirItem->type = 'file'; - $dirItem->path = '/some/path'; + $directoryItem = new DirectoryItem(); + $directoryItem->type = 'file'; + $directoryItem->path = '/some/path'; $responseUrl = 'https://example.com/test/'; @@ -108,7 +105,7 @@ public function testStar() ) // Return what was passed to offsetGet as a new instance ->will(self::returnCallback( - function ($method, $uri, $params) use ($starResponse, $lib, $dirItem) { + function ($method, $uri, array $params) use ($starResponse, $library, $directoryItem): Response|\Response { $hasParams = array_key_exists('headers', $params) && array_key_exists('multipart', $params) @@ -117,8 +114,8 @@ function ($method, $uri, $params) use ($starResponse, $lib, $dirItem) { && array_key_exists('name', $params['multipart'][1]) && array_key_exists('contents', $params['multipart'][1]); - $hasContents = $params['multipart'][0]['contents'] === $lib->id - && $params['multipart'][1]['contents'] === $dirItem->path; + $hasContents = $params['multipart'][0]['contents'] === $library->id + && $params['multipart'][1]['contents'] === $directoryItem->path; if ($hasParams && $hasContents @@ -132,9 +129,9 @@ function ($method, $uri, $params) use ($starResponse, $lib, $dirItem) { } )); - $starredFileResource = new StarredFile($mockedClient); + $starredFile = new StarredFile($mockedClient); - $result = $starredFileResource->star($lib, $dirItem); + $result = $starredFile->star($library, $directoryItem); self::assertSame($responseUrl, $result); } @@ -142,18 +139,17 @@ function ($method, $uri, $params) use ($starResponse, $lib, $dirItem) { /** * Test star() with error response * - * @return void * @throws Exception * @throws GuzzleException */ - public function testStarErrorStatusCode() + public function testStarErrorStatusCode(): void { - $lib = new LibraryType(); - $lib->id = 123; + $library = new LibraryType(); + $library->id = 123; - $dirItem = new DirectoryItem(); - $dirItem->type = 'file'; - $dirItem->path = '/some/path'; + $directoryItem = new DirectoryItem(); + $directoryItem->type = 'file'; + $directoryItem->path = '/some/path'; $responseUrl = 'https://example.com/test/'; @@ -178,29 +174,28 @@ public function testStarErrorStatusCode() ->with('POST') ->willReturn($starResponse); - $starredFileResource = new StarredFile($mockedClient); + $starredFile = new StarredFile($mockedClient); $this->expectException('Exception'); $this->expectExceptionMessage('Could not star file'); - $starredFileResource->star($lib, $dirItem); + $starredFile->star($library, $directoryItem); } /** * Test star() with missing location * - * @return void * @throws Exception * @throws GuzzleException */ - public function testStarErrorMissingLocation() + public function testStarErrorMissingLocation(): void { - $lib = new LibraryType(); - $lib->id = 123; + $library = new LibraryType(); + $library->id = 123; - $dirItem = new DirectoryItem(); - $dirItem->type = 'file'; - $dirItem->path = '/some/path'; + $directoryItem = new DirectoryItem(); + $directoryItem->type = 'file'; + $directoryItem->path = '/some/path'; /** @var SeafileHttpClient|MockObject $mockedClient */ $mockedClient = $this->getMockBuilder(SeafileHttpClient::class)->getMock(); @@ -215,18 +210,16 @@ public function testStarErrorMissingLocation() ->with('POST') ->willReturn(new Response(500)); - $starredFileResource = new StarredFile($mockedClient); + $starredFile = new StarredFile($mockedClient); $this->expectException('Exception'); $this->expectExceptionMessage('Could not star file'); - $starredFileResource->star($lib, $dirItem); + $starredFile->star($library, $directoryItem); } /** * DataProvider for unstar() - * - * @return array */ public static function dataProviderUnstar(): array { @@ -251,19 +244,18 @@ public static function dataProviderUnstar(): array * * @param array $data Data provider array * - * @return void * @throws GuzzleException * @throws Exception * @dataProvider dataProviderUnstar */ - public function testUnstar(array $data) + public function testUnstar(array $data): void { - $lib = new LibraryType(); - $lib->id = 123; + $library = new LibraryType(); + $library->id = 123; - $dirItem = new DirectoryItem(); - $dirItem->type = 'file'; - $dirItem->path = '/some/path'; + $directoryItem = new DirectoryItem(); + $directoryItem->type = 'file'; + $directoryItem->path = '/some/path'; /** @var SeafileHttpClient|MockObject $mockedClient */ $mockedClient = $this->getMockBuilder(SeafileHttpClient::class)->getMock(); @@ -280,11 +272,11 @@ public function testUnstar(array $data) new Response($data['responseCode']) ); - $starredFileResource = new StarredFile($mockedClient); + $starredFile = new StarredFile($mockedClient); self::assertSame( $data['result'], - $starredFileResource->unstar($lib, $dirItem) + $starredFile->unstar($library, $directoryItem) ); } } diff --git a/test/unit/Stubs/FileResourceStub.php b/test/unit/Stubs/FileResourceStub.php index c26f2d9..794eb82 100644 --- a/test/unit/Stubs/FileResourceStub.php +++ b/test/unit/Stubs/FileResourceStub.php @@ -20,35 +20,27 @@ class FileResourceStub extends File /** * Get download URL of a file * - * @param LibraryType $library Library instance - * @param DirectoryItem $item Item instance + * @param LibraryType $libraryType Library instance + * @param DirectoryItem $directoryItem Item instance * @param string $dir Dir string * @param int $reuse Reuse more than once per hour - * - * @return string */ - public function getDownloadUrl(LibraryType $library, DirectoryItem $item, string $dir = '/', int $reuse = 1) + public function getDownloadUrl(LibraryType $libraryType, DirectoryItem $directoryItem, string $dir = '/', int $reuse = 1): string { - $library = null; - $item = null; - $dir = null; - $reuse = null; return 'http://download.example.com/'; } /** * Get upload URL * - * @param LibraryType $library Library instance + * @param LibraryType $libraryType Library instance * @param bool $newFile Is new file (=upload) or not (=update) * @param string $dir Directory to upload to * * @return String Upload link */ - public function getUploadUrl(LibraryType $library, bool $newFile = true, string $dir = "/"): string + public function getUploadUrl(LibraryType $libraryType, bool $newFile = true, string $dir = "/"): string { - $library = null; - $newFile = null; return 'http://upload.example.com/'; } } diff --git a/test/unit/Type/DirectoryItemUnitTest.php b/test/unit/Type/DirectoryItemUnitTest.php index c0b0b09..045dfe1 100644 --- a/test/unit/Type/DirectoryItemUnitTest.php +++ b/test/unit/Type/DirectoryItemUnitTest.php @@ -21,10 +21,8 @@ class DirectoryItemUnitTest extends UnitTestCase { /** * DataProvider for testFromArray() - * - * @return array */ - public function dataFromArray() + public function dataFromArray(): array { return [ // [[expect response code, expected result, password]] @@ -48,18 +46,17 @@ public function dataFromArray() * * @param array $data Dataprovider array * - * @return void * @dataProvider dataFromArray * @throws GuzzleException * @throws Exception */ - public function testFromArray(array $data) + public function testFromArray(array $data): void { - $dirItem = new DirectoryItem([ + $directoryItem = new DirectoryItem([ 'dir' => $data['dir'], ]); - self::assertSame($data['dir'], $dirItem->dir); - self::assertSame($data['type'], $dirItem->type); + self::assertSame($data['dir'], $directoryItem->dir); + self::assertSame($data['type'], $directoryItem->type); } } diff --git a/test/unit/Type/TypeUnitTest.php b/test/unit/Type/TypeUnitTest.php index f1a726c..12a1e8c 100644 --- a/test/unit/Type/TypeUnitTest.php +++ b/test/unit/Type/TypeUnitTest.php @@ -26,33 +26,31 @@ class TypeUnitTest extends UnitTestCase /** * Test fromArray() * - * @return void * @throws Exception */ - public function testFromArray() + public function testFromArray(): void { - $dirItem = new DirectoryItem([ + $directoryItem = new DirectoryItem([ 'id' => 1, 'size' => 2, 'name' => 'my name', 'type' => 'my type', ]); - self::assertSame(1, $dirItem->id); - self::assertSame(2, $dirItem->size); - self::assertSame('my name', $dirItem->name); - self::assertSame('my type', $dirItem->type); + self::assertSame(1, $directoryItem->id); + self::assertSame(2, $directoryItem->size); + self::assertSame('my name', $directoryItem->name); + self::assertSame('my type', $directoryItem->type); } /** * Test fromArray() with a non-existing property * - * @return void * @throws Exception */ - public function testFromArrayPropertyMissing() + public function testFromArrayPropertyMissing(): void { - $dirItem = new DirectoryItem([ + $directoryItem = new DirectoryItem([ 'id' => 1, 'size' => 2, 'name' => 'my name', @@ -72,53 +70,49 @@ public function testFromArrayPropertyMissing() 'path' => null, 'repo' => null, ], - (array)$dirItem + (array)$directoryItem ); } /** * Test fromArray() with create_time property * - * @return void * @throws Exception */ - public function testFromArrayCreateTime() + public function testFromArrayCreateTime(): void { - $accountType = new AccountType([ + $account = new AccountType([ 'create_time' => '1452202279000000', ]); - self::assertSame('2016-01-07T21:31:19+0000', $accountType->createTime->format(DateTime::ISO8601)); + self::assertSame('2016-01-07T21:31:19+00:00', $account->createTime->format(\DateTimeInterface::ATOM)); } /** * Test fromJson() with create_time property * - * @return void * @throws Exception */ - public function testFromJsonCreateTime() + public function testFromJsonCreateTime(): void { - $accountType = new AccountType(); + $account = new AccountType(); - $accountType->fromJson(json_decode(json_encode([ + $account->fromJson(json_decode(json_encode([ 'create_time' => '1452202279000000', ]))); - self::assertSame('2016-01-07T21:31:19+0000', $accountType->createTime->format(DateTime::ISO8601)); + self::assertSame('2016-01-07T21:31:19+00:00', $account->createTime->format(\DateTimeInterface::ATOM)); } /** * Test toJson() * - * @return void * @throws Exception */ - public function testJson() + public function testJson(): void { - $accountType = new AccountType(); - - $jsonString = $accountType->toJson(); + $account = new AccountType(); + $jsonString = $account->toJson(); self::assertStringStartsWith('{"contactEmail":null', $jsonString); self::assertStringEndsWith('"total":null,"usage":null}', $jsonString); @@ -126,8 +120,6 @@ public function testJson() /** * Data provider for testToArrayAssoc() - * - * @return array */ public static function dataProviderTestToArrayAssoc(): array { @@ -140,8 +132,8 @@ public static function dataProviderTestToArrayAssoc(): array ], [ [ - ['createTime' => 1452202279000000], - ['createTime' => 1452202279000000] // no empty values + ['create_time' => 1452202279000000], + ['createTime' => DateTime::createFromFormat(\DateTimeInterface::ATOM, '2016-01-07T21:31:19+0000')] // no empty values ], ], ]; @@ -152,22 +144,18 @@ public static function dataProviderTestToArrayAssoc(): array * * @param array $data Data provider array * - * @return void * @dataProvider dataProviderTestToArrayAssoc * @throws Exception */ - public function testToArrayAssoc(array $data) + public function testToArrayAssoc(array $data): void { $accountType = (new AccountType())->fromArray($data[0]); - self::assertEquals($data[1], $accountType->toArray()); } /** * Data provider for testToArrayMultiPart() - * - * @return array */ public static function dataProviderTestToArrayMultiPart(): array { @@ -180,8 +168,8 @@ public static function dataProviderTestToArrayMultiPart(): array ], [ [ - ['createTime' => 1452202279000000], - [['name' => 'create_time', 'contents' => '1452202279000000']] // no empty values + ['create_time' => 1452202279000000], + [['name' => 'create_time', 'contents' => '1452202279']] // no empty values ], ], ]; @@ -192,11 +180,10 @@ public static function dataProviderTestToArrayMultiPart(): array * * @param array $data Data provider array * - * @return void * @dataProvider dataProviderTestToArrayMultiPart * @throws Exception */ - public function testToArrayMultiPart(array $data) + public function testToArrayMultiPart(array $data): void { $accountType = (new AccountType())->fromArray($data[0]); @@ -208,14 +195,13 @@ public function testToArrayMultiPart(array $data) * * Must yield AccountType instance * - * @return void * @throws Exception */ - public function testFromArrayCreator() + public function testFromArrayCreator(): void { $email = 'someone@example.com'; $groupType = (new GroupType())->fromArray(['creator' => $email]); - self::assertInstanceOf(Account::class, $groupType->creator); + self::assertInstanceOf(AccountType::class, $groupType->creator); self::assertSame($email, $groupType->creator->email); } } diff --git a/test/unit/UnitTestCase.php b/test/unit/UnitTestCase.php index 35dd5a2..6e4cacb 100644 --- a/test/unit/UnitTestCase.php +++ b/test/unit/UnitTestCase.php @@ -32,11 +32,11 @@ class UnitTestCase extends TestCase */ public function invokeMethod(&$object, string $methodName, array $parameters = []) { - $reflection = new ReflectionClass(get_class($object)); - $method = $reflection->getMethod($methodName); - $method->setAccessible(true); + $reflectionClass = new ReflectionClass($object::class); + $reflectionMethod = $reflectionClass->getMethod($methodName); + $reflectionMethod->setAccessible(true); - return $method->invokeArgs($object, $parameters); + return $reflectionMethod->invokeArgs($object, $parameters); } /**