From 8690b5a1541204f4445822ad61a2621e015a2d48 Mon Sep 17 00:00:00 2001 From: Dimitar Yanakiev Date: Fri, 5 Jan 2018 01:06:01 +0200 Subject: [PATCH 01/20] Update database.php --- config/database.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/database.php b/config/database.php index 15d708f16..acbc8627b 100644 --- a/config/database.php +++ b/config/database.php @@ -40,7 +40,7 @@ return [ 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', - 'prefix' => '', + 'prefix' => env('DB_PREFIX', ''), 'strict' => env('DB_STRICT_MODE', false), ], ], From 60eb60013c14e9d02eba449f12f107f801e992a8 Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Thu, 4 Jan 2018 22:49:50 -0600 Subject: [PATCH 02/20] Update repository base code to be cleaner and make use of PHP 7 features --- .../Commands/User/DeleteUserCommand.php | 2 +- .../Commands/User/DisableTwoFactorCommand.php | 2 +- .../AllocationRepositoryInterface.php | 15 +- .../Attributes/SearchableInterface.php | 35 ++- .../DaemonKeyRepositoryInterface.php | 32 +-- .../DatabaseHostRepositoryInterface.php | 22 +- .../DatabaseRepositoryInterface.php | 21 +- .../LocationRepositoryInterface.php | 19 +- .../Repository/NodeRepositoryInterface.php | 49 ++-- .../Repository/PackRepositoryInterface.php | 36 +-- .../Repository/RepositoryInterface.php | 101 ++++---- .../ScheduleRepositoryInterface.php | 9 +- .../Repository/ServerRepositoryInterface.php | 93 +++---- .../ServerVariableRepositoryInterface.php | 7 - .../Repository/SessionRepositoryInterface.php | 27 +- .../SettingsRepositoryInterface.php | 5 +- .../Repository/SubuserRepositoryInterface.php | 21 -- .../Repository/TaskRepositoryInterface.php | 17 +- .../Repository/UserRepositoryInterface.php | 15 +- .../Controllers/Admin/DatabaseController.php | 1 - .../Controllers/Admin/NodesController.php | 14 +- app/Http/Controllers/Admin/PackController.php | 10 +- .../Controllers/Admin/ServersController.php | 8 +- app/Http/Controllers/Admin/UserController.php | 2 +- app/Http/Controllers/Base/IndexController.php | 28 +- app/Http/Middleware/DaemonAuthenticate.php | 4 +- app/Models/User.php | 5 + app/Policies/APIKeyPolicy.php | 2 +- app/Policies/ServerPolicy.php | 2 +- app/Repositories/Concerns/Searchable.php | 50 +++- app/Repositories/Daemon/ServerRepository.php | 7 - .../Eloquent/AllocationRepository.php | 29 ++- .../Eloquent/ApiKeyRepository.php | 11 +- .../Eloquent/ApiPermissionRepository.php | 11 +- .../Eloquent/DaemonKeyRepository.php | 55 ++-- .../Eloquent/DatabaseHostRepository.php | 42 +-- .../Eloquent/DatabaseRepository.php | 93 ++++--- app/Repositories/Eloquent/EggRepository.php | 36 +-- .../Eloquent/EggVariableRepository.php | 11 +- .../Eloquent/EloquentRepository.php | 240 ++++++++++-------- .../Eloquent/LocationRepository.php | 57 +++-- app/Repositories/Eloquent/NestRepository.php | 4 +- app/Repositories/Eloquent/NodeRepository.php | 157 ++++++------ app/Repositories/Eloquent/PackRepository.php | 73 ++---- .../Eloquent/PermissionRepository.php | 11 +- .../Eloquent/ScheduleRepository.php | 27 +- .../Eloquent/ServerRepository.php | 218 ++++++++-------- .../Eloquent/ServerVariableRepository.php | 11 +- .../Eloquent/SessionRepository.php | 27 +- .../Eloquent/SettingsRepository.php | 39 ++- .../Eloquent/SubuserRepository.php | 47 +--- app/Repositories/Eloquent/TaskRepository.php | 42 ++- app/Repositories/Eloquent/UserRepository.php | 61 ++--- app/Repositories/Repository.php | 87 ++++--- .../Eggs/Sharing/EggUpdateImporterService.php | 2 +- .../Eggs/Variables/VariableUpdateService.php | 2 +- app/Services/Nodes/NodeDeletionService.php | 2 +- app/Services/Packs/PackDeletionService.php | 2 +- app/Services/Packs/PackUpdateService.php | 2 +- .../Servers/ServerDeletionService.php | 4 +- .../Sftp/AuthenticateUsingPasswordService.php | 4 +- app/Services/Users/UserDeletionService.php | 2 +- database/factories/ModelFactory.php | 1 + database/seeds/EggSeeder.php | 2 +- tests/Traits/Http/RequestMockHelpers.php | 5 +- .../Commands/User/DeleteUserCommandTest.php | 27 +- .../User/DisableTwoFactorCommandTest.php | 4 +- .../Admin/DatabaseControllerTest.php | 19 +- .../Controllers/Base/APIControllerTest.php | 14 +- .../Controllers/Base/IndexControllerTest.php | 17 +- .../Base/SecurityControllerTest.php | 4 +- .../Files/FileActionsControllerTest.php | 4 +- .../Server/SubuserControllerTest.php | 2 +- .../Middleware/DaemonAuthenticateTest.php | 2 +- .../Eloquent/AllocationRepositoryTest.php | 72 ------ .../Eloquent/ApiKeyRepositoryTest.php | 50 ---- .../Eloquent/ApiPermissionRepositoryTest.php | 50 ---- .../Eloquent/DatabaseHostRepositoryTest.php | 88 ------- .../Eloquent/DatabaseRepositoryTest.php | 157 ------------ .../Eloquent/LocationRepositoryTest.php | 100 -------- .../Allocations/AssignmentServiceTest.php | 14 +- .../DaemonKeyDeletionServiceTest.php | 6 +- .../Databases/DatabasePasswordServiceTest.php | 10 +- .../Services/Eggs/EggUpdateServiceTest.php | 1 - .../Sharing/EggUpdateImporterServiceTest.php | 10 +- .../Variables/VariableUpdateServiceTest.php | 6 +- .../Nodes/NodeDeletionServiceTest.php | 20 +- .../Packs/PackDeletionServiceTest.php | 6 +- .../Services/Packs/PackUpdateServiceTest.php | 2 +- .../Servers/ServerCreationServiceTest.php | 6 +- .../Servers/ServerDeletionServiceTest.php | 16 +- .../AuthenticateUsingPasswordServiceTest.php | 20 +- .../PermissionCreationServiceTest.php | 2 +- .../Subusers/SubuserDeletionServiceTest.php | 2 +- .../Subusers/SubuserUpdateServiceTest.php | 4 +- .../Users/UserDeletionServiceTest.php | 20 +- 96 files changed, 1048 insertions(+), 1785 deletions(-) delete mode 100644 tests/Unit/Repositories/Eloquent/AllocationRepositoryTest.php delete mode 100644 tests/Unit/Repositories/Eloquent/ApiKeyRepositoryTest.php delete mode 100644 tests/Unit/Repositories/Eloquent/ApiPermissionRepositoryTest.php delete mode 100644 tests/Unit/Repositories/Eloquent/DatabaseHostRepositoryTest.php delete mode 100644 tests/Unit/Repositories/Eloquent/DatabaseRepositoryTest.php delete mode 100644 tests/Unit/Repositories/Eloquent/LocationRepositoryTest.php diff --git a/app/Console/Commands/User/DeleteUserCommand.php b/app/Console/Commands/User/DeleteUserCommand.php index ce79a493d..c9a69bee8 100644 --- a/app/Console/Commands/User/DeleteUserCommand.php +++ b/app/Console/Commands/User/DeleteUserCommand.php @@ -61,7 +61,7 @@ class DeleteUserCommand extends Command $search = $this->option('user') ?? $this->ask(trans('command/messages.user.search_users')); Assert::notEmpty($search, 'Search term must be a non-null value, received %s.'); - $results = $this->repository->search($search)->all(); + $results = $this->repository->setSearchTerm($search)->all(); if (count($results) < 1) { $this->error(trans('command/messages.user.no_users_found')); if ($this->input->isInteractive()) { diff --git a/app/Console/Commands/User/DisableTwoFactorCommand.php b/app/Console/Commands/User/DisableTwoFactorCommand.php index 568a5a95e..7df23b41e 100644 --- a/app/Console/Commands/User/DisableTwoFactorCommand.php +++ b/app/Console/Commands/User/DisableTwoFactorCommand.php @@ -54,7 +54,7 @@ class DisableTwoFactorCommand extends Command } $email = $this->option('email') ?? $this->ask(trans('command/messages.user.ask_email')); - $user = $this->repository->withColumns(['id', 'email'])->findFirstWhere([['email', '=', $email]]); + $user = $this->repository->setColumns(['id', 'email'])->findFirstWhere([['email', '=', $email]]); $this->repository->withoutFresh()->update($user->id, [ 'use_totp' => false, diff --git a/app/Contracts/Repository/AllocationRepositoryInterface.php b/app/Contracts/Repository/AllocationRepositoryInterface.php index 90b75fced..fa854e24a 100644 --- a/app/Contracts/Repository/AllocationRepositoryInterface.php +++ b/app/Contracts/Repository/AllocationRepositoryInterface.php @@ -1,14 +1,9 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; +use Illuminate\Support\Collection; + interface AllocationRepositoryInterface extends RepositoryInterface { /** @@ -18,13 +13,13 @@ interface AllocationRepositoryInterface extends RepositoryInterface * @param array $ids * @return int */ - public function assignAllocationsToServer($server, array $ids); + public function assignAllocationsToServer(int $server = null, array $ids): int; /** * Return all of the allocations for a specific node. * * @param int $node - * @return \Illuminate\Database\Eloquent\Collection + * @return \Illuminate\Support\Collection */ - public function getAllocationsForNode($node); + public function getAllocationsForNode(int $node): Collection; } diff --git a/app/Contracts/Repository/Attributes/SearchableInterface.php b/app/Contracts/Repository/Attributes/SearchableInterface.php index 30b2a202a..f1ab6e804 100644 --- a/app/Contracts/Repository/Attributes/SearchableInterface.php +++ b/app/Contracts/Repository/Attributes/SearchableInterface.php @@ -1,21 +1,38 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository\Attributes; interface SearchableInterface { /** - * Filter results by search term. + * Set the search term. * - * @param string $term + * @param string|null $term * @return $this + * @deprecated */ public function search($term); + + /** + * Set the search term to use when requesting all records from + * the model. + * + * @param string|null $term + * @return $this + */ + public function setSearchTerm(string $term = null); + + /** + * Determine if a valid search term is set on this repository. + * + * @return bool + */ + public function hasSearchTerm(): bool; + + /** + * Return the search term. + * + * @return string|null + */ + public function getSearchTerm(); } diff --git a/app/Contracts/Repository/DaemonKeyRepositoryInterface.php b/app/Contracts/Repository/DaemonKeyRepositoryInterface.php index 4f2156ad5..7979980c0 100644 --- a/app/Contracts/Repository/DaemonKeyRepositoryInterface.php +++ b/app/Contracts/Repository/DaemonKeyRepositoryInterface.php @@ -1,26 +1,4 @@ . - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ namespace Pterodactyl\Contracts\Repository; @@ -44,14 +22,6 @@ interface DaemonKeyRepositoryInterface extends RepositoryInterface */ public function loadServerAndUserRelations(DaemonKey $key, bool $refresh = false): DaemonKey; - /** - * Gets the daemon keys associated with a specific server. - * - * @param int $server - * @return \Illuminate\Support\Collection - */ - public function getServerKeys($server); - /** * Return a daemon key with the associated server relation attached. * @@ -60,7 +30,7 @@ interface DaemonKeyRepositoryInterface extends RepositoryInterface * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getKeyWithServer($key); + public function getKeyWithServer(string $key): DaemonKey; /** * Get all of the keys for a specific user including the information needed diff --git a/app/Contracts/Repository/DatabaseHostRepositoryInterface.php b/app/Contracts/Repository/DatabaseHostRepositoryInterface.php index 955e1f7f3..dfd29e9ab 100644 --- a/app/Contracts/Repository/DatabaseHostRepositoryInterface.php +++ b/app/Contracts/Repository/DatabaseHostRepositoryInterface.php @@ -1,30 +1,28 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; +use Illuminate\Support\Collection; +use Pterodactyl\Models\DatabaseHost; + interface DatabaseHostRepositoryInterface extends RepositoryInterface { /** - * Return database hosts with a count of databases and the node information for which it is attached. + * Return database hosts with a count of databases and the node + * information for which it is attached. * * @return \Illuminate\Support\Collection */ - public function getWithViewDetails(); + public function getWithViewDetails(): Collection; /** - * Return a database host with the databases and associated servers that are attached to said databases. + * Return a database host with the databases and associated servers + * that are attached to said databases. * * @param int $id - * @return mixed + * @return \Pterodactyl\Models\DatabaseHost * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getWithServers($id); + public function getWithServers(int $id): DatabaseHost; } diff --git a/app/Contracts/Repository/DatabaseRepositoryInterface.php b/app/Contracts/Repository/DatabaseRepositoryInterface.php index 1e90d0e04..7fc3bf045 100644 --- a/app/Contracts/Repository/DatabaseRepositoryInterface.php +++ b/app/Contracts/Repository/DatabaseRepositoryInterface.php @@ -9,6 +9,7 @@ namespace Pterodactyl\Contracts\Repository; +use Pterodactyl\Models\Database; use Illuminate\Support\Collection; interface DatabaseRepositoryInterface extends RepositoryInterface @@ -43,12 +44,12 @@ interface DatabaseRepositoryInterface extends RepositoryInterface * the provided details. * * @param array $data - * @return mixed + * @return \Pterodactyl\Models\Database * - * @throws \Pterodactyl\Exceptions\DisplayException * @throws \Pterodactyl\Exceptions\Model\DataValidationException + * @throws \Pterodactyl\Exceptions\Repository\DuplicateDatabaseNameException */ - public function createIfNotExists(array $data); + public function createIfNotExists(array $data): Database; /** * Create a new database on a given connection. @@ -56,7 +57,7 @@ interface DatabaseRepositoryInterface extends RepositoryInterface * @param string $database * @return bool */ - public function createDatabase($database); + public function createDatabase(string $database): bool; /** * Create a new database user on a given connection. @@ -66,7 +67,7 @@ interface DatabaseRepositoryInterface extends RepositoryInterface * @param string $password * @return bool */ - public function createUser($username, $remote, $password); + public function createUser(string $username, string $remote, string $password): bool; /** * Give a specific user access to a given database. @@ -76,14 +77,14 @@ interface DatabaseRepositoryInterface extends RepositoryInterface * @param string $remote * @return bool */ - public function assignUserToDatabase($database, $username, $remote); + public function assignUserToDatabase(string $database, string $username, string $remote): bool; /** * Flush the privileges for a given connection. * - * @return mixed + * @return bool */ - public function flush(); + public function flush(): bool; /** * Drop a given database on a specific connection. @@ -91,7 +92,7 @@ interface DatabaseRepositoryInterface extends RepositoryInterface * @param string $database * @return bool */ - public function dropDatabase($database); + public function dropDatabase(string $database): bool; /** * Drop a given user on a specific connection. @@ -100,5 +101,5 @@ interface DatabaseRepositoryInterface extends RepositoryInterface * @param string $remote * @return mixed */ - public function dropUser($username, $remote); + public function dropUser(string $username, string $remote): bool; } diff --git a/app/Contracts/Repository/LocationRepositoryInterface.php b/app/Contracts/Repository/LocationRepositoryInterface.php index ef68fdf28..e91da6c43 100644 --- a/app/Contracts/Repository/LocationRepositoryInterface.php +++ b/app/Contracts/Repository/LocationRepositoryInterface.php @@ -1,14 +1,9 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; +use Pterodactyl\Models\Location; +use Illuminate\Support\Collection; use Pterodactyl\Contracts\Repository\Attributes\SearchableInterface; interface LocationRepositoryInterface extends RepositoryInterface, SearchableInterface @@ -16,16 +11,16 @@ interface LocationRepositoryInterface extends RepositoryInterface, SearchableInt /** * Return locations with a count of nodes and servers attached to it. * - * @return mixed + * @return \Illuminate\Support\Collection */ - public function getAllWithDetails(); + public function getAllWithDetails(): Collection; /** * Return all of the available locations with the nodes as a relationship. * * @return \Illuminate\Support\Collection */ - public function getAllWithNodes(); + public function getAllWithNodes(): Collection; /** * Return all of the nodes and their respective count of servers for a location. @@ -35,7 +30,7 @@ interface LocationRepositoryInterface extends RepositoryInterface, SearchableInt * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getWithNodes($id); + public function getWithNodes(int $id): Location; /** * Return a location and the count of nodes in that location. @@ -45,5 +40,5 @@ interface LocationRepositoryInterface extends RepositoryInterface, SearchableInt * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getWithNodeCount($id); + public function getWithNodeCount(int $id): Location; } diff --git a/app/Contracts/Repository/NodeRepositoryInterface.php b/app/Contracts/Repository/NodeRepositoryInterface.php index 078a274db..49db33be8 100644 --- a/app/Contracts/Repository/NodeRepositoryInterface.php +++ b/app/Contracts/Repository/NodeRepositoryInterface.php @@ -1,68 +1,65 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; +use Pterodactyl\Models\Node; +use Illuminate\Support\Collection; +use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Pterodactyl\Contracts\Repository\Attributes\SearchableInterface; interface NodeRepositoryInterface extends RepositoryInterface, SearchableInterface { + const THRESHOLD_PERCENTAGE_LOW = 75; + const THRESHOLD_PERCENTAGE_MEDIUM = 90; + /** * Return the usage stats for a single node. * - * @param int $id + * @param \Pterodactyl\Models\Node $node * @return array */ - public function getUsageStats($id); + public function getUsageStats(Node $node): array; /** * Return all available nodes with a searchable interface. * - * @param int $count * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ - public function getNodeListingData($count = 25); + public function getNodeListingData(): LengthAwarePaginator; /** * Return a single node with location and server information. * - * @param int $id - * @return mixed - * - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException + * @param \Pterodactyl\Models\Node $node + * @param bool $refresh + * @return \Pterodactyl\Models\Node */ - public function getSingleNode($id); + public function loadLocationAndServerCount(Node $node, bool $refresh = false): Node; /** - * Return a node with all of the associated allocations and servers that are attached to said allocations. + * Attach a paginated set of allocations to a node mode including + * any servers that are also attached to those allocations. * - * @param int $id - * @return mixed - * - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException + * @param \Pterodactyl\Models\Node $node + * @param bool $refresh + * @return \Pterodactyl\Models\Node */ - public function getNodeAllocations($id); + public function loadNodeAllocations(Node $node, bool $refresh = false): Node; /** * Return a node with all of the servers attached to that node. * * @param int $id - * @return mixed + * @return \Pterodactyl\Models\Node * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getNodeServers($id); + public function getNodeServers(int $id): Node; /** * Return a collection of nodes for all locations to use in server creation UI. * - * @return mixed + * @return \Illuminate\Support\Collection */ - public function getNodesForServerCreation(); + public function getNodesForServerCreation(): Collection; } diff --git a/app/Contracts/Repository/PackRepositoryInterface.php b/app/Contracts/Repository/PackRepositoryInterface.php index d6ad80785..6ef7cef7f 100644 --- a/app/Contracts/Repository/PackRepositoryInterface.php +++ b/app/Contracts/Repository/PackRepositoryInterface.php @@ -1,44 +1,26 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; +use Pterodactyl\Models\Pack; +use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Pterodactyl\Contracts\Repository\Attributes\SearchableInterface; interface PackRepositoryInterface extends RepositoryInterface, SearchableInterface { - /** - * Return a paginated listing of packs with their associated egg and server count. - * - * @param int $paginate - * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator - */ - public function paginateWithEggAndServerCount($paginate = 50); - /** * Return a pack with the associated server models attached to it. * - * @param int $id - * @return \Illuminate\Database\Eloquent\Collection - * - * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + * @param \Pterodactyl\Models\Pack $pack + * @param bool $refresh + * @return \Pterodactyl\Models\Pack */ - public function getWithServers($id); + public function loadServerData(Pack $pack, bool $refresh = false): Pack; /** - * Return all of the file archives for a given pack. + * Return a paginated listing of packs with their associated egg and server count. * - * @param int $id - * @param bool $collection - * @return object|\Illuminate\Support\Collection - * - * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ - public function getFileArchives($id, $collection = false); + public function paginateWithEggAndServerCount(): LengthAwarePaginator; } diff --git a/app/Contracts/Repository/RepositoryInterface.php b/app/Contracts/Repository/RepositoryInterface.php index f31e852d8..028058af4 100644 --- a/app/Contracts/Repository/RepositoryInterface.php +++ b/app/Contracts/Repository/RepositoryInterface.php @@ -1,14 +1,9 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; +use Illuminate\Support\Collection; + interface RepositoryInterface { /** @@ -42,17 +37,34 @@ interface RepositoryInterface /** * An array of columns to filter the response by. * - * @param array $columns + * @param array|string $columns * @return $this */ - public function withColumns($columns = ['*']); + public function setColumns($columns = ['*']); /** - * Disable returning a fresh model when data is inserted or updated. + * Stop repository update functions from returning a fresh + * model when changes are committed. * * @return $this */ - public function withoutFresh(); + public function withoutFreshModel(); + + /** + * Return a fresh model with a repository updates a model. + * + * @return $this + */ + public function withFreshModel(); + + /** + * Set wether or not the repository should return a fresh model + * when changes are committed. + * + * @param bool $fresh + * @return $this + */ + public function setFreshModel(bool $fresh = true); /** * Create a new model instance and persist it to the database. @@ -64,23 +76,7 @@ interface RepositoryInterface * * @throws \Pterodactyl\Exceptions\Model\DataValidationException */ - public function create(array $fields, $validate = true, $force = false); - - /** - * Delete a given record from the database. - * - * @param int $id - * @return int - */ - public function delete($id); - - /** - * Delete records matching the given attributes. - * - * @param array $attributes - * @return int - */ - public function deleteWhere(array $attributes); + public function create(array $fields, bool $validate = true, bool $force = false); /** * Find a model that has the specific ID passed. @@ -90,15 +86,15 @@ interface RepositoryInterface * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function find($id); + public function find(int $id); /** * Find a model matching an array of where clauses. * * @param array $fields - * @return mixed + * @return \Illuminate\Support\Collection */ - public function findWhere(array $fields); + public function findWhere(array $fields): Collection; /** * Find and return the first matching instance for the given fields. @@ -116,7 +112,23 @@ interface RepositoryInterface * @param array $fields * @return int */ - public function findCountWhere(array $fields); + public function findCountWhere(array $fields): int; + + /** + * Delete a given record from the database. + * + * @param int $id + * @return int + */ + public function delete(int $id): int; + + /** + * Delete records matching the given attributes. + * + * @param array $attributes + * @return int + */ + public function deleteWhere(array $attributes): int; /** * Update a given ID with the passed array of fields. @@ -130,7 +142,7 @@ interface RepositoryInterface * @throws \Pterodactyl\Exceptions\Model\DataValidationException * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function update($id, array $fields, $validate = true, $force = false); + public function update($id, array $fields, bool $validate = true, bool $force = false); /** * Perform a mass update where matching records are updated using whereIn. @@ -141,7 +153,7 @@ interface RepositoryInterface * @param array $fields * @return int */ - public function updateWhereIn($column, array $values, array $fields); + public function updateWhereIn(string $column, array $values, array $fields): int; /** * Update a record if it exists in the database, otherwise create it. @@ -154,23 +166,14 @@ interface RepositoryInterface * * @throws \Pterodactyl\Exceptions\Model\DataValidationException */ - public function updateOrCreate(array $where, array $fields, $validate = true, $force = false); + public function updateOrCreate(array $where, array $fields, bool $validate = true, bool $force = false); /** - * Update multiple records matching the passed clauses. + * Return all records associated with the given model. * - * @param array $where - * @param array $fields - * @return mixed + * @return Collection */ - public function massUpdate(array $where, array $fields); - - /** - * Return all records from the model. - * - * @return mixed - */ - public function all(); + public function all(): Collection; /** * Insert a single or multiple records into the database at once skipping @@ -179,7 +182,7 @@ interface RepositoryInterface * @param array $data * @return bool */ - public function insert(array $data); + public function insert(array $data): bool; /** * Insert multiple records into the database and ignore duplicates. @@ -187,5 +190,5 @@ interface RepositoryInterface * @param array $values * @return bool */ - public function insertIgnore(array $values); + public function insertIgnore(array $values): bool; } diff --git a/app/Contracts/Repository/ScheduleRepositoryInterface.php b/app/Contracts/Repository/ScheduleRepositoryInterface.php index 7e28b016f..32650bdcf 100644 --- a/app/Contracts/Repository/ScheduleRepositoryInterface.php +++ b/app/Contracts/Repository/ScheduleRepositoryInterface.php @@ -1,11 +1,4 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; @@ -38,5 +31,5 @@ interface ScheduleRepositoryInterface extends RepositoryInterface * @param string $timestamp * @return \Illuminate\Support\Collection */ - public function getSchedulesToProcess($timestamp); + public function getSchedulesToProcess(string $timestamp): Collection; } diff --git a/app/Contracts/Repository/ServerRepositoryInterface.php b/app/Contracts/Repository/ServerRepositoryInterface.php index 2fb8349e3..6d1c14e78 100644 --- a/app/Contracts/Repository/ServerRepositoryInterface.php +++ b/app/Contracts/Repository/ServerRepositoryInterface.php @@ -1,15 +1,11 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; +use Pterodactyl\Models\User; use Pterodactyl\Models\Server; +use Illuminate\Support\Collection; +use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Pterodactyl\Contracts\Repository\Attributes\SearchableInterface; interface ServerRepositoryInterface extends RepositoryInterface, SearchableInterface @@ -17,19 +13,10 @@ interface ServerRepositoryInterface extends RepositoryInterface, SearchableInter /** * Returns a listing of all servers that exist including relationships. * - * @param int|null $paginate - * @return mixed + * @param int $paginate + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ - public function getAllServers($paginate); - - /** - * Return a collection of servers with their associated data for rebuild operations. - * - * @param int|null $server - * @param int|null $node - * @return \Illuminate\Database\Eloquent\Collection - */ - public function getDataForRebuild($server = null, $node = null); + public function getAllServers(int $paginate): LengthAwarePaginator; /** * Load the egg relations onto the server model. @@ -40,15 +27,35 @@ interface ServerRepositoryInterface extends RepositoryInterface, SearchableInter */ public function loadEggRelations(Server $server, bool $refresh = false): Server; + /** + * Return a collection of servers with their associated data for rebuild operations. + * + * @param int|null $server + * @param int|null $node + * @return \Illuminate\Support\Collection + */ + public function getDataForRebuild(int $server = null, int $node = null): Collection; + /** * Return a server model and all variables associated with the server. * * @param int $id - * @return mixed + * @return \Pterodactyl\Models\Server * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function findWithVariables($id); + public function findWithVariables(int $id): Server; + + /** + * Get the primary allocation for a given server. If a model is passed into + * the function, load the allocation relationship onto it. Otherwise, find and + * return the server from the database. + * + * @param \Pterodactyl\Models\Server $server + * @param bool $refresh + * @return \Pterodactyl\Models\Server + */ + public function getPrimaryAllocation(Server $server, bool $refresh = false): Server; /** * Return all of the server variables possible and default to the variable @@ -60,20 +67,7 @@ interface ServerRepositoryInterface extends RepositoryInterface, SearchableInter * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getVariablesWithValues($id, $returnAsObject = false); - - /** - * Get the primary allocation for a given server. If a model is passed into - * the function, load the allocation relationship onto it. Otherwise, find and - * return the server from the database. - * - * @param int|\Pterodactyl\Models\Server $server - * @param bool $refresh - * @return \Pterodactyl\Models\Server - * - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException - */ - public function getPrimaryAllocation($server, bool $refresh = false): Server; + public function getVariablesWithValues(int $id, bool $returnAsObject = false); /** * Return enough data to be used for the creation of a server via the daemon. @@ -85,14 +79,13 @@ interface ServerRepositoryInterface extends RepositoryInterface, SearchableInter public function getDataForCreation(Server $server, bool $refresh = false): Server; /** - * Return a server as well as associated databases and their hosts. + * Load associated databases onto the server model. * - * @param int $id - * @return mixed - * - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException + * @param \Pterodactyl\Models\Server $server + * @param bool $refresh + * @return \Pterodactyl\Models\Server */ - public function getWithDatabases($id); + public function loadDatabaseRelations(Server $server, bool $refresh = false): Server; /** * Get data for use when updating a server on the Daemon. Returns an array of @@ -105,24 +98,14 @@ interface ServerRepositoryInterface extends RepositoryInterface, SearchableInter */ public function getDaemonServiceData(Server $server, bool $refresh = false): array; - /** - * Return an array of server IDs that a given user can access based on owner and subuser permissions. - * - * @param int $user - * @return array - */ - public function getUserAccessServers($user); - /** * Return a paginated list of servers that a user can access at a given level. * - * @param int $user - * @param string $level - * @param bool $admin - * @param array $relations + * @param \Pterodactyl\Models\User $user + * @param int $level * @return \Illuminate\Pagination\LengthAwarePaginator */ - public function filterUserAccessServers($user, $admin = false, $level = 'all', array $relations = []); + public function filterUserAccessServers(User $user, int $level): LengthAwarePaginator; /** * Return a server by UUID. @@ -132,5 +115,5 @@ interface ServerRepositoryInterface extends RepositoryInterface, SearchableInter * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getByUuid($uuid); + public function getByUuid(string $uuid): Server; } diff --git a/app/Contracts/Repository/ServerVariableRepositoryInterface.php b/app/Contracts/Repository/ServerVariableRepositoryInterface.php index a04f30e01..dc3e241a9 100644 --- a/app/Contracts/Repository/ServerVariableRepositoryInterface.php +++ b/app/Contracts/Repository/ServerVariableRepositoryInterface.php @@ -1,11 +1,4 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; diff --git a/app/Contracts/Repository/SessionRepositoryInterface.php b/app/Contracts/Repository/SessionRepositoryInterface.php index b95bad44e..1f2dd73e8 100644 --- a/app/Contracts/Repository/SessionRepositoryInterface.php +++ b/app/Contracts/Repository/SessionRepositoryInterface.php @@ -1,16 +1,19 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; +use Illuminate\Support\Collection; + interface SessionRepositoryInterface extends RepositoryInterface { + /** + * Return all of the active sessions for a user. + * + * @param int $user + * @return \Illuminate\Support\Collection + */ + public function getUserSessions(int $user): Collection; + /** * Delete a session for a given user. * @@ -18,13 +21,5 @@ interface SessionRepositoryInterface extends RepositoryInterface * @param int $session * @return null|int */ - public function deleteUserSession($user, $session); - - /** - * Return all of the active sessions for a user. - * - * @param int $user - * @return \Illuminate\Support\Collection - */ - public function getUserSessions($user); + public function deleteUserSession(int $user, int $session); } diff --git a/app/Contracts/Repository/SettingsRepositoryInterface.php b/app/Contracts/Repository/SettingsRepositoryInterface.php index dbf87f744..9128e7f78 100644 --- a/app/Contracts/Repository/SettingsRepositoryInterface.php +++ b/app/Contracts/Repository/SettingsRepositoryInterface.php @@ -9,7 +9,9 @@ interface SettingsRepositoryInterface extends RepositoryInterface * * @param string $key * @param string $value - * @return mixed + * + * @throws \Pterodactyl\Exceptions\Model\DataValidationException + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ public function set(string $key, string $value); @@ -26,7 +28,6 @@ interface SettingsRepositoryInterface extends RepositoryInterface * Remove a key from the database cache. * * @param string $key - * @return mixed */ public function forget(string $key); } diff --git a/app/Contracts/Repository/SubuserRepositoryInterface.php b/app/Contracts/Repository/SubuserRepositoryInterface.php index 06a9efc38..2d722119a 100644 --- a/app/Contracts/Repository/SubuserRepositoryInterface.php +++ b/app/Contracts/Repository/SubuserRepositoryInterface.php @@ -34,25 +34,4 @@ interface SubuserRepositoryInterface extends RepositoryInterface * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ public function getWithPermissionsUsingUserAndServer(int $user, int $server): Subuser; - - /** - * Find a subuser and return with server and permissions relationships. - * - * @param int $id - * @return \Illuminate\Database\Eloquent\Collection - * - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException - */ - public function getWithServerAndPermissions($id); - - /** - * Return a subuser and their associated connection key for a server. - * - * @param int $user - * @param int $server - * @return \Pterodactyl\Models\Subuser - * - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException - */ - public function getWithKey($user, $server); } diff --git a/app/Contracts/Repository/TaskRepositoryInterface.php b/app/Contracts/Repository/TaskRepositoryInterface.php index 4f400adee..80ca277bb 100644 --- a/app/Contracts/Repository/TaskRepositoryInterface.php +++ b/app/Contracts/Repository/TaskRepositoryInterface.php @@ -1,14 +1,9 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; +use Pterodactyl\Models\Task; + interface TaskRepositoryInterface extends RepositoryInterface { /** @@ -19,14 +14,14 @@ interface TaskRepositoryInterface extends RepositoryInterface * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getTaskWithServer($id); + public function getTaskWithServer(int $id): Task; /** * Returns the next task in a schedule. * - * @param int $schedule the ID of the schedule to select the next task from - * @param int $index the index of the current task + * @param int $schedule + * @param int $index * @return null|\Pterodactyl\Models\Task */ - public function getNextTask($schedule, $index); + public function getNextTask(int $schedule, int $index); } diff --git a/app/Contracts/Repository/UserRepositoryInterface.php b/app/Contracts/Repository/UserRepositoryInterface.php index fac353ed4..b5003e0b2 100644 --- a/app/Contracts/Repository/UserRepositoryInterface.php +++ b/app/Contracts/Repository/UserRepositoryInterface.php @@ -1,14 +1,9 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository; +use Illuminate\Support\Collection; +use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Pterodactyl\Contracts\Repository\Attributes\SearchableInterface; interface UserRepositoryInterface extends RepositoryInterface, SearchableInterface @@ -18,13 +13,13 @@ interface UserRepositoryInterface extends RepositoryInterface, SearchableInterfa * * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ - public function getAllUsersWithCounts(); + public function getAllUsersWithCounts(): LengthAwarePaginator; /** * Return all matching models for a user in a format that can be used for dropdowns. * * @param string $query - * @return \Illuminate\Database\Eloquent\Collection + * @return \Illuminate\Support\Collection */ - public function filterUsersByQuery($query); + public function filterUsersByQuery(string $query): Collection; } diff --git a/app/Http/Controllers/Admin/DatabaseController.php b/app/Http/Controllers/Admin/DatabaseController.php index 02271d699..dbf2766a1 100644 --- a/app/Http/Controllers/Admin/DatabaseController.php +++ b/app/Http/Controllers/Admin/DatabaseController.php @@ -139,7 +139,6 @@ class DatabaseController extends Controller * @param int $host * @return \Illuminate\Http\RedirectResponse * - * @throws \Pterodactyl\Exceptions\DisplayException * @throws \Pterodactyl\Exceptions\Model\DataValidationException * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ diff --git a/app/Http/Controllers/Admin/NodesController.php b/app/Http/Controllers/Admin/NodesController.php index d68a47556..a2b80b4f9 100644 --- a/app/Http/Controllers/Admin/NodesController.php +++ b/app/Http/Controllers/Admin/NodesController.php @@ -126,7 +126,7 @@ class NodesController extends Controller public function index(Request $request) { return view('admin.nodes.index', [ - 'nodes' => $this->repository->search($request->input('query'))->getNodeListingData(), + 'nodes' => $this->repository->setSearchTerm($request->input('query'))->getNodeListingData(), ]); } @@ -166,15 +166,15 @@ class NodesController extends Controller /** * Shows the index overview page for a specific node. * - * @param int $node + * @param \Pterodactyl\Models\Node $node * @return \Illuminate\View\View * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function viewIndex($node) + public function viewIndex(Node $node) { return view('admin.nodes.view.index', [ - 'node' => $this->repository->getSingleNode($node), + 'node' => $this->repository->loadLocationAndServerCount($node), 'stats' => $this->repository->getUsageStats($node), 'version' => $this->versionService, ]); @@ -208,14 +208,14 @@ class NodesController extends Controller /** * Shows the allocation page for a specific node. * - * @param int $node + * @param \Pterodactyl\Models\Node $node * @return \Illuminate\View\View * * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function viewAllocation($node) + public function viewAllocation(Node $node) { - $node = $this->repository->getNodeAllocations($node); + $this->repository->loadNodeAllocations($node); Javascript::put(['node' => collect($node)->only(['id'])]); return view('admin.nodes.view.allocation', ['node' => $node]); diff --git a/app/Http/Controllers/Admin/PackController.php b/app/Http/Controllers/Admin/PackController.php index fed86f3a0..1dd7c881c 100644 --- a/app/Http/Controllers/Admin/PackController.php +++ b/app/Http/Controllers/Admin/PackController.php @@ -114,9 +114,7 @@ class PackController extends Controller public function index(Request $request) { return view('admin.packs.index', [ - 'packs' => $this->repository->search($request->input('query'))->paginateWithEggAndServerCount( - $this->config->get('pterodactyl.paginate.admin.packs') - ), + 'packs' => $this->repository->setSearchTerm($request->input('query'))->paginateWithEggAndServerCount(), ]); } @@ -177,14 +175,14 @@ class PackController extends Controller /** * Display pack view template to user. * - * @param int $pack + * @param \Pterodactyl\Models\Pack $pack * @return \Illuminate\View\View * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function view($pack) + public function view(Pack $pack) { return view('admin.packs.view', [ - 'pack' => $this->repository->getWithServers($pack), + 'pack' => $this->repository->loadServerData($pack), 'nests' => $this->serviceRepository->getWithEggs(), ]); } diff --git a/app/Http/Controllers/Admin/ServersController.php b/app/Http/Controllers/Admin/ServersController.php index 427bb7d20..fb393e65c 100644 --- a/app/Http/Controllers/Admin/ServersController.php +++ b/app/Http/Controllers/Admin/ServersController.php @@ -352,14 +352,12 @@ class ServersController extends Controller /** * Display the database management page for a specific server. * - * @param int $server + * @param \Pterodactyl\Models\Server $server * @return \Illuminate\View\View - * - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function viewDatabase($server) + public function viewDatabase(Server $server) { - $server = $this->repository->getWithDatabases($server); + $this->repository->loadDatabaseRelations($server); return view('admin.servers.view.database', [ 'hosts' => $this->databaseHostRepository->all(), diff --git a/app/Http/Controllers/Admin/UserController.php b/app/Http/Controllers/Admin/UserController.php index faa535b6a..5656ae124 100644 --- a/app/Http/Controllers/Admin/UserController.php +++ b/app/Http/Controllers/Admin/UserController.php @@ -83,7 +83,7 @@ class UserController extends Controller */ public function index(Request $request) { - $users = $this->repository->search($request->input('query'))->getAllUsersWithCounts(); + $users = $this->repository->setSearchTerm($request->input('query'))->getAllUsersWithCounts(); return view('admin.users.index', ['users' => $users]); } diff --git a/app/Http/Controllers/Base/IndexController.php b/app/Http/Controllers/Base/IndexController.php index 8e16f8605..7c2cc2f1c 100644 --- a/app/Http/Controllers/Base/IndexController.php +++ b/app/Http/Controllers/Base/IndexController.php @@ -1,31 +1,9 @@ - * Some Modifications (c) 2015 Dylan Seidt . - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ namespace Pterodactyl\Http\Controllers\Base; use Illuminate\Http\Request; +use Pterodactyl\Models\User; use GuzzleHttp\Exception\RequestException; use Pterodactyl\Http\Controllers\Controller; use Symfony\Component\HttpKernel\Exception\HttpException; @@ -75,8 +53,8 @@ class IndexController extends Controller */ public function getIndex(Request $request) { - $servers = $this->repository->search($request->input('query'))->filterUserAccessServers( - $request->user()->id, $request->user()->root_admin, 'all', ['user'] + $servers = $this->repository->setSearchTerm($request->input('query'))->filterUserAccessServers( + $request->user(), User::FILTER_LEVEL_ALL ); return view('base.index', ['servers' => $servers]); diff --git a/app/Http/Middleware/DaemonAuthenticate.php b/app/Http/Middleware/DaemonAuthenticate.php index 6bd2908cf..b8e83bf8c 100644 --- a/app/Http/Middleware/DaemonAuthenticate.php +++ b/app/Http/Middleware/DaemonAuthenticate.php @@ -34,6 +34,7 @@ class DaemonAuthenticate * Create a new filter instance. * * @param \Pterodactyl\Contracts\Repository\NodeRepositoryInterface $repository + * @deprecated */ public function __construct(NodeRepositoryInterface $repository) { @@ -47,6 +48,7 @@ class DaemonAuthenticate * @param \Closure $next * @return mixed * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException */ public function handle(Request $request, Closure $next) @@ -59,7 +61,7 @@ class DaemonAuthenticate throw new AccessDeniedHttpException; } - $node = $this->repository->findWhere(['daemonSecret' => $request->header('X-Access-Node')]); + $node = $this->repository->findFirstWhere(['daemonSecret' => $request->header('X-Access-Node')]); $request->attributes->set('node', $node); return $next($request); diff --git a/app/Models/User.php b/app/Models/User.php index 4452f0c33..af574b597 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -28,6 +28,11 @@ class User extends Model implements const USER_LEVEL_USER = 0; const USER_LEVEL_ADMIN = 1; + const FILTER_LEVEL_ALL = 0; + const FILTER_LEVEL_OWNER = 1; + const FILTER_LEVEL_ADMIN = 2; + const FILTER_LEVEL_SUBUSER = 3; + /** * Level of servers to display when using access() on a user. * diff --git a/app/Policies/APIKeyPolicy.php b/app/Policies/APIKeyPolicy.php index 69ce45c04..e8556ca9c 100644 --- a/app/Policies/APIKeyPolicy.php +++ b/app/Policies/APIKeyPolicy.php @@ -39,7 +39,7 @@ class APIKeyPolicy })->values(); }); - return $permissions->search($permission, true) !== false; + return $permissions->setSearchTerm($permission, true) !== false; } /** diff --git a/app/Policies/ServerPolicy.php b/app/Policies/ServerPolicy.php index 9b4db6f05..8891fa87f 100644 --- a/app/Policies/ServerPolicy.php +++ b/app/Policies/ServerPolicy.php @@ -32,7 +32,7 @@ class ServerPolicy })->values(); }); - return $permissions->search($permission, true) !== false; + return $permissions->setSearchTerm($permission, true) !== false; } /** diff --git a/app/Repositories/Concerns/Searchable.php b/app/Repositories/Concerns/Searchable.php index 0d396cdc4..26ed6544a 100644 --- a/app/Repositories/Concerns/Searchable.php +++ b/app/Repositories/Concerns/Searchable.php @@ -1,30 +1,36 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Concerns; trait Searchable { /** - * The term to search. + * The search term to use when filtering results. * - * @var bool|string + * @var null|string */ - protected $searchTerm = false; + protected $searchTerm; /** - * Perform a search of the model using the given term. + * Set the search term. * - * @param string $term + * @param string|null $term * @return $this + * @deprecated */ public function search($term) + { + return $this->setSearchTerm($term); + } + + /** + * Set the search term to use when requesting all records from + * the model. + * + * @param string|null $term + * @return $this + */ + public function setSearchTerm(string $term = null) { if (empty($term)) { return $this; @@ -35,4 +41,24 @@ trait Searchable return $clone; } + + /** + * Determine if a valid search term is set on this repository. + * + * @return bool + */ + public function hasSearchTerm(): bool + { + return ! empty($this->searchTerm); + } + + /** + * Return the search term. + * + * @return string|null + */ + public function getSearchTerm() + { + return $this->searchTerm; + } } diff --git a/app/Repositories/Daemon/ServerRepository.php b/app/Repositories/Daemon/ServerRepository.php index f21ec197a..d46749e5d 100644 --- a/app/Repositories/Daemon/ServerRepository.php +++ b/app/Repositories/Daemon/ServerRepository.php @@ -1,11 +1,4 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Daemon; diff --git a/app/Repositories/Eloquent/AllocationRepository.php b/app/Repositories/Eloquent/AllocationRepository.php index f613f734f..674d8b8fd 100644 --- a/app/Repositories/Eloquent/AllocationRepository.php +++ b/app/Repositories/Eloquent/AllocationRepository.php @@ -1,21 +1,17 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; +use Illuminate\Support\Collection; use Pterodactyl\Models\Allocation; use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface; class AllocationRepository extends EloquentRepository implements AllocationRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -23,18 +19,25 @@ class AllocationRepository extends EloquentRepository implements AllocationRepos } /** - * {@inheritdoc} + * Set an array of allocation IDs to be assigned to a specific server. + * + * @param int|null $server + * @param array $ids + * @return int */ - public function assignAllocationsToServer($server, array $ids) + public function assignAllocationsToServer(int $server = null, array $ids): int { return $this->getBuilder()->whereIn('id', $ids)->update(['server_id' => $server]); } /** - * {@inheritdoc} + * Return all of the allocations for a specific node. + * + * @param int $node + * @return \Illuminate\Support\Collection */ - public function getAllocationsForNode($node) + public function getAllocationsForNode(int $node): Collection { - return $this->getBuilder()->where('node_id', $node)->get(); + return $this->getBuilder()->where('node_id', $node)->get($this->getColumns()); } } diff --git a/app/Repositories/Eloquent/ApiKeyRepository.php b/app/Repositories/Eloquent/ApiKeyRepository.php index 107e0b6c9..f6169c939 100644 --- a/app/Repositories/Eloquent/ApiKeyRepository.php +++ b/app/Repositories/Eloquent/ApiKeyRepository.php @@ -1,11 +1,4 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; @@ -15,7 +8,9 @@ use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface; class ApiKeyRepository extends EloquentRepository implements ApiKeyRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { diff --git a/app/Repositories/Eloquent/ApiPermissionRepository.php b/app/Repositories/Eloquent/ApiPermissionRepository.php index b88fdfd1c..d94771327 100644 --- a/app/Repositories/Eloquent/ApiPermissionRepository.php +++ b/app/Repositories/Eloquent/ApiPermissionRepository.php @@ -1,11 +1,4 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; @@ -15,7 +8,9 @@ use Pterodactyl\Contracts\Repository\ApiPermissionRepositoryInterface; class ApiPermissionRepository extends EloquentRepository implements ApiPermissionRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { diff --git a/app/Repositories/Eloquent/DaemonKeyRepository.php b/app/Repositories/Eloquent/DaemonKeyRepository.php index 97fe0c2bb..ba246f458 100644 --- a/app/Repositories/Eloquent/DaemonKeyRepository.php +++ b/app/Repositories/Eloquent/DaemonKeyRepository.php @@ -1,26 +1,4 @@ . - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ namespace Pterodactyl\Repositories\Eloquent; @@ -28,13 +6,16 @@ use Pterodactyl\Models\User; use Webmozart\Assert\Assert; use Pterodactyl\Models\DaemonKey; use Illuminate\Support\Collection; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Pterodactyl\Exceptions\Repository\RecordNotFoundException; use Pterodactyl\Contracts\Repository\DaemonKeyRepositoryInterface; class DaemonKeyRepository extends EloquentRepository implements DaemonKeyRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -62,28 +43,22 @@ class DaemonKeyRepository extends EloquentRepository implements DaemonKeyReposit } /** - * {@inheritdoc} + * Return a daemon key with the associated server relation attached. + * + * @param string $key + * @return \Pterodactyl\Models\DaemonKey + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getServerKeys($server) + public function getKeyWithServer(string $key): DaemonKey { - Assert::integerish($server, 'First argument passed to getServerKeys must be integer, received %s.'); + Assert::notEmpty($key, 'Expected non-empty string as first argument passed to ' . __METHOD__); - return $this->getBuilder()->where('server_id', $server)->get($this->getColumns()); - } - - /** - * {@inheritdoc} - */ - public function getKeyWithServer($key) - { - Assert::stringNotEmpty($key, 'First argument passed to getServerByKey must be string, received %s.'); - - $instance = $this->getBuilder()->with('server')->where('secret', '=', $key)->first(); - if (is_null($instance)) { + try { + return $this->getBuilder()->with('server')->where('secret', '=', $key)->firstOrFail($this->getColumns()); + } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } - - return $instance; } /** diff --git a/app/Repositories/Eloquent/DatabaseHostRepository.php b/app/Repositories/Eloquent/DatabaseHostRepository.php index 1bfe8d75b..6bfb94d70 100644 --- a/app/Repositories/Eloquent/DatabaseHostRepository.php +++ b/app/Repositories/Eloquent/DatabaseHostRepository.php @@ -1,23 +1,19 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; -use Webmozart\Assert\Assert; +use Illuminate\Support\Collection; use Pterodactyl\Models\DatabaseHost; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Pterodactyl\Exceptions\Repository\RecordNotFoundException; use Pterodactyl\Contracts\Repository\DatabaseHostRepositoryInterface; class DatabaseHostRepository extends EloquentRepository implements DatabaseHostRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -25,25 +21,31 @@ class DatabaseHostRepository extends EloquentRepository implements DatabaseHostR } /** - * {@inheritdoc} + * Return database hosts with a count of databases and the node + * information for which it is attached. + * + * @return \Illuminate\Support\Collection */ - public function getWithViewDetails() + public function getWithViewDetails(): Collection { return $this->getBuilder()->withCount('databases')->with('node')->get(); } /** - * {@inheritdoc} + * Return a database host with the databases and associated servers + * that are attached to said databases. + * + * @param int $id + * @return \Pterodactyl\Models\DatabaseHost + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getWithServers($id) + public function getWithServers(int $id): DatabaseHost { - Assert::numeric($id, 'First argument passed to getWithServers must be numeric, recieved %s.'); - - $instance = $this->getBuilder()->with('databases.server')->find($id, $this->getColumns()); - if (! $instance) { - throw new RecordNotFoundException(); + try { + return $this->getBuilder()->with('databases.server')->findOrFail($id, $this->getColumns()); + } catch (ModelNotFoundException $exception) { + throw new RecordNotFoundException; } - - return $instance; } } diff --git a/app/Repositories/Eloquent/DatabaseRepository.php b/app/Repositories/Eloquent/DatabaseRepository.php index f030812b5..d24dd177e 100644 --- a/app/Repositories/Eloquent/DatabaseRepository.php +++ b/app/Repositories/Eloquent/DatabaseRepository.php @@ -1,11 +1,4 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; @@ -34,17 +27,17 @@ class DatabaseRepository extends EloquentRepository implements DatabaseRepositor * @param \Illuminate\Foundation\Application $application * @param \Illuminate\Database\DatabaseManager $database */ - public function __construct( - Application $application, - DatabaseManager $database - ) { + public function __construct(Application $application, DatabaseManager $database) + { parent::__construct($application); $this->database = $database; } /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -86,18 +79,24 @@ class DatabaseRepository extends EloquentRepository implements DatabaseRepositor } /** - * {@inheritdoc} - * @return bool|\Illuminate\Database\Eloquent\Model + * Create a new database if it does not already exist on the host with + * the provided details. + * + * @param array $data + * @return \Pterodactyl\Models\Database + * + * @throws \Pterodactyl\Exceptions\Model\DataValidationException + * @throws \Pterodactyl\Exceptions\Repository\DuplicateDatabaseNameException */ - public function createIfNotExists(array $data) + public function createIfNotExists(array $data): Database { - $instance = $this->getBuilder()->where([ + $count = $this->getBuilder()->where([ ['server_id', '=', array_get($data, 'server_id')], ['database_host_id', '=', array_get($data, 'database_host_id')], ['database', '=', array_get($data, 'database')], ])->count(); - if ($instance > 0) { + if ($count > 0) { throw new DuplicateDatabaseNameException('A database with those details already exists for the specified server.'); } @@ -105,27 +104,40 @@ class DatabaseRepository extends EloquentRepository implements DatabaseRepositor } /** - * {@inheritdoc} + * Create a new database on a given connection. + * + * @param string $database + * @return bool */ - public function createDatabase($database) + public function createDatabase(string $database): bool { - return $this->runStatement(sprintf('CREATE DATABASE IF NOT EXISTS `%s`', $database)); + return $this->run(sprintf('CREATE DATABASE IF NOT EXISTS `%s`', $database)); } /** - * {@inheritdoc} + * Create a new database user on a given connection. + * + * @param string $username + * @param string $remote + * @param string $password + * @return bool */ - public function createUser($username, $remote, $password) + public function createUser(string $username, string $remote, string $password): bool { - return $this->runStatement(sprintf('CREATE USER `%s`@`%s` IDENTIFIED BY \'%s\'', $username, $remote, $password)); + return $this->run(sprintf('CREATE USER `%s`@`%s` IDENTIFIED BY \'%s\'', $username, $remote, $password)); } /** - * {@inheritdoc} + * Give a specific user access to a given database. + * + * @param string $database + * @param string $username + * @param string $remote + * @return bool */ - public function assignUserToDatabase($database, $username, $remote) + public function assignUserToDatabase(string $database, string $username, string $remote): bool { - return $this->runStatement(sprintf( + return $this->run(sprintf( 'GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX, EXECUTE ON `%s`.* TO `%s`@`%s`', $database, $username, @@ -134,27 +146,36 @@ class DatabaseRepository extends EloquentRepository implements DatabaseRepositor } /** - * {@inheritdoc} + * Flush the privileges for a given connection. + * + * @return bool */ - public function flush() + public function flush(): bool { - return $this->runStatement('FLUSH PRIVILEGES'); + return $this->run('FLUSH PRIVILEGES'); } /** - * {@inheritdoc} + * Drop a given database on a specific connection. + * + * @param string $database + * @return bool */ - public function dropDatabase($database) + public function dropDatabase(string $database): bool { - return $this->runStatement(sprintf('DROP DATABASE IF EXISTS `%s`', $database)); + return $this->run(sprintf('DROP DATABASE IF EXISTS `%s`', $database)); } /** - * {@inheritdoc} + * Drop a given user on a specific connection. + * + * @param string $username + * @param string $remote + * @return mixed */ - public function dropUser($username, $remote) + public function dropUser(string $username, string $remote): bool { - return $this->runStatement(sprintf('DROP USER IF EXISTS `%s`@`%s`', $username, $remote)); + return $this->run(sprintf('DROP USER IF EXISTS `%s`@`%s`', $username, $remote)); } /** @@ -163,7 +184,7 @@ class DatabaseRepository extends EloquentRepository implements DatabaseRepositor * @param string $statement * @return bool */ - protected function runStatement($statement) + private function run(string $statement): bool { return $this->database->connection($this->getConnection())->statement($statement); } diff --git a/app/Repositories/Eloquent/EggRepository.php b/app/Repositories/Eloquent/EggRepository.php index c1fcc583f..bfb6738d9 100644 --- a/app/Repositories/Eloquent/EggRepository.php +++ b/app/Repositories/Eloquent/EggRepository.php @@ -1,24 +1,20 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; use Pterodactyl\Models\Egg; use Webmozart\Assert\Assert; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Pterodactyl\Contracts\Repository\EggRepositoryInterface; use Pterodactyl\Exceptions\Repository\RecordNotFoundException; class EggRepository extends EloquentRepository implements EggRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -35,13 +31,11 @@ class EggRepository extends EloquentRepository implements EggRepositoryInterface */ public function getWithVariables(int $id): Egg { - /** @var \Pterodactyl\Models\Egg $instance */ - $instance = $this->getBuilder()->with('variables')->find($id, $this->getColumns()); - if (! $instance) { + try { + return $this->getBuilder()->with('variables')->firstOrFail($id, $this->getColumns()); + } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } - - return $instance; } /** @@ -67,13 +61,11 @@ class EggRepository extends EloquentRepository implements EggRepositoryInterface { Assert::true((is_digit($value) || is_string($value)), 'First argument passed to getWithCopyAttributes must be an integer or string, received %s.'); - /** @var \Pterodactyl\Models\Egg $instance */ - $instance = $this->getBuilder()->with('scriptFrom', 'configFrom')->where($column, '=', $value)->first($this->getColumns()); - if (! $instance) { + try { + return $this->getBuilder()->with('scriptFrom', 'configFrom')->where($column, '=', $value)->firstOrFail($this->getColumns()); + } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } - - return $instance; } /** @@ -86,13 +78,11 @@ class EggRepository extends EloquentRepository implements EggRepositoryInterface */ public function getWithExportAttributes(int $id): Egg { - /** @var \Pterodactyl\Models\Egg $instance */ - $instance = $this->getBuilder()->with('scriptFrom', 'configFrom', 'variables')->find($id, $this->getColumns()); - if (! $instance) { + try { + return $this->getBuilder()->with('scriptFrom', 'configFrom', 'variables')->find($id, $this->getColumns()); + } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } - - return $instance; } /** diff --git a/app/Repositories/Eloquent/EggVariableRepository.php b/app/Repositories/Eloquent/EggVariableRepository.php index 2c34c7527..9d84b9db1 100644 --- a/app/Repositories/Eloquent/EggVariableRepository.php +++ b/app/Repositories/Eloquent/EggVariableRepository.php @@ -1,11 +1,4 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; @@ -16,7 +9,9 @@ use Pterodactyl\Contracts\Repository\EggVariableRepositoryInterface; class EggVariableRepository extends EloquentRepository implements EggVariableRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { diff --git a/app/Repositories/Eloquent/EloquentRepository.php b/app/Repositories/Eloquent/EloquentRepository.php index d94cd5cac..417b547ce 100644 --- a/app/Repositories/Eloquent/EloquentRepository.php +++ b/app/Repositories/Eloquent/EloquentRepository.php @@ -1,17 +1,12 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; use Webmozart\Assert\Assert; +use Illuminate\Support\Collection; use Pterodactyl\Repositories\Repository; use Illuminate\Database\Query\Expression; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Pterodactyl\Contracts\Repository\RepositoryInterface; use Pterodactyl\Exceptions\Model\DataValidationException; use Pterodactyl\Exceptions\Repository\RecordNotFoundException; @@ -20,7 +15,19 @@ use Pterodactyl\Contracts\Repository\Attributes\SearchableInterface; abstract class EloquentRepository extends Repository implements RepositoryInterface { /** - * {@inheritdoc} + * Return an instance of the eloquent model bound to this + * repository instance. + * + * @return \Illuminate\Database\Eloquent\Model + */ + public function getModel() + { + return $this->model; + } + + /** + * Return an instance of the builder to use for this repository. + * * @return \Illuminate\Database\Eloquent\Builder */ public function getBuilder() @@ -29,22 +36,19 @@ abstract class EloquentRepository extends Repository implements RepositoryInterf } /** - * {@inheritdoc} - * @param bool $force + * Create a new record in the database and return the associated model. + * + * @param array $fields + * @param bool $validate + * @param bool $force * @return \Illuminate\Database\Eloquent\Model|bool + * + * @throws \Pterodactyl\Exceptions\Model\DataValidationException */ - public function create(array $fields, $validate = true, $force = false) + public function create(array $fields, bool $validate = true, bool $force = false) { - Assert::boolean($validate, 'Second argument passed to create must be boolean, recieved %s.'); - Assert::boolean($force, 'Third argument passed to create must be boolean, received %s.'); - $instance = $this->getBuilder()->newModelInstance(); - - if ($force) { - $instance->forceFill($fields); - } else { - $instance->fill($fields); - } + ($force) ? $instance->forceFill($fields) : $instance->fill($fields); if (! $validate) { $saved = $instance->skipValidation()->save(); @@ -58,99 +62,108 @@ abstract class EloquentRepository extends Repository implements RepositoryInterf } /** - * {@inheritdoc} - * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model + * Find a model that has the specific ID passed. + * + * @param int $id + * @return \Illuminate\Database\Eloquent\Model + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function find($id) + public function find(int $id) { - Assert::numeric($id, 'First argument passed to find must be numeric, received %s.'); - - $instance = $this->getBuilder()->find($id, $this->getColumns()); - - if (! $instance) { - throw new RecordNotFoundException(); + try { + return $this->getBuilder()->findOrFail($id, $this->getColumns()); + } catch (ModelNotFoundException $exception) { + throw new RecordNotFoundException; } - - return $instance; } /** - * {@inheritdoc} - * @return \Illuminate\Database\Eloquent\Collection + * Find a model matching an array of where clauses. + * + * @param array $fields + * @return \Illuminate\Support\Collection */ - public function findWhere(array $fields) + public function findWhere(array $fields): Collection { return $this->getBuilder()->where($fields)->get($this->getColumns()); } /** - * {@inheritdoc} + * Find and return the first matching instance for the given fields. + * + * @param array $fields * @return \Illuminate\Database\Eloquent\Model + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ public function findFirstWhere(array $fields) { - $instance = $this->getBuilder()->where($fields)->first($this->getColumns()); - - if (! $instance) { + try { + return $this->getBuilder()->where($fields)->firstOrFail($this->getColumns()); + } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } - - return $instance; } /** - * {@inheritdoc}. + * Return a count of records matching the passed arguments. + * + * @param array $fields + * @return int */ - public function findCountWhere(array $fields) + public function findCountWhere(array $fields): int { return $this->getBuilder()->where($fields)->count($this->getColumns()); } /** - * {@inheritdoc} + * Delete a given record from the database. + * + * @param int $id + * @param bool $destroy + * @return int */ - public function delete($id, $destroy = false) + public function delete(int $id, bool $destroy = false): int { - Assert::numeric($id, 'First argument passed to delete must be numeric, received %s.'); - Assert::boolean($destroy, 'Second argument passed to delete must be boolean, received %s.'); - - $instance = $this->getBuilder()->where($this->getModel()->getKeyName(), $id); - - return ($destroy) ? $instance->forceDelete() : $instance->delete(); + return $this->deleteWhere(['id' => $id], $destroy); } /** - * {@inheritdoc} + * Delete records matching the given attributes. + * + * @param array $attributes + * @param bool $force + * @return int */ - public function deleteWhere(array $attributes, $force = false) + public function deleteWhere(array $attributes, bool $force = false): int { - Assert::boolean($force, 'Second argument passed to deleteWhere must be boolean, received %s.'); - $instance = $this->getBuilder()->where($attributes); return ($force) ? $instance->forceDelete() : $instance->delete(); } /** - * {@inheritdoc} + * Update a given ID with the passed array of fields. + * + * @param int $id + * @param array $fields + * @param bool $validate + * @param bool $force + * @return \Illuminate\Database\Eloquent\Model|bool + * + * @throws \Pterodactyl\Exceptions\Model\DataValidationException + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function update($id, array $fields, $validate = true, $force = false) + public function update($id, array $fields, bool $validate = true, bool $force = false) { - Assert::numeric($id, 'First argument passed to update must be numeric, received %s.'); - Assert::boolean($validate, 'Third argument passed to update must be boolean, received %s.'); - Assert::boolean($force, 'Fourth argument passed to update must be boolean, received %s.'); - - $instance = $this->getBuilder()->where('id', $id)->first(); - - if (! $instance) { - throw new RecordNotFoundException(); + try { + $instance = $this->getBuilder()->where('id', $id)->firstOrFail(); + } catch (ModelNotFoundException $exception) { + throw new RecordNotFoundException; } - if ($force) { - $instance->forceFill($fields); - } else { - $instance->fill($fields); - } + ($force) ? $instance->forceFill($fields) : $instance->fill($fields); if (! $validate) { $saved = $instance->skipValidation()->save(); @@ -164,40 +177,71 @@ abstract class EloquentRepository extends Repository implements RepositoryInterf } /** - * {@inheritdoc} + * Perform a mass update where matching records are updated using whereIn. + * This does not perform any model data validation. + * + * @param string $column + * @param array $values + * @param array $fields + * @return int */ - public function updateWhereIn($column, array $values, array $fields) + public function updateWhereIn(string $column, array $values, array $fields): int { - Assert::stringNotEmpty($column, 'First argument passed to updateWhereIn must be a non-empty string, received %s.'); + Assert::notEmpty($column, 'First argument passed to updateWhereIn must be a non-empty string.'); return $this->getBuilder()->whereIn($column, $values)->update($fields); } /** - * {@inheritdoc} + * Update a record if it exists in the database, otherwise create it. + * + * @param array $where + * @param array $fields + * @param bool $validate + * @param bool $force + * @return \Illuminate\Database\Eloquent\Model + * + * @throws \Pterodactyl\Exceptions\Model\DataValidationException + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function massUpdate(array $where, array $fields) + public function updateOrCreate(array $where, array $fields, bool $validate = true, bool $force = false) { - // TODO: Implement massUpdate() method. + foreach ($where as $item) { + Assert::true(is_scalar($item) || is_null($item), 'First argument passed to updateOrCreate should be an array of scalar or null values, received an array value of %s.'); + } + + try { + $instance = $this->setColumns('id')->findFirstWhere($where); + } catch (RecordNotFoundException $exception) { + return $this->create(array_merge($where, $fields), $validate, $force); + } + + return $this->update($instance->id, $fields, $validate, $force); } /** - * {@inheritdoc} + * Return all records associated with the given model. + * + * @return \Illuminate\Support\Collection */ - public function all() + public function all(): Collection { $instance = $this->getBuilder(); - if (is_subclass_of(get_called_class(), SearchableInterface::class)) { - $instance = $instance->search($this->searchTerm); + if (is_subclass_of(get_called_class(), SearchableInterface::class) && $this->hasSearchTerm()) { + $instance = $instance->setSearchTerm($this->getSearchTerm()); } return $instance->get($this->getColumns()); } /** - * {@inheritdoc} + * Insert a single or multiple records into the database at once skipping + * validation and mass assignment checking. + * + * @param array $data + * @return bool */ - public function insert(array $data) + public function insert(array $data): bool { return $this->getBuilder()->insert($data); } @@ -208,19 +252,15 @@ abstract class EloquentRepository extends Repository implements RepositoryInterf * @param array $values * @return bool */ - public function insertIgnore(array $values) + public function insertIgnore(array $values): bool { if (empty($values)) { return true; } - if (! is_array(reset($values))) { - $values = [$values]; - } else { - foreach ($values as $key => $value) { - ksort($value); - $values[$key] = $value; - } + foreach ($values as $key => $value) { + ksort($value); + $values[$key] = $value; } $bindings = array_values(array_filter(array_flatten($values, 1), function ($binding) { @@ -239,26 +279,4 @@ abstract class EloquentRepository extends Repository implements RepositoryInterf return $this->getBuilder()->getConnection()->statement($statement, $bindings); } - - /** - * {@inheritdoc} - * @return bool|\Illuminate\Database\Eloquent\Model - */ - public function updateOrCreate(array $where, array $fields, $validate = true, $force = false) - { - Assert::boolean($validate, 'Third argument passed to updateOrCreate must be boolean, received %s.'); - Assert::boolean($force, 'Fourth argument passed to updateOrCreate must be boolean, received %s.'); - - foreach ($where as $item) { - Assert::true(is_scalar($item) || is_null($item), 'First argument passed to updateOrCreate should be an array of scalar or null values, received an array value of %s.'); - } - - $instance = $this->withColumns('id')->findWhere($where)->first(); - - if (! $instance) { - return $this->create(array_merge($where, $fields), $validate, $force); - } - - return $this->update($instance->id, $fields, $validate, $force); - } } diff --git a/app/Repositories/Eloquent/LocationRepository.php b/app/Repositories/Eloquent/LocationRepository.php index b893a0588..47d5e321a 100644 --- a/app/Repositories/Eloquent/LocationRepository.php +++ b/app/Repositories/Eloquent/LocationRepository.php @@ -1,16 +1,11 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; use Pterodactyl\Models\Location; +use Illuminate\Support\Collection; use Pterodactyl\Repositories\Concerns\Searchable; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Pterodactyl\Exceptions\Repository\RecordNotFoundException; use Pterodactyl\Contracts\Repository\LocationRepositoryInterface; @@ -19,7 +14,9 @@ class LocationRepository extends EloquentRepository implements LocationRepositor use Searchable; /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -27,44 +24,56 @@ class LocationRepository extends EloquentRepository implements LocationRepositor } /** - * {@inheritdoc} + * Return locations with a count of nodes and servers attached to it. + * + * @return \Illuminate\Support\Collection */ - public function getAllWithDetails() + public function getAllWithDetails(): Collection { return $this->getBuilder()->withCount('nodes', 'servers')->get($this->getColumns()); } /** - * {@inheritdoc} + * Return all of the available locations with the nodes as a relationship. + * + * @return \Illuminate\Support\Collection */ - public function getAllWithNodes() + public function getAllWithNodes(): Collection { return $this->getBuilder()->with('nodes')->get($this->getColumns()); } /** - * {@inheritdoc} + * Return all of the nodes and their respective count of servers for a location. + * + * @param int $id + * @return mixed + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getWithNodes($id) + public function getWithNodes(int $id): Location { - $instance = $this->getBuilder()->with('nodes.servers')->find($id, $this->getColumns()); - if (! $instance) { + try { + return $this->getBuilder()->with('nodes.servers')->findOrFail($id, $this->getColumns()); + } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } - - return $instance; } /** - * {@inheritdoc} + * Return a location and the count of nodes in that location. + * + * @param int $id + * @return mixed + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getWithNodeCount($id) + public function getWithNodeCount(int $id): Location { - $instance = $this->getBuilder()->withCount('nodes')->find($id, $this->getColumns()); - if (! $instance) { + try { + return $this->getBuilder()->withCount('nodes')->findOrFail($id, $this->getColumns()); + } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } - - return $instance; } } diff --git a/app/Repositories/Eloquent/NestRepository.php b/app/Repositories/Eloquent/NestRepository.php index 923186c26..9c0fcf73c 100644 --- a/app/Repositories/Eloquent/NestRepository.php +++ b/app/Repositories/Eloquent/NestRepository.php @@ -16,7 +16,9 @@ use Pterodactyl\Exceptions\Repository\RecordNotFoundException; class NestRepository extends EloquentRepository implements NestRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { diff --git a/app/Repositories/Eloquent/NodeRepository.php b/app/Repositories/Eloquent/NodeRepository.php index c1dd68a8a..f943441d1 100644 --- a/app/Repositories/Eloquent/NodeRepository.php +++ b/app/Repositories/Eloquent/NodeRepository.php @@ -1,16 +1,12 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; use Pterodactyl\Models\Node; +use Illuminate\Support\Collection; use Pterodactyl\Repositories\Concerns\Searchable; +use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Pterodactyl\Contracts\Repository\NodeRepositoryInterface; use Pterodactyl\Exceptions\Repository\RecordNotFoundException; @@ -18,11 +14,10 @@ class NodeRepository extends EloquentRepository implements NodeRepositoryInterfa { use Searchable; - const THRESHOLD_PERCENTAGE_LOW = 75; - const THRESHOLD_PERCENTAGE_MEDIUM = 90; - /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -30,113 +25,121 @@ class NodeRepository extends EloquentRepository implements NodeRepositoryInterfa } /** - * {@inheritdoc} + * Return the usage stats for a single node. + * + * @param \Pterodactyl\Models\Node $node + * @return array */ - public function getUsageStats($id) + public function getUsageStats(Node $node): array { - $node = $this->getBuilder()->select([ - 'nodes.disk_overallocate', - 'nodes.memory_overallocate', - 'nodes.disk', - 'nodes.memory', - ])->where('id', $id)->first(); - $stats = $this->getBuilder()->select( $this->getBuilder()->raw('IFNULL(SUM(servers.memory), 0) as sum_memory, IFNULL(SUM(servers.disk), 0) as sum_disk') - )->join('servers', 'servers.node_id', '=', 'nodes.id')->where('node_id', $id)->first(); + )->join('servers', 'servers.node_id', '=', 'nodes.id')->where('node_id', $node->id)->first(); - return collect(['disk' => $stats->sum_disk, 'memory' => $stats->sum_memory]) - ->mapWithKeys(function ($value, $key) use ($node) { - $maxUsage = $node->{$key}; - if ($node->{$key . '_overallocate'} > 0) { - $maxUsage = $node->{$key} * (1 + ($node->{$key . '_overallocate'} / 100)); - } + return collect(['disk' => $stats->sum_disk, 'memory' => $stats->sum_memory])->mapWithKeys(function ($value, $key) use ($node) { + $maxUsage = $node->{$key}; + if ($node->{$key . '_overallocate'} > 0) { + $maxUsage = $node->{$key} * (1 + ($node->{$key . '_overallocate'} / 100)); + } - $percent = ($value / $maxUsage) * 100; + $percent = ($value / $maxUsage) * 100; - return [ - $key => [ - 'value' => number_format($value), - 'max' => number_format($maxUsage), - 'percent' => $percent, - 'css' => ($percent <= self::THRESHOLD_PERCENTAGE_LOW) ? 'green' : (($percent > self::THRESHOLD_PERCENTAGE_MEDIUM) ? 'red' : 'yellow'), - ], - ]; - }) - ->toArray(); + return [ + $key => [ + 'value' => number_format($value), + 'max' => number_format($maxUsage), + 'percent' => $percent, + 'css' => ($percent <= self::THRESHOLD_PERCENTAGE_LOW) ? 'green' : (($percent > self::THRESHOLD_PERCENTAGE_MEDIUM) ? 'red' : 'yellow'), + ], + ]; + })->toArray(); } /** - * {@inheritdoc} + * Return all available nodes with a searchable interface. + * + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ - public function getNodeListingData($count = 25) + public function getNodeListingData(): LengthAwarePaginator { $instance = $this->getBuilder()->with('location')->withCount('servers'); - if ($this->searchTerm) { - $instance->search($this->searchTerm); + if ($this->hasSearchTerm()) { + $instance->setSearchTerm($this->getSearchTerm()); } - return $instance->paginate($count, $this->getColumns()); + return $instance->paginate(25, $this->getColumns()); } /** - * {@inheritdoc} + * Return a single node with location and server information. + * + * @param \Pterodactyl\Models\Node $node + * @param bool $refresh + * @return \Pterodactyl\Models\Node */ - public function getSingleNode($id) + public function loadLocationAndServerCount(Node $node, bool $refresh = false): Node { - $instance = $this->getBuilder()->with('location')->withCount('servers')->find($id, $this->getColumns()); - - if (! $instance) { - throw new RecordNotFoundException(); + if (! $node->relationLoaded('location') || $refresh) { + $node->load('location'); } - return $instance; + // This is quite ugly and can probably be improved down the road. + // And by probably, I mean it should. + if (is_null($node->servers_count) || $refresh) { + $node->load('servers'); + $node->setRelation('servers_count', count($node->getRelation('servers'))); + unset($node->servers); + } + + return $node; } /** - * {@inheritdoc} + * Attach a paginated set of allocations to a node mode including + * any servers that are also attached to those allocations. + * + * @param \Pterodactyl\Models\Node $node + * @param bool $refresh + * @return \Pterodactyl\Models\Node */ - public function getNodeAllocations($id) + public function loadNodeAllocations(Node $node, bool $refresh = false): Node { - $instance = $this->getBuilder()->find($id, $this->getColumns()); - - if (! $instance) { - throw new RecordNotFoundException(); - } - - $instance->setRelation( - 'allocations', - $instance->allocations()->orderBy('ip', 'asc')->orderBy('port', 'asc')->with('server')->paginate(50) + $node->setRelation('allocations', + $node->allocations()->orderBy('ip', 'asc')->orderBy('port', 'asc')->with('server')->paginate(50) ); - return $instance; + return $node; } /** - * {@inheritdoc} + * Return a node with all of the servers attached to that node. + * + * @param int $id + * @return \Pterodactyl\Models\Node + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getNodeServers($id) + public function getNodeServers(int $id): Node { - $instance = $this->getBuilder()->with('servers.user', 'servers.nest', 'servers.egg') - ->find($id, $this->getColumns()); - - if (! $instance) { - throw new RecordNotFoundException(); + try { + return $this->getBuilder()->with([ + 'servers.user', 'servers.nest', 'servers.egg', + ])->findOrFail($id, $this->getColumns()); + } catch (ModelNotFoundException $exception) { + throw new RecordNotFoundException; } - - return $instance; } /** - * {@inheritdoc} + * Return a collection of nodes for all locations to use in server creation UI. + * + * @return \Illuminate\Support\Collection */ - public function getNodesForServerCreation() + public function getNodesForServerCreation(): Collection { - $instance = $this->getBuilder()->with('allocations')->get(); - - return $instance->map(function ($item) { - $filtered = $item->allocations->where('server_id', null)->map(function ($map) { + return $this->getBuilder()->with('allocations')->get()->map(function (Node $item) { + $filtered = $item->getRelation('allocations')->where('server_id', null)->map(function ($map) { return collect($map)->only(['id', 'ip', 'port']); }); diff --git a/app/Repositories/Eloquent/PackRepository.php b/app/Repositories/Eloquent/PackRepository.php index b2c555512..a199e5500 100644 --- a/app/Repositories/Eloquent/PackRepository.php +++ b/app/Repositories/Eloquent/PackRepository.php @@ -1,27 +1,20 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; use Pterodactyl\Models\Pack; -use Webmozart\Assert\Assert; use Pterodactyl\Repositories\Concerns\Searchable; -use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Pterodactyl\Contracts\Repository\PackRepositoryInterface; -use Illuminate\Contracts\Filesystem\Factory as FilesystemFactory; class PackRepository extends EloquentRepository implements PackRepositoryInterface { use Searchable; /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -29,58 +22,32 @@ class PackRepository extends EloquentRepository implements PackRepositoryInterfa } /** - * {@inheritdoc} + * Return a pack with the associated server models attached to it. + * + * @param \Pterodactyl\Models\Pack $pack + * @param bool $refresh + * @return \Pterodactyl\Models\Pack */ - public function getFileArchives($id, $collection = false) + public function loadServerData(Pack $pack, bool $refresh = false): Pack { - Assert::numeric($id, 'First argument passed to getFileArchives must be numeric, received %s.'); - Assert::boolean($collection, 'Second argument passed to getFileArchives must be boolean, received %s.'); - - $pack = $this->getBuilder()->find($id, ['id', 'uuid']); - if (! $pack) { - throw new ModelNotFoundException; + if ($refresh) { + $pack->load(['servers.node', 'servers.user']); } - $storage = $this->app->make(FilesystemFactory::class); - $files = collect($storage->disk('default')->files('packs/' . $pack->uuid)); + $pack->loadMissing(['servers.node', 'servers.user']); - $files = $files->map(function ($file) { - $path = storage_path('app/' . $file); - - return (object) [ - 'name' => basename($file), - 'hash' => sha1_file($path), - 'size' => human_readable($path), - ]; - }); - - return ($collection) ? $files : (object) $files->all(); + return $pack; } /** - * {@inheritdoc} + * Return a paginated listing of packs with their associated egg and server count. + * + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ - public function getWithServers($id) + public function paginateWithEggAndServerCount(): LengthAwarePaginator { - Assert::numeric($id, 'First argument passed to getWithServers must be numeric, received %s.'); - - $instance = $this->getBuilder()->with('servers.node', 'servers.user')->find($id, $this->getColumns()); - if (! $instance) { - throw new ModelNotFoundException; - } - - return $instance; - } - - /** - * {@inheritdoc} - */ - public function paginateWithEggAndServerCount($paginate = 50) - { - Assert::integer($paginate, 'First argument passed to paginateWithOptionAndServerCount must be integer, received %s.'); - return $this->getBuilder()->with('egg')->withCount('servers') - ->search($this->searchTerm) - ->paginate($paginate, $this->getColumns()); + ->setSearchTerm($this->getSearchTerm()) + ->paginate(50, $this->getColumns()); } } diff --git a/app/Repositories/Eloquent/PermissionRepository.php b/app/Repositories/Eloquent/PermissionRepository.php index ca67b3975..ad2fa6386 100644 --- a/app/Repositories/Eloquent/PermissionRepository.php +++ b/app/Repositories/Eloquent/PermissionRepository.php @@ -1,11 +1,4 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; @@ -15,7 +8,9 @@ use Pterodactyl\Contracts\Repository\PermissionRepositoryInterface; class PermissionRepository extends EloquentRepository implements PermissionRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { diff --git a/app/Repositories/Eloquent/ScheduleRepository.php b/app/Repositories/Eloquent/ScheduleRepository.php index 4c0f5b0f0..02be96439 100644 --- a/app/Repositories/Eloquent/ScheduleRepository.php +++ b/app/Repositories/Eloquent/ScheduleRepository.php @@ -1,23 +1,19 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; use Pterodactyl\Models\Schedule; use Illuminate\Support\Collection; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Pterodactyl\Exceptions\Repository\RecordNotFoundException; use Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface; class ScheduleRepository extends EloquentRepository implements ScheduleRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -45,19 +41,20 @@ class ScheduleRepository extends EloquentRepository implements ScheduleRepositor */ public function getScheduleWithTasks(int $schedule): Schedule { - /** @var \Pterodactyl\Models\Schedule $instance */ - $instance = $this->getBuilder()->with('tasks')->find($schedule, $this->getColumns()); - if (! $instance) { + try { + return $this->getBuilder()->with('tasks')->findOrFail($schedule, $this->getColumns()); + } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } - - return $instance; } /** - * {@inheritdoc} + * Return all of the schedules that should be processed. + * + * @param string $timestamp + * @return \Illuminate\Support\Collection */ - public function getSchedulesToProcess($timestamp) + public function getSchedulesToProcess(string $timestamp): Collection { return $this->getBuilder()->with('tasks') ->where('is_active', true) diff --git a/app/Repositories/Eloquent/ServerRepository.php b/app/Repositories/Eloquent/ServerRepository.php index b8f5cc6fc..49fa53c41 100644 --- a/app/Repositories/Eloquent/ServerRepository.php +++ b/app/Repositories/Eloquent/ServerRepository.php @@ -1,17 +1,14 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; +use Pterodactyl\Models\User; use Webmozart\Assert\Assert; use Pterodactyl\Models\Server; +use Illuminate\Support\Collection; use Pterodactyl\Repositories\Concerns\Searchable; +use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Pterodactyl\Exceptions\Repository\RecordNotFoundException; use Pterodactyl\Contracts\Repository\ServerRepositoryInterface; @@ -20,7 +17,9 @@ class ServerRepository extends EloquentRepository implements ServerRepositoryInt use Searchable; /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -28,15 +27,16 @@ class ServerRepository extends EloquentRepository implements ServerRepositoryInt } /** - * {@inheritdoc} + * Returns a listing of all servers that exist including relationships. + * + * @param int $paginate + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ - public function getAllServers($paginate = 25) + public function getAllServers(int $paginate): LengthAwarePaginator { - Assert::nullOrIntegerish($paginate, 'First argument passed to getAllServers must be integer or null, received %s.'); + $instance = $this->getBuilder()->with('node', 'user', 'allocation')->setSearchTerm($this->getSearchTerm()); - $instance = $this->getBuilder()->with('node', 'user', 'allocation')->search($this->searchTerm); - - return is_null($paginate) ? $instance->get($this->getColumns()) : $instance->paginate($paginate, $this->getColumns()); + return $instance->paginate($paginate, $this->getColumns()); } /** @@ -56,14 +56,15 @@ class ServerRepository extends EloquentRepository implements ServerRepositoryInt } /** - * {@inheritdoc} + * Return a collection of servers with their associated data for rebuild operations. + * + * @param int|null $server + * @param int|null $node + * @return \Illuminate\Support\Collection */ - public function getDataForRebuild($server = null, $node = null) + public function getDataForRebuild(int $server = null, int $node = null): Collection { - Assert::nullOrIntegerish($server, 'First argument passed to getDataForRebuild must be null or integer, received %s.'); - Assert::nullOrIntegerish($node, 'Second argument passed to getDataForRebuild must be null or integer, received %s.'); - - $instance = $this->getBuilder()->with('allocation', 'allocations', 'pack', 'egg', 'node'); + $instance = $this->getBuilder()->with(['allocation', 'allocations', 'pack', 'egg', 'node']); if (! is_null($server) && is_null($node)) { $instance = $instance->where('id', '=', $server); @@ -75,22 +76,22 @@ class ServerRepository extends EloquentRepository implements ServerRepositoryInt } /** - * {@inheritdoc} - * @return \Illuminate\Database\Eloquent\Model + * Return a server model and all variables associated with the server. + * + * @param int $id + * @return \Pterodactyl\Models\Server + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function findWithVariables($id) + public function findWithVariables(int $id): Server { - Assert::integerish($id, 'First argument passed to findWithVariables must be integer, received %s.'); - - $instance = $this->getBuilder()->with('egg.variables', 'variables') - ->where($this->getModel()->getKeyName(), '=', $id) - ->first($this->getColumns()); - - if (is_null($instance)) { - throw new RecordNotFoundException(); + try { + return $this->getBuilder()->with('egg.variables', 'variables') + ->where($this->getModel()->getKeyName(), '=', $id) + ->firstOrFail($this->getColumns()); + } catch (ModelNotFoundException $exception) { + throw new RecordNotFoundException; } - - return $instance; } /** @@ -98,51 +99,45 @@ class ServerRepository extends EloquentRepository implements ServerRepositoryInt * the function, load the allocation relationship onto it. Otherwise, find and * return the server from the database. * - * @param int|\Pterodactyl\Models\Server $server - * @param bool $refresh + * @param \Pterodactyl\Models\Server $server + * @param bool $refresh * @return \Pterodactyl\Models\Server - * - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getPrimaryAllocation($server, bool $refresh = false): Server + public function getPrimaryAllocation(Server $server, bool $refresh = false): Server { - $instance = $server; - if (! $instance instanceof Server) { - Assert::integerish($server, 'First argument passed to getPrimaryAllocation must be instance of \Pterodactyl\Models\Server or integer, received %s.'); - $instance = $this->getBuilder()->find($server, $this->getColumns()); + if (! $server->relationLoaded('allocation') || $refresh) { + $server->load('allocation'); } - if (! $instance) { - throw new RecordNotFoundException; - } - - if (! $instance->relationLoaded('allocation') || $refresh) { - $instance->load('allocation'); - } - - return $instance; + return $server; } /** - * {@inheritdoc} + * Return all of the server variables possible and default to the variable + * default if there is no value defined for the specific server requested. + * + * @param int $id + * @param bool $returnAsObject + * @return array|object + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getVariablesWithValues($id, $returnWithObject = false) + public function getVariablesWithValues(int $id, bool $returnAsObject = false) { - $instance = $this->getBuilder()->with('variables', 'egg.variables') - ->find($id, $this->getColumns()); - - if (! $instance) { - throw new RecordNotFoundException(); + try { + $instance = $this->getBuilder()->with('variables', 'egg.variables')->find($id, $this->getColumns()); + } catch (ModelNotFoundException $exception) { + throw new RecordNotFoundException; } $data = []; - $instance->egg->variables->each(function ($item) use (&$data, $instance) { - $display = $instance->variables->where('variable_id', $item->id)->pluck('variable_value')->first(); + $instance->getRelation('egg')->getRelation('variables')->each(function ($item) use (&$data, $instance) { + $display = $instance->getRelation('variables')->where('variable_id', $item->id)->pluck('variable_value')->first(); $data[$item->env_variable] = $display ?? $item->default_value; }); - if ($returnWithObject) { + if ($returnAsObject) { return (object) [ 'data' => $data, 'server' => $instance, @@ -171,19 +166,19 @@ class ServerRepository extends EloquentRepository implements ServerRepositoryInt } /** - * {@inheritdoc} + * Load associated databases onto the server model. + * + * @param \Pterodactyl\Models\Server $server + * @param bool $refresh + * @return \Pterodactyl\Models\Server */ - public function getWithDatabases($id) + public function loadDatabaseRelations(Server $server, bool $refresh = false): Server { - $instance = $this->getBuilder()->with('databases.host') - ->where('installed', 1) - ->find($id, $this->getColumns()); - - if (! $instance) { - throw new RecordNotFoundException(); + if (! $server->relationLoaded('databases') || $refresh) { + $server->load('databases.host'); } - return $instance; + return $server; } /** @@ -212,71 +207,70 @@ class ServerRepository extends EloquentRepository implements ServerRepositoryInt } /** - * {@inheritdoc} + * Return a paginated list of servers that a user can access at a given level. + * + * @param \Pterodactyl\Models\User $user + * @param int $level + * @return \Illuminate\Pagination\LengthAwarePaginator */ - public function getUserAccessServers($user) + public function filterUserAccessServers(User $user, int $level): LengthAwarePaginator { - Assert::numeric($user, 'First argument passed to getUserAccessServers must be numeric, received %s.'); - - $subuser = $this->app->make(SubuserRepository::class); - - return $this->getBuilder()->select('id')->where('owner_id', $user)->union( - $subuser->getBuilder()->select('server_id')->where('user_id', $user) - )->pluck('id')->all(); - } - - /** - * {@inheritdoc} - */ - public function filterUserAccessServers($user, $admin = false, $level = 'all', array $relations = []) - { - Assert::numeric($user, 'First argument passed to filterUserAccessServers must be numeric, received %s.'); - Assert::boolean($admin, 'Second argument passed to filterUserAccessServers must be boolean, received %s.'); - Assert::stringNotEmpty($level, 'Third argument passed to filterUserAccessServers must be a non-empty string, received %s.'); - - $instance = $this->getBuilder()->with($relations); + $instance = $this->getBuilder()->with(['user']); // If access level is set to owner, only display servers // that the user owns. - if ($level === 'owner') { - $instance->where('owner_id', $user); + if ($level === User::FILTER_LEVEL_OWNER) { + $instance->where('owner_id', $user->id); } // If set to all, display all servers they can access, including - // those they access as an admin. - // - // If set to subuser, only return the servers they can access because + // those they access as an admin. If set to subuser, only return the servers they can access because // they are owner, or marked as a subuser of the server. - if (($level === 'all' && ! $admin) || $level === 'subuser') { - $instance->whereIn('id', $this->getUserAccessServers($user)); + elseif (($level === User::FILTER_LEVEL_ALL && ! $user->root_admin) || $level === User::FILTER_LEVEL_SUBUSER) { + $instance->whereIn('id', $this->getUserAccessServers($user->id)); } // If set to admin, only display the servers a user can access // as an administrator (leaves out owned and subuser of). - if ($level === 'admin' && $admin) { - $instance->whereIn('id', $this->getUserAccessServers($user)); + elseif ($level === User::FILTER_LEVEL_ADMIN && $user->root_admin) { + $instance->whereNotIn('id', $this->getUserAccessServers($user->id)); } - return $instance->search($this->searchTerm)->paginate( - $this->app->make('config')->get('pterodactyl.paginate.frontend.servers') - ); + return $instance->setSearchTerm($this->getSearchTerm())->paginate(25); } /** - * {@inheritdoc} + * Return a server by UUID. + * + * @param string $uuid + * @return \Pterodactyl\Models\Server + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getByUuid($uuid) + public function getByUuid(string $uuid): Server { - Assert::stringNotEmpty($uuid, 'First argument passed to getByUuid must be a non-empty string, received %s.'); + Assert::notEmpty($uuid, 'Expected non-empty string as first argument passed to ' . __METHOD__); - $instance = $this->getBuilder()->with('nest', 'node')->where(function ($query) use ($uuid) { - $query->where('uuidShort', $uuid)->orWhere('uuid', $uuid); - })->first($this->getColumns()); - - if (! $instance) { + try { + return $this->getBuilder()->with('nest', 'node')->where(function ($query) use ($uuid) { + $query->where('uuidShort', $uuid)->orWhere('uuid', $uuid); + })->firstOrFail($this->getColumns()); + } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } + } - return $instance; + /** + * Return an array of server IDs that a given user can access based + * on owner and subuser permissions. + * + * @param int $user + * @return int[] + */ + private function getUserAccessServers(int $user): array + { + return $this->getBuilder()->select('id')->where('owner_id', $user)->union( + $this->app->make(SubuserRepository::class)->getBuilder()->select('server_id')->where('user_id', $user) + )->pluck('id')->all(); } } diff --git a/app/Repositories/Eloquent/ServerVariableRepository.php b/app/Repositories/Eloquent/ServerVariableRepository.php index 49a81430a..d0d5e4dba 100644 --- a/app/Repositories/Eloquent/ServerVariableRepository.php +++ b/app/Repositories/Eloquent/ServerVariableRepository.php @@ -1,11 +1,4 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; @@ -15,7 +8,9 @@ use Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface; class ServerVariableRepository extends EloquentRepository implements ServerVariableRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { diff --git a/app/Repositories/Eloquent/SessionRepository.php b/app/Repositories/Eloquent/SessionRepository.php index 8ba826696..47d955077 100644 --- a/app/Repositories/Eloquent/SessionRepository.php +++ b/app/Repositories/Eloquent/SessionRepository.php @@ -1,21 +1,17 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; use Pterodactyl\Models\Session; +use Illuminate\Support\Collection; use Pterodactyl\Contracts\Repository\SessionRepositoryInterface; class SessionRepository extends EloquentRepository implements SessionRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -23,17 +19,24 @@ class SessionRepository extends EloquentRepository implements SessionRepositoryI } /** - * {@inheritdoc} + * Return all of the active sessions for a user. + * + * @param int $user + * @return \Illuminate\Support\Collection */ - public function getUserSessions($user) + public function getUserSessions(int $user): Collection { return $this->getBuilder()->where('user_id', $user)->get($this->getColumns()); } /** - * {@inheritdoc} + * Delete a session for a given user. + * + * @param int $user + * @param int $session + * @return null|int */ - public function deleteUserSession($user, $session) + public function deleteUserSession(int $user, int $session) { return $this->getBuilder()->where('user_id', $user)->where('id', $session)->delete(); } diff --git a/app/Repositories/Eloquent/SettingsRepository.php b/app/Repositories/Eloquent/SettingsRepository.php index b6937bf31..dd516d68e 100644 --- a/app/Repositories/Eloquent/SettingsRepository.php +++ b/app/Repositories/Eloquent/SettingsRepository.php @@ -10,16 +10,15 @@ class SettingsRepository extends EloquentRepository implements SettingsRepositor /** * @var array */ - private $cache = []; + private static $cache = []; /** * @var array */ - private $databaseMiss = []; + private static $databaseMiss = []; /** - * Return an instance of the model that acts as the base for - * this repository. + * Return the model backing this repository. * * @return string */ @@ -33,12 +32,17 @@ class SettingsRepository extends EloquentRepository implements SettingsRepositor * * @param string $key * @param string $value + * + * @throws \Pterodactyl\Exceptions\Model\DataValidationException + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ public function set(string $key, string $value) { // Clear item from the cache. $this->clearCache($key); - $this->withoutFresh()->updateOrCreate(['key' => $key], ['value' => $value]); + $this->withoutFreshModel()->updateOrCreate(['key' => $key], ['value' => $value]); + + self::$cache[$key] = $value; } /** @@ -51,32 +55,27 @@ class SettingsRepository extends EloquentRepository implements SettingsRepositor public function get(string $key, $default = null) { // If item has already been requested return it from the cache. If - // we already know it is missing, immediately return the default - // value. - if (array_key_exists($key, $this->cache)) { - return $this->cache[$key]; - } elseif (array_key_exists($key, $this->databaseMiss)) { - return $default; + // we already know it is missing, immediately return the default value. + if (array_key_exists($key, self::$cache)) { + return self::$cache[$key]; + } elseif (array_key_exists($key, self::$databaseMiss)) { + return value($default); } $instance = $this->getBuilder()->where('key', $key)->first(); - if (is_null($instance)) { - $this->databaseMiss[$key] = true; + self::$databaseMiss[$key] = true; - return $default; + return value($default); } - $this->cache[$key] = $instance->value; - - return $this->cache[$key]; + return self::$cache[$key] = $instance->value; } /** * Remove a key from the database cache. * * @param string $key - * @return mixed */ public function forget(string $key) { @@ -89,8 +88,8 @@ class SettingsRepository extends EloquentRepository implements SettingsRepositor * * @param string $key */ - protected function clearCache(string $key) + private function clearCache(string $key) { - unset($this->cache[$key], $this->databaseMiss[$key]); + unset(self::$cache[$key], self::$databaseMiss[$key]); } } diff --git a/app/Repositories/Eloquent/SubuserRepository.php b/app/Repositories/Eloquent/SubuserRepository.php index e1387b530..0296e0dbd 100644 --- a/app/Repositories/Eloquent/SubuserRepository.php +++ b/app/Repositories/Eloquent/SubuserRepository.php @@ -1,15 +1,7 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; -use Webmozart\Assert\Assert; use Pterodactyl\Models\Subuser; use Pterodactyl\Exceptions\Repository\RecordNotFoundException; use Pterodactyl\Contracts\Repository\SubuserRepositoryInterface; @@ -17,7 +9,9 @@ use Pterodactyl\Contracts\Repository\SubuserRepositoryInterface; class SubuserRepository extends EloquentRepository implements SubuserRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -86,39 +80,4 @@ class SubuserRepository extends EloquentRepository implements SubuserRepositoryI return $instance; } - - /** - * {@inheritdoc} - */ - public function getWithServerAndPermissions($id) - { - Assert::numeric($id, 'First argument passed to getWithServerAndPermissions must be numeric, received %s.'); - - $instance = $this->getBuilder()->with('server', 'permission', 'user')->find($id, $this->getColumns()); - if (! $instance) { - throw new RecordNotFoundException; - } - - return $instance; - } - - /** - * {@inheritdoc} - */ - public function getWithKey($user, $server) - { - Assert::integerish($user, 'First argument passed to getWithKey must be integer, received %s.'); - Assert::integerish($server, 'Second argument passed to getWithKey must be integer, received %s.'); - - $instance = $this->getBuilder()->with('key')->where([ - ['user_id', '=', $user], - ['server_id', '=', $server], - ])->first(); - - if (is_null($instance)) { - throw new RecordNotFoundException; - } - - return $instance; - } } diff --git a/app/Repositories/Eloquent/TaskRepository.php b/app/Repositories/Eloquent/TaskRepository.php index c44aa2fc6..ef4a92a0b 100644 --- a/app/Repositories/Eloquent/TaskRepository.php +++ b/app/Repositories/Eloquent/TaskRepository.php @@ -1,23 +1,18 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; use Pterodactyl\Models\Task; -use Webmozart\Assert\Assert; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Pterodactyl\Contracts\Repository\TaskRepositoryInterface; use Pterodactyl\Exceptions\Repository\RecordNotFoundException; class TaskRepository extends EloquentRepository implements TaskRepositoryInterface { /** - * {@inheritdoc} + * Return the model backing this repository. + * + * @return string */ public function model() { @@ -25,28 +20,31 @@ class TaskRepository extends EloquentRepository implements TaskRepositoryInterfa } /** - * {@inheritdoc} + * Get a task and the server relationship for that task. + * + * @param int $id + * @return \Pterodactyl\Models\Task + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getTaskWithServer($id) + public function getTaskWithServer(int $id): Task { - Assert::integerish($id, 'First argument passed to getTaskWithServer must be numeric, received %s.'); - - $instance = $this->getBuilder()->with('server.user')->find($id, $this->getColumns()); - if (! $instance) { + try { + return $this->getBuilder()->with('server.user')->findOrFail($id, $this->getColumns()); + } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } - - return $instance; } /** - * {@inheritdoc} + * Returns the next task in a schedule. + * + * @param int $schedule + * @param int $index + * @return null|\Pterodactyl\Models\Task */ - public function getNextTask($schedule, $index) + public function getNextTask(int $schedule, int $index) { - Assert::integerish($schedule, 'First argument passed to getNextTask must be integer, received %s.'); - Assert::integerish($index, 'Second argument passed to getNextTask must be integer, received %s.'); - return $this->getBuilder()->where('schedule_id', '=', $schedule) ->where('sequence_id', '=', $index + 1) ->first($this->getColumns()); diff --git a/app/Repositories/Eloquent/UserRepository.php b/app/Repositories/Eloquent/UserRepository.php index 6dbb5d8c3..4b033dc14 100644 --- a/app/Repositories/Eloquent/UserRepository.php +++ b/app/Repositories/Eloquent/UserRepository.php @@ -1,44 +1,21 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Eloquent; use Pterodactyl\Models\User; -use Illuminate\Foundation\Application; +use Illuminate\Support\Collection; use Pterodactyl\Repositories\Concerns\Searchable; +use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Pterodactyl\Contracts\Repository\UserRepositoryInterface; -use Illuminate\Contracts\Config\Repository as ConfigRepository; class UserRepository extends EloquentRepository implements UserRepositoryInterface { use Searchable; /** - * @var \Illuminate\Contracts\Config\Repository - */ - protected $config; - - /** - * UserRepository constructor. + * Return the model backing this repository. * - * @param \Illuminate\Foundation\Application $application - * @param \Illuminate\Contracts\Config\Repository $config - */ - public function __construct(Application $application, ConfigRepository $config) - { - parent::__construct($application); - - $this->config = $config; - } - - /** - * {@inheritdoc} + * @return string */ public function model() { @@ -46,32 +23,30 @@ class UserRepository extends EloquentRepository implements UserRepositoryInterfa } /** - * {@inheritdoc} + * Return all users with counts of servers and subusers of servers. + * + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ - public function getAllUsersWithCounts() + public function getAllUsersWithCounts(): LengthAwarePaginator { - $users = $this->getBuilder()->withCount('servers', 'subuserOf'); - - if ($this->searchTerm) { - $users->search($this->searchTerm); - } - - return $users->paginate( - $this->config->get('pterodactyl.paginate.admin.users'), - $this->getColumns() - ); + return $this->getBuilder()->withCount('servers', 'subuserOf') + ->setSearchTerm($this->getSearchTerm()) + ->paginate(50, $this->getColumns()); } /** - * {@inheritdoc} + * Return all matching models for a user in a format that can be used for dropdowns. + * + * @param string $query + * @return \Illuminate\Support\Collection */ - public function filterUsersByQuery($query) + public function filterUsersByQuery(string $query): Collection { - $this->withColumns([ + $this->setColumns([ 'id', 'email', 'username', 'name_first', 'name_last', ]); - $instance = $this->getBuilder()->search($query)->get($this->getColumns()); + $instance = $this->getBuilder()->setSearchTerm($query)->get($this->getColumns()); return $instance->transform(function ($item) { $item->md5 = md5(strtolower($item->email)); diff --git a/app/Repositories/Repository.php b/app/Repositories/Repository.php index f9164d284..c3014a31a 100644 --- a/app/Repositories/Repository.php +++ b/app/Repositories/Repository.php @@ -1,14 +1,8 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories; +use InvalidArgumentException; use Illuminate\Foundation\Application; use Pterodactyl\Contracts\Repository\RepositoryInterface; @@ -43,35 +37,13 @@ abstract class Repository implements RepositoryInterface { $this->app = $application; - $this->setModel($this->model()); + $this->initalizeModel($this->model()); } /** - * Take the provided model and make it accessible to the rest of the repository. + * Return the model backing this repository. * - * @param string|array $model - * @return mixed - */ - protected function setModel($model) - { - if (is_array($model)) { - if (count($model) !== 2) { - throw new \InvalidArgumentException( - printf('setModel expected exactly 2 parameters, %d received.', count($model)) - ); - } - - return $this->model = call_user_func( - $model[1], - $this->app->make($model[0]) - ); - } - - return $this->model = $this->app->make($model); - } - - /** - * @return mixed + * @return string|\Closure|object */ abstract public function model(); @@ -88,10 +60,10 @@ abstract class Repository implements RepositoryInterface /** * Setup column selection functionality. * - * @param array $columns + * @param array|string $columns * @return $this */ - public function withColumns($columns = ['*']) + public function setColumns($columns = ['*']) { $clone = clone $this; $clone->columns = is_array($columns) ? $columns : func_get_args(); @@ -110,15 +82,56 @@ abstract class Repository implements RepositoryInterface } /** - * Set repository to not return a fresh record from the DB when completed. + * Stop repository update functions from returning a fresh + * model when changes are committed. * * @return $this */ - public function withoutFresh() + public function withoutFreshModel() + { + return $this->setFreshModel(false); + } + + /** + * Return a fresh model with a repository updates a model. + * + * @return $this + */ + public function withFreshModel() + { + return $this->setFreshModel(true); + } + + /** + * Set wether or not the repository should return a fresh model + * when changes are committed. + * + * @param bool $fresh + * @return $this + */ + public function setFreshModel(bool $fresh = true) { $clone = clone $this; - $clone->withFresh = false; + $clone->withFresh = $fresh; return $clone; } + + /** + * Take the provided model and make it accessible to the rest of the repository. + * + * @param array $model + * @return mixed + */ + protected function initalizeModel(...$model) + { + switch (count($model)) { + case 1: + return $this->model = $this->app->make($model[0]); + case 2: + return $this->model = call_user_func([$this->app->make($model[0]), $model[1]]); + default: + throw new InvalidArgumentException('Model must be a FQCN or an array with a count of two.'); + } + } } diff --git a/app/Services/Eggs/Sharing/EggUpdateImporterService.php b/app/Services/Eggs/Sharing/EggUpdateImporterService.php index f0df63ad7..3cb275ff7 100644 --- a/app/Services/Eggs/Sharing/EggUpdateImporterService.php +++ b/app/Services/Eggs/Sharing/EggUpdateImporterService.php @@ -96,7 +96,7 @@ class EggUpdateImporterService }); $imported = collect($parsed->variables)->pluck('env_variable')->toArray(); - $existing = $this->variableRepository->withColumns(['id', 'env_variable'])->findWhere([['egg_id', '=', $egg]]); + $existing = $this->variableRepository->setColumns(['id', 'env_variable'])->findWhere([['egg_id', '=', $egg]]); // Delete variables not present in the import. collect($existing)->each(function ($variable) use ($egg, $imported) { diff --git a/app/Services/Eggs/Variables/VariableUpdateService.php b/app/Services/Eggs/Variables/VariableUpdateService.php index 0249e4fba..91694b166 100644 --- a/app/Services/Eggs/Variables/VariableUpdateService.php +++ b/app/Services/Eggs/Variables/VariableUpdateService.php @@ -49,7 +49,7 @@ class VariableUpdateService ])); } - $search = $this->repository->withColumns('id')->findCountWhere([ + $search = $this->repository->setColumns('id')->findCountWhere([ ['env_variable', '=', array_get($data, 'env_variable')], ['egg_id', '=', $variable->egg_id], ['id', '!=', $variable->id], diff --git a/app/Services/Nodes/NodeDeletionService.php b/app/Services/Nodes/NodeDeletionService.php index 9df62be6a..e4d2ed999 100644 --- a/app/Services/Nodes/NodeDeletionService.php +++ b/app/Services/Nodes/NodeDeletionService.php @@ -63,7 +63,7 @@ class NodeDeletionService $node = $node->id; } - $servers = $this->serverRepository->withColumns('id')->findCountWhere([['node_id', '=', $node]]); + $servers = $this->serverRepository->setColumns('id')->findCountWhere([['node_id', '=', $node]]); if ($servers > 0) { throw new HasActiveServersException($this->translator->trans('exceptions.node.servers_attached')); } diff --git a/app/Services/Packs/PackDeletionService.php b/app/Services/Packs/PackDeletionService.php index 5118990ad..9d4743310 100644 --- a/app/Services/Packs/PackDeletionService.php +++ b/app/Services/Packs/PackDeletionService.php @@ -69,7 +69,7 @@ class PackDeletionService public function handle($pack) { if (! $pack instanceof Pack) { - $pack = $this->repository->withColumns(['id', 'uuid'])->find($pack); + $pack = $this->repository->setColumns(['id', 'uuid'])->find($pack); } $count = $this->serverRepository->findCountWhere([['pack_id', '=', $pack->id]]); diff --git a/app/Services/Packs/PackUpdateService.php b/app/Services/Packs/PackUpdateService.php index bb84f7b98..3354a66f5 100644 --- a/app/Services/Packs/PackUpdateService.php +++ b/app/Services/Packs/PackUpdateService.php @@ -54,7 +54,7 @@ class PackUpdateService public function handle($pack, array $data) { if (! $pack instanceof Pack) { - $pack = $this->repository->withColumns(['id', 'egg_id'])->find($pack); + $pack = $this->repository->setColumns(['id', 'egg_id'])->find($pack); } if ((int) array_get($data, 'egg_id', $pack->egg_id) !== $pack->egg_id) { diff --git a/app/Services/Servers/ServerDeletionService.php b/app/Services/Servers/ServerDeletionService.php index 1129a187c..4ae5c645d 100644 --- a/app/Services/Servers/ServerDeletionService.php +++ b/app/Services/Servers/ServerDeletionService.php @@ -106,7 +106,7 @@ class ServerDeletionService public function handle($server) { if (! $server instanceof Server) { - $server = $this->repository->withColumns(['id', 'node_id', 'uuid'])->find($server); + $server = $this->repository->setColumns(['id', 'node_id', 'uuid'])->find($server); } try { @@ -128,7 +128,7 @@ class ServerDeletionService } $this->connection->beginTransaction(); - $this->databaseRepository->withColumns('id')->findWhere([['server_id', '=', $server->id]])->each(function ($item) { + $this->databaseRepository->setColumns('id')->findWhere([['server_id', '=', $server->id]])->each(function ($item) { $this->databaseManagementService->delete($item->id); }); diff --git a/app/Services/Sftp/AuthenticateUsingPasswordService.php b/app/Services/Sftp/AuthenticateUsingPasswordService.php index 16ac56b67..1cf64bd8e 100644 --- a/app/Services/Sftp/AuthenticateUsingPasswordService.php +++ b/app/Services/Sftp/AuthenticateUsingPasswordService.php @@ -68,7 +68,7 @@ class AuthenticateUsingPasswordService } try { - $user = $this->userRepository->withColumns(['id', 'root_admin', 'password'])->findFirstWhere([['username', '=', $username]]); + $user = $this->userRepository->setColumns(['id', 'root_admin', 'password'])->findFirstWhere([['username', '=', $username]]); if (! password_verify($password, $user->password)) { throw new AuthenticationException; @@ -77,7 +77,7 @@ class AuthenticateUsingPasswordService throw new AuthenticationException; } - $server = $this->repository->withColumns(['id', 'node_id', 'owner_id', 'uuid'])->getByUuid($server); + $server = $this->repository->setColumns(['id', 'node_id', 'owner_id', 'uuid'])->getByUuid($server); if ($server->node_id !== $node || (! $user->root_admin && $server->owner_id !== $user->id)) { throw new RecordNotFoundException; } diff --git a/app/Services/Users/UserDeletionService.php b/app/Services/Users/UserDeletionService.php index 6b335be4b..942e76faf 100644 --- a/app/Services/Users/UserDeletionService.php +++ b/app/Services/Users/UserDeletionService.php @@ -63,7 +63,7 @@ class UserDeletionService $user = $user->id; } - $servers = $this->serverRepository->withColumns('id')->findCountWhere([['owner_id', '=', $user]]); + $servers = $this->serverRepository->setColumns('id')->findCountWhere([['owner_id', '=', $user]]); if ($servers > 0) { throw new DisplayException($this->translator->trans('admin/user.exceptions.user_has_servers')); } diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php index c5501d119..6e585d4d6 100644 --- a/database/factories/ModelFactory.php +++ b/database/factories/ModelFactory.php @@ -186,6 +186,7 @@ $factory->define(Pterodactyl\Models\Database::class, function (Faker $faker) { 'database_host_id' => $faker->randomNumber(), 'database' => str_random(10), 'username' => str_random(10), + 'remote' => '%', 'password' => $password ?: bcrypt('test123'), 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), diff --git a/database/seeds/EggSeeder.php b/database/seeds/EggSeeder.php index 4f5915a2d..245d74ac3 100644 --- a/database/seeds/EggSeeder.php +++ b/database/seeds/EggSeeder.php @@ -122,7 +122,7 @@ class EggSeeder extends Seeder $file = new UploadedFile($file->getPathname(), $file->getFilename(), 'application/json', $file->getSize()); try { - $egg = $this->repository->withColumns('id')->findFirstWhere([ + $egg = $this->repository->setColumns('id')->findFirstWhere([ ['author', '=', $decoded->author], ['name', '=', $decoded->name], ['nest_id', '=', $nest->id], diff --git a/tests/Traits/Http/RequestMockHelpers.php b/tests/Traits/Http/RequestMockHelpers.php index 8611e710f..f33ff71e9 100644 --- a/tests/Traits/Http/RequestMockHelpers.php +++ b/tests/Traits/Http/RequestMockHelpers.php @@ -45,11 +45,12 @@ trait RequestMockHelpers /** * Generates a new request user model and also returns the generated model. * + * @param array $args * @return \Pterodactyl\Models\User */ - public function generateRequestUserModel(): User + public function generateRequestUserModel(array $args = []): User { - $user = factory(User::class)->make(); + $user = factory(User::class)->make($args); $this->setRequestUserModel($user); return $user; diff --git a/tests/Unit/Commands/User/DeleteUserCommandTest.php b/tests/Unit/Commands/User/DeleteUserCommandTest.php index 1800c70da..fa5b5199d 100644 --- a/tests/Unit/Commands/User/DeleteUserCommandTest.php +++ b/tests/Unit/Commands/User/DeleteUserCommandTest.php @@ -1,11 +1,4 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Tests\Unit\Commands\User; @@ -60,7 +53,7 @@ class DeleteUserCommandTest extends CommandTestCase $user2 = factory(User::class)->make(), ]); - $this->repository->shouldReceive('search')->with($user1->username)->once()->andReturnSelf() + $this->repository->shouldReceive('setSearchTerm')->with($user1->username)->once()->andReturnSelf() ->shouldReceive('all')->withNoArgs()->once()->andReturn($users); $this->deletionService->shouldReceive('handle')->with($user1->id)->once()->andReturnNull(); @@ -82,9 +75,9 @@ class DeleteUserCommandTest extends CommandTestCase $user1 = factory(User::class)->make(), ]); - $this->repository->shouldReceive('search')->with('noResults')->once()->andReturnSelf() - ->shouldReceive('all')->withNoArgs()->once()->andReturn([]); - $this->repository->shouldReceive('search')->with($user1->username)->once()->andReturnSelf() + $this->repository->shouldReceive('setSearchTerm')->with('noResults')->once()->andReturnSelf() + ->shouldReceive('all')->withNoArgs()->once()->andReturn(collect()); + $this->repository->shouldReceive('setSearchTerm')->with($user1->username)->once()->andReturnSelf() ->shouldReceive('all')->withNoArgs()->once()->andReturn($users); $this->deletionService->shouldReceive('handle')->with($user1->id)->once()->andReturnNull(); @@ -107,7 +100,7 @@ class DeleteUserCommandTest extends CommandTestCase $user1 = factory(User::class)->make(), ]); - $this->repository->shouldReceive('search')->with($user1->username)->twice()->andReturnSelf() + $this->repository->shouldReceive('setSearchTerm')->with($user1->username)->twice()->andReturnSelf() ->shouldReceive('all')->withNoArgs()->twice()->andReturn($users); $this->deletionService->shouldReceive('handle')->with($user1->id)->once()->andReturnNull(); @@ -130,7 +123,7 @@ class DeleteUserCommandTest extends CommandTestCase $user1 = factory(User::class)->make(), ]); - $this->repository->shouldReceive('search')->with($user1->username)->once()->andReturnSelf() + $this->repository->shouldReceive('setSearchTerm')->with($user1->username)->once()->andReturnSelf() ->shouldReceive('all')->withNoArgs()->once()->andReturn($users); $this->deletionService->shouldNotReceive('handle'); @@ -149,7 +142,7 @@ class DeleteUserCommandTest extends CommandTestCase $user1 = factory(User::class)->make(), ]); - $this->repository->shouldReceive('search')->with($user1->username)->once()->andReturnSelf() + $this->repository->shouldReceive('setSearchTerm')->with($user1->username)->once()->andReturnSelf() ->shouldReceive('all')->withNoArgs()->once()->andReturn($users); $this->deletionService->shouldReceive('handle')->with($user1)->once()->andReturnNull(); @@ -169,7 +162,7 @@ class DeleteUserCommandTest extends CommandTestCase $user2 = factory(User::class)->make(), ]); - $this->repository->shouldReceive('search')->with($user1->username)->once()->andReturnSelf() + $this->repository->shouldReceive('setSearchTerm')->with($user1->username)->once()->andReturnSelf() ->shouldReceive('all')->withNoArgs()->once()->andReturn($users); $this->deletionService->shouldNotReceive('handle'); @@ -184,8 +177,8 @@ class DeleteUserCommandTest extends CommandTestCase */ public function testNoInteractionWithNoResults() { - $this->repository->shouldReceive('search')->with(123456)->once()->andReturnSelf() - ->shouldReceive('all')->withNoArgs()->once()->andReturn([]); + $this->repository->shouldReceive('setSearchTerm')->with(123456)->once()->andReturnSelf() + ->shouldReceive('all')->withNoArgs()->once()->andReturn(collect()); $display = $this->withoutInteraction()->runCommand($this->command, ['--user' => 123456]); diff --git a/tests/Unit/Commands/User/DisableTwoFactorCommandTest.php b/tests/Unit/Commands/User/DisableTwoFactorCommandTest.php index 577dd0275..d741e8be4 100644 --- a/tests/Unit/Commands/User/DisableTwoFactorCommandTest.php +++ b/tests/Unit/Commands/User/DisableTwoFactorCommandTest.php @@ -47,7 +47,7 @@ class DisableTwoFactorCommandTest extends CommandTestCase { $user = factory(User::class)->make(); - $this->repository->shouldReceive('withColumns')->with(['id', 'email'])->once()->andReturnSelf() + $this->repository->shouldReceive('setColumns')->with(['id', 'email'])->once()->andReturnSelf() ->shouldReceive('findFirstWhere')->with([['email', '=', $user->email]])->once()->andReturn($user); $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($user->id, [ @@ -68,7 +68,7 @@ class DisableTwoFactorCommandTest extends CommandTestCase { $user = factory(User::class)->make(); - $this->repository->shouldReceive('withColumns')->with(['id', 'email'])->once()->andReturnSelf() + $this->repository->shouldReceive('setColumns')->with(['id', 'email'])->once()->andReturnSelf() ->shouldReceive('findFirstWhere')->with([['email', '=', $user->email]])->once()->andReturn($user); $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($user->id, [ diff --git a/tests/Unit/Http/Controllers/Admin/DatabaseControllerTest.php b/tests/Unit/Http/Controllers/Admin/DatabaseControllerTest.php index 62b66d0bb..108198bde 100644 --- a/tests/Unit/Http/Controllers/Admin/DatabaseControllerTest.php +++ b/tests/Unit/Http/Controllers/Admin/DatabaseControllerTest.php @@ -11,6 +11,7 @@ namespace Tests\Unit\Http\Controllers\Admin; use Mockery as m; use Tests\TestCase; +use Pterodactyl\Models\DatabaseHost; use Prologue\Alerts\AlertsMessageBag; use Tests\Assertions\ControllerAssertionsTrait; use Pterodactyl\Http\Controllers\Admin\DatabaseController; @@ -74,8 +75,8 @@ class DatabaseControllerTest extends TestCase */ public function testIndexController() { - $this->locationRepository->shouldReceive('getAllWithNodes')->withNoArgs()->once()->andReturn('getAllWithNodes'); - $this->repository->shouldReceive('getWithViewDetails')->withNoArgs()->once()->andReturn('getWithViewDetails'); + $this->locationRepository->shouldReceive('getAllWithNodes')->withNoArgs()->once()->andReturn(collect(['getAllWithNodes'])); + $this->repository->shouldReceive('getWithViewDetails')->withNoArgs()->once()->andReturn(collect(['getWithViewDetails'])); $response = $this->getController()->index(); @@ -83,8 +84,8 @@ class DatabaseControllerTest extends TestCase $this->assertViewNameEquals('admin.databases.index', $response); $this->assertViewHasKey('locations', $response); $this->assertViewHasKey('hosts', $response); - $this->assertViewKeyEquals('locations', 'getAllWithNodes', $response); - $this->assertViewKeyEquals('hosts', 'getWithViewDetails', $response); + $this->assertViewKeyEquals('locations', collect(['getAllWithNodes']), $response); + $this->assertViewKeyEquals('hosts', collect(['getWithViewDetails']), $response); } /** @@ -92,8 +93,10 @@ class DatabaseControllerTest extends TestCase */ public function testViewController() { - $this->locationRepository->shouldReceive('getAllWithNodes')->withNoArgs()->once()->andReturn('getAllWithNodes'); - $this->repository->shouldReceive('getWithServers')->with(1)->once()->andReturn('getWithServers'); + $model = factory(DatabaseHost::class)->make(); + + $this->locationRepository->shouldReceive('getAllWithNodes')->withNoArgs()->once()->andReturn(collect(['getAllWithNodes'])); + $this->repository->shouldReceive('getWithServers')->with(1)->once()->andReturn($model); $response = $this->getController()->view(1); @@ -101,8 +104,8 @@ class DatabaseControllerTest extends TestCase $this->assertViewNameEquals('admin.databases.view', $response); $this->assertViewHasKey('locations', $response); $this->assertViewHasKey('host', $response); - $this->assertViewKeyEquals('locations', 'getAllWithNodes', $response); - $this->assertViewKeyEquals('host', 'getWithServers', $response); + $this->assertViewKeyEquals('locations', collect(['getAllWithNodes']), $response); + $this->assertViewKeyEquals('host', $model, $response); } /** diff --git a/tests/Unit/Http/Controllers/Base/APIControllerTest.php b/tests/Unit/Http/Controllers/Base/APIControllerTest.php index 579fb43bb..e356c3910 100644 --- a/tests/Unit/Http/Controllers/Base/APIControllerTest.php +++ b/tests/Unit/Http/Controllers/Base/APIControllerTest.php @@ -46,15 +46,15 @@ class APIControllerTest extends ControllerTestCase */ public function testIndexController() { - $model = $this->setRequestUser(); + $model = $this->generateRequestUserModel(); - $this->repository->shouldReceive('findWhere')->with([['user_id', '=', $model->id]])->once()->andReturn(['testkeys']); + $this->repository->shouldReceive('findWhere')->with([['user_id', '=', $model->id]])->once()->andReturn(collect(['testkeys'])); $response = $this->getController()->index($this->request); $this->assertIsViewResponse($response); $this->assertViewNameEquals('base.api.index', $response); $this->assertViewHasKey('keys', $response); - $this->assertViewKeyEquals('keys', ['testkeys'], $response); + $this->assertViewKeyEquals('keys', collect(['testkeys']), $response); } /** @@ -64,7 +64,7 @@ class APIControllerTest extends ControllerTestCase */ public function testCreateController($admin) { - $this->setRequestUser(factory(User::class)->make(['root_admin' => $admin])); + $this->generateRequestUserModel(['root_admin' => $admin]); $response = $this->getController()->create($this->request); $this->assertIsViewResponse($response); @@ -87,7 +87,7 @@ class APIControllerTest extends ControllerTestCase public function testStoreController($admin) { $this->setRequestMockClass(ApiKeyFormRequest::class); - $model = $this->setRequestUser(factory(User::class)->make(['root_admin' => $admin])); + $model = $this->generateRequestUserModel(['root_admin' => $admin]); $keyModel = factory(APIKey::class)->make(); if ($admin) { @@ -118,12 +118,12 @@ class APIControllerTest extends ControllerTestCase */ public function testRevokeController() { - $model = $this->setRequestUser(); + $model = $this->generateRequestUserModel(); $this->repository->shouldReceive('deleteWhere')->with([ ['user_id', '=', $model->id], ['token', '=', 'testKey123'], - ])->once()->andReturnNull(); + ])->once()->andReturn(1); $response = $this->getController()->revoke($this->request, 'testKey123'); $this->assertIsResponse($response); diff --git a/tests/Unit/Http/Controllers/Base/IndexControllerTest.php b/tests/Unit/Http/Controllers/Base/IndexControllerTest.php index 7245e9662..8dab9007a 100644 --- a/tests/Unit/Http/Controllers/Base/IndexControllerTest.php +++ b/tests/Unit/Http/Controllers/Base/IndexControllerTest.php @@ -15,6 +15,7 @@ use Pterodactyl\Models\Server; use Tests\Assertions\ControllerAssertionsTrait; use Tests\Unit\Http\Controllers\ControllerTestCase; use Pterodactyl\Http\Controllers\Base\IndexController; +use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Pterodactyl\Services\DaemonKeys\DaemonKeyProviderService; use Pterodactyl\Contracts\Repository\ServerRepositoryInterface; use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface as DaemonServerRepositoryInterface; @@ -62,19 +63,19 @@ class IndexControllerTest extends ControllerTestCase */ public function testIndexController() { - $model = $this->setRequestUser(); + $paginator = m::mock(LengthAwarePaginator::class); + $model = $this->generateRequestUserModel(); $this->request->shouldReceive('input')->with('query')->once()->andReturn('searchTerm'); - $this->repository->shouldReceive('search')->with('searchTerm')->once()->andReturnSelf() - ->shouldReceive('filterUserAccessServers')->with( - $model->id, $model->root_admin, 'all', ['user'] - )->once()->andReturn(['test']); + $this->repository->shouldReceive('setSearchTerm')->with('searchTerm')->once()->andReturnSelf() + ->shouldReceive('filterUserAccessServers')->with($model, User::FILTER_LEVEL_ALL) + ->once()->andReturn($paginator); $response = $this->controller->getIndex($this->request); $this->assertIsViewResponse($response); $this->assertViewNameEquals('base.index', $response); $this->assertViewHasKey('servers', $response); - $this->assertViewKeyEquals('servers', ['test'], $response); + $this->assertViewKeyEquals('servers', $paginator, $response); } /** @@ -82,7 +83,7 @@ class IndexControllerTest extends ControllerTestCase */ public function testStatusController() { - $user = $this->setRequestUser(); + $user = $this->generateRequestUserModel(); $server = factory(Server::class)->make(['suspended' => 0, 'installed' => 1]); $this->repository->shouldReceive('findFirstWhere')->with([['uuidShort', '=', $server->uuidShort]])->once()->andReturn($server); @@ -105,7 +106,7 @@ class IndexControllerTest extends ControllerTestCase */ public function testStatusControllerWhenServerNotInstalled() { - $user = $this->setRequestUser(); + $user = $this->generateRequestUserModel(); $server = factory(Server::class)->make(['suspended' => 0, 'installed' => 0]); $this->repository->shouldReceive('findFirstWhere')->with([['uuidShort', '=', $server->uuidShort]])->once()->andReturn($server); diff --git a/tests/Unit/Http/Controllers/Base/SecurityControllerTest.php b/tests/Unit/Http/Controllers/Base/SecurityControllerTest.php index 7c698a597..72435791b 100644 --- a/tests/Unit/Http/Controllers/Base/SecurityControllerTest.php +++ b/tests/Unit/Http/Controllers/Base/SecurityControllerTest.php @@ -61,13 +61,13 @@ class SecurityControllerTest extends ControllerTestCase $model = $this->generateRequestUserModel(); $this->config->shouldReceive('get')->with('session.driver')->once()->andReturn('database'); - $this->repository->shouldReceive('getUserSessions')->with($model->id)->once()->andReturn(['sessions']); + $this->repository->shouldReceive('getUserSessions')->with($model->id)->once()->andReturn(collect(['sessions'])); $response = $this->getController()->index($this->request); $this->assertIsViewResponse($response); $this->assertViewNameEquals('base.security', $response); $this->assertViewHasKey('sessions', $response); - $this->assertViewKeyEquals('sessions', ['sessions'], $response); + $this->assertViewKeyEquals('sessions', collect(['sessions']), $response); } /** diff --git a/tests/Unit/Http/Controllers/Server/Files/FileActionsControllerTest.php b/tests/Unit/Http/Controllers/Server/Files/FileActionsControllerTest.php index 077cf02d9..f6d8cac0c 100644 --- a/tests/Unit/Http/Controllers/Server/Files/FileActionsControllerTest.php +++ b/tests/Unit/Http/Controllers/Server/Files/FileActionsControllerTest.php @@ -103,7 +103,7 @@ class FileActionsControllerTest extends ControllerTestCase ->shouldReceive('setAccessToken')->with('abc123')->once()->andReturnSelf() ->shouldReceive('getContent')->with($file)->once()->andReturn('file contents'); - $response = $controller->update($this->request, '1234', $file); + $response = $controller->view($this->request, '1234', $file); $this->assertIsViewResponse($response); $this->assertViewNameEquals('server.files.edit', $response); $this->assertViewHasKey('file', $response); @@ -134,7 +134,7 @@ class FileActionsControllerTest extends ControllerTestCase $this->repository->shouldReceive('setNode')->with($server->node_id)->once()->andThrow($this->getExceptionMock()); try { - $controller->update($this->request, '1234', 'file.txt'); + $controller->view($this->request, '1234', 'file.txt'); } catch (PterodactylException $exception) { $this->assertInstanceOf(DaemonConnectionException::class, $exception); $this->assertInstanceOf(RequestException::class, $exception->getPrevious()); diff --git a/tests/Unit/Http/Controllers/Server/SubuserControllerTest.php b/tests/Unit/Http/Controllers/Server/SubuserControllerTest.php index 6bf6111b6..f9b550cfc 100644 --- a/tests/Unit/Http/Controllers/Server/SubuserControllerTest.php +++ b/tests/Unit/Http/Controllers/Server/SubuserControllerTest.php @@ -76,7 +76,7 @@ class SubuserControllerTest extends ControllerTestCase $this->mockInjectJavascript(); $controller->shouldReceive('authorize')->with('list-subusers', $server)->once()->andReturnNull(); - $this->repository->shouldReceive('findWhere')->with([['server_id', '=', $server->id]])->once()->andReturn([]); + $this->repository->shouldReceive('findWhere')->with([['server_id', '=', $server->id]])->once()->andReturn(collect()); $response = $controller->index($this->request); $this->assertIsViewResponse($response); diff --git a/tests/Unit/Http/Middleware/DaemonAuthenticateTest.php b/tests/Unit/Http/Middleware/DaemonAuthenticateTest.php index f6531bfbc..861e2724c 100644 --- a/tests/Unit/Http/Middleware/DaemonAuthenticateTest.php +++ b/tests/Unit/Http/Middleware/DaemonAuthenticateTest.php @@ -34,7 +34,7 @@ class DaemonAuthenticateTest extends MiddlewareTestCase $this->request->shouldReceive('route->getName')->withNoArgs()->once()->andReturn('random.name'); $this->request->shouldReceive('header')->with('X-Access-Node')->twice()->andReturn($node->uuid); - $this->repository->shouldReceive('findWhere')->with(['daemonSecret' => $node->uuid])->once()->andReturn($node); + $this->repository->shouldReceive('findFirstWhere')->with(['daemonSecret' => $node->uuid])->once()->andReturn($node); $this->getMiddleware()->handle($this->request, $this->getClosureAssertions()); $this->assertRequestHasAttribute('node'); diff --git a/tests/Unit/Repositories/Eloquent/AllocationRepositoryTest.php b/tests/Unit/Repositories/Eloquent/AllocationRepositoryTest.php deleted file mode 100644 index a316fc61c..000000000 --- a/tests/Unit/Repositories/Eloquent/AllocationRepositoryTest.php +++ /dev/null @@ -1,72 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Tests\Unit\Repositories\Eloquent; - -use Mockery as m; -use Tests\TestCase; -use Pterodactyl\Models\Allocation; -use Illuminate\Database\Eloquent\Builder; -use Pterodactyl\Repositories\Eloquent\AllocationRepository; - -class AllocationRepositoryTest extends TestCase -{ - /** - * @var \Illuminate\Database\Eloquent\Builder - */ - protected $builder; - - /** - * @var \Pterodactyl\Repositories\Eloquent\AllocationRepository - */ - protected $repository; - - /** - * Setup tests. - */ - public function setUp() - { - parent::setUp(); - - $this->builder = m::mock(Builder::class); - $this->repository = m::mock(AllocationRepository::class)->makePartial(); - - $this->repository->shouldReceive('getBuilder')->withNoArgs()->andReturn($this->builder); - } - - /** - * Test that we are returning the correct model. - */ - public function testCorrectModelIsAssigned() - { - $this->assertEquals(Allocation::class, $this->repository->model()); - } - - /** - * Test that allocations can be assigned to a server correctly. - */ - public function testAllocationsAreAssignedToAServer() - { - $this->builder->shouldReceive('whereIn')->with('id', [1, 2])->once()->andReturnSelf() - ->shouldReceive('update')->with(['server_id' => 10])->once()->andReturn(true); - - $this->assertTrue($this->repository->assignAllocationsToServer(10, [1, 2])); - } - - /** - * Test that allocations with a node relationship are returned. - */ - public function testAllocationsForANodeAreReturned() - { - $this->builder->shouldReceive('where')->with('node_id', 1)->once()->andReturnSelf() - ->shouldReceive('get')->once()->andReturn(factory(Allocation::class)->make()); - - $this->assertInstanceOf(Allocation::class, $this->repository->getAllocationsForNode(1)); - } -} diff --git a/tests/Unit/Repositories/Eloquent/ApiKeyRepositoryTest.php b/tests/Unit/Repositories/Eloquent/ApiKeyRepositoryTest.php deleted file mode 100644 index e304041ca..000000000 --- a/tests/Unit/Repositories/Eloquent/ApiKeyRepositoryTest.php +++ /dev/null @@ -1,50 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Tests\Unit\Repositories\Eloquent; - -use Mockery as m; -use Tests\TestCase; -use Pterodactyl\Models\APIKey; -use Illuminate\Database\Eloquent\Builder; -use Pterodactyl\Repositories\Eloquent\ApiKeyRepository; - -class ApiKeyRepositoryTest extends TestCase -{ - /** - * @var \Illuminate\Database\Eloquent\Builder - */ - protected $builder; - - /** - * @var \Pterodactyl\Repositories\Eloquent\ApiKeyRepository - */ - protected $repository; - - /** - * Setup tests. - */ - public function setUp() - { - parent::setUp(); - - $this->builder = m::mock(Builder::class); - $this->repository = m::mock(ApiKeyRepository::class)->makePartial(); - - $this->repository->shouldReceive('getBuilder')->withNoArgs()->andReturn($this->builder); - } - - /** - * Test that we are returning the correct model. - */ - public function testCorrectModelIsAssigned() - { - $this->assertEquals(APIKey::class, $this->repository->model()); - } -} diff --git a/tests/Unit/Repositories/Eloquent/ApiPermissionRepositoryTest.php b/tests/Unit/Repositories/Eloquent/ApiPermissionRepositoryTest.php deleted file mode 100644 index d1641f04f..000000000 --- a/tests/Unit/Repositories/Eloquent/ApiPermissionRepositoryTest.php +++ /dev/null @@ -1,50 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Tests\Unit\Repositories\Eloquent; - -use Mockery as m; -use Tests\TestCase; -use Pterodactyl\Models\APIPermission; -use Illuminate\Database\Eloquent\Builder; -use Pterodactyl\Repositories\Eloquent\ApiPermissionRepository; - -class ApiPermissionRepositoryTest extends TestCase -{ - /** - * @var \Illuminate\Database\Eloquent\Builder - */ - protected $builder; - - /** - * @var \Pterodactyl\Repositories\Eloquent\ApiPermissionRepository - */ - protected $repository; - - /** - * Setup tests. - */ - public function setUp() - { - parent::setUp(); - - $this->builder = m::mock(Builder::class); - $this->repository = m::mock(ApiPermissionRepository::class)->makePartial(); - - $this->repository->shouldReceive('getBuilder')->withNoArgs()->andReturn($this->builder); - } - - /** - * Test that we are returning the correct model. - */ - public function testCorrectModelIsAssigned() - { - $this->assertEquals(APIPermission::class, $this->repository->model()); - } -} diff --git a/tests/Unit/Repositories/Eloquent/DatabaseHostRepositoryTest.php b/tests/Unit/Repositories/Eloquent/DatabaseHostRepositoryTest.php deleted file mode 100644 index 94c9486b4..000000000 --- a/tests/Unit/Repositories/Eloquent/DatabaseHostRepositoryTest.php +++ /dev/null @@ -1,88 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Tests\Unit\Repositories\Eloquent; - -use Mockery as m; -use Tests\TestCase; -use Pterodactyl\Models\DatabaseHost; -use Illuminate\Database\Eloquent\Builder; -use Pterodactyl\Repositories\Eloquent\DatabaseHostRepository; - -class DatabaseHostRepositoryTest extends TestCase -{ - /** - * @var \Illuminate\Database\Eloquent\Builder - */ - protected $builder; - - /** - * @var \Pterodactyl\Repositories\Eloquent\DatabaseHostRepository - */ - protected $repository; - - /** - * Setup tests. - */ - public function setUp() - { - parent::setUp(); - - $this->builder = m::mock(Builder::class); - $this->repository = m::mock(DatabaseHostRepository::class)->makePartial(); - - $this->repository->shouldReceive('getBuilder')->withNoArgs()->andReturn($this->builder); - } - - /** - * Test that we are returning the correct model. - */ - public function testCorrectModelIsAssigned() - { - $this->assertEquals(DatabaseHost::class, $this->repository->model()); - } - - /** - * Test query to reutrn all of the default view data. - */ - public function testHostWithDefaultViewDataIsReturned() - { - $this->builder->shouldReceive('withCount')->with('databases')->once()->andReturnSelf() - ->shouldReceive('with')->with('node')->once()->andReturnSelf() - ->shouldReceive('get')->withNoArgs()->once()->andReturnNull(); - - $this->assertNull($this->repository->getWithViewDetails()); - } - - /** - * Test query to return host and servers. - */ - public function testHostIsReturnedWithServers() - { - $model = factory(DatabaseHost::class)->make(); - - $this->builder->shouldReceive('with')->with('databases.server')->once()->andReturnSelf() - ->shouldReceive('find')->with(1, ['*'])->once()->andReturn($model); - - $this->assertEquals($model, $this->repository->getWithServers(1)); - } - - /** - * Test exception is found if no host is found when querying for servers. - * - * @expectedException \Pterodactyl\Exceptions\Repository\RecordNotFoundException - */ - public function testExceptionIsThrownIfNoRecordIsFoundWithServers() - { - $this->builder->shouldReceive('with')->with('databases.server')->once()->andReturnSelf() - ->shouldReceive('find')->with(1, ['*'])->once()->andReturnNull(); - - $this->repository->getWithServers(1); - } -} diff --git a/tests/Unit/Repositories/Eloquent/DatabaseRepositoryTest.php b/tests/Unit/Repositories/Eloquent/DatabaseRepositoryTest.php deleted file mode 100644 index 4a7f0ccc3..000000000 --- a/tests/Unit/Repositories/Eloquent/DatabaseRepositoryTest.php +++ /dev/null @@ -1,157 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Tests\Unit\Repositories\Eloquent; - -use Mockery as m; -use Tests\TestCase; -use Pterodactyl\Models\Database; -use Illuminate\Database\Eloquent\Builder; -use Pterodactyl\Exceptions\DisplayException; -use Pterodactyl\Repositories\Eloquent\DatabaseRepository; -use Pterodactyl\Exceptions\Repository\DuplicateDatabaseNameException; - -class DatabaseRepositoryTest extends TestCase -{ - /** - * @var \Illuminate\Database\Eloquent\Builder - */ - protected $builder; - - /** - * @var \Pterodactyl\Repositories\Eloquent\DatabaseRepository - */ - protected $repository; - - /** - * Setup tests. - */ - public function setUp() - { - parent::setUp(); - - $this->builder = m::mock(Builder::class); - $this->repository = m::mock(DatabaseRepository::class)->makePartial()->shouldAllowMockingProtectedMethods(); - - $this->repository->shouldReceive('getBuilder')->withNoArgs()->andReturn($this->builder); - $this->repository->shouldNotReceive('runStatement'); - } - - /** - * Test that we are returning the correct model. - */ - public function testCorrectModelIsAssigned() - { - $this->assertEquals(Database::class, $this->repository->model()); - } - - /** - * Test that a database can be created if it does not already exist. - */ - public function testDatabaseIsCreatedIfNotExists() - { - $data = [ - 'server_id' => 1, - 'database_host_id' => 100, - 'database' => 'somename', - ]; - - $this->builder->shouldReceive('where')->with([ - ['server_id', '=', array_get($data, 'server_id')], - ['database_host_id', '=', array_get($data, 'database_host_id')], - ['database', '=', array_get($data, 'database')], - ])->once()->andReturnSelf() - ->shouldReceive('count')->withNoArgs()->once()->andReturn(0); - - $this->repository->shouldReceive('create')->with($data)->once()->andReturn(true); - - $this->assertTrue($this->repository->createIfNotExists($data)); - } - - /** - * Test that an exception is thrown if a database already exists with the given name. - */ - public function testExceptionIsThrownIfDatabaseAlreadyExists() - { - $this->builder->shouldReceive('where->count')->once()->andReturn(1); - $this->repository->shouldNotReceive('create'); - - try { - $this->repository->createIfNotExists([]); - } catch (DisplayException $exception) { - $this->assertInstanceOf(DuplicateDatabaseNameException::class, $exception); - $this->assertEquals('A database with those details already exists for the specified server.', $exception->getMessage()); - } - } - - /** - * Test SQL used to create a database. - */ - public function testCreateDatabaseStatement() - { - $query = sprintf('CREATE DATABASE IF NOT EXISTS `%s`', 'test_database'); - $this->repository->shouldReceive('runStatement')->with($query)->once()->andReturn(true); - - $this->assertTrue($this->repository->createDatabase('test_database', 'test')); - } - - /** - * Test SQL used to create a user. - */ - public function testCreateUserStatement() - { - $query = sprintf('CREATE USER `%s`@`%s` IDENTIFIED BY \'%s\'', 'test', '%', 'password'); - $this->repository->shouldReceive('runStatement')->with($query)->once()->andReturn(true); - - $this->assertTrue($this->repository->createUser('test', '%', 'password', 'test')); - } - - /** - * Test that a user is assigned the correct permissions on a database. - */ - public function testUserAssignmentToDatabaseStatement() - { - $query = sprintf('GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX, EXECUTE ON `%s`.* TO `%s`@`%s`', 'test_database', 'test', '%'); - $this->repository->shouldReceive('runStatement')->with($query)->once()->andReturn(true); - - $this->assertTrue($this->repository->assignUserToDatabase('test_database', 'test', '%', 'test')); - } - - /** - * Test SQL for flushing privileges. - */ - public function testFlushStatement() - { - $this->repository->shouldReceive('runStatement')->with('FLUSH PRIVILEGES')->once()->andReturn(true); - - $this->assertTrue($this->repository->flush('test')); - } - - /** - * Test SQL to drop a database. - */ - public function testDropDatabaseStatement() - { - $query = sprintf('DROP DATABASE IF EXISTS `%s`', 'test_database'); - $this->repository->shouldReceive('runStatement')->with($query)->once()->andReturn(true); - - $this->assertTrue($this->repository->dropDatabase('test_database', 'test')); - } - - /** - * Test SQL to drop a user. - */ - public function testDropUserStatement() - { - $query = sprintf('DROP USER IF EXISTS `%s`@`%s`', 'test', '%'); - $this->repository->shouldReceive('runStatement')->with($query)->once()->andReturn(true); - - $this->assertTrue($this->repository->dropUser('test', '%', 'test')); - } -} diff --git a/tests/Unit/Repositories/Eloquent/LocationRepositoryTest.php b/tests/Unit/Repositories/Eloquent/LocationRepositoryTest.php deleted file mode 100644 index a245e2a9e..000000000 --- a/tests/Unit/Repositories/Eloquent/LocationRepositoryTest.php +++ /dev/null @@ -1,100 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Tests\Unit\Repositories\Eloquent; - -use Mockery as m; -use Tests\TestCase; -use Pterodactyl\Models\Location; -use Illuminate\Database\Eloquent\Builder; -use Pterodactyl\Repositories\Eloquent\LocationRepository; - -class LocationRepositoryTest extends TestCase -{ - /** - * @var \Illuminate\Database\Eloquent\Builder - */ - protected $builder; - - /** - * @var \Pterodactyl\Repositories\Eloquent\LocationRepository - */ - protected $repository; - - /** - * Setup tests. - */ - public function setUp() - { - parent::setUp(); - - $this->builder = m::mock(Builder::class); - $this->repository = m::mock(LocationRepository::class)->makePartial(); - - $this->repository->shouldReceive('getBuilder')->withNoArgs()->andReturn($this->builder); - } - - /** - * Test that we are returning the correct model. - */ - public function testCorrectModelIsAssigned() - { - $this->assertEquals(Location::class, $this->repository->model()); - } - - /** - * Test that all locations with associated node and server counts are returned. - */ - public function testAllLocationsWithDetailsAreReturned() - { - $this->builder->shouldReceive('withCount')->with('nodes', 'servers')->once()->andReturnSelf() - ->shouldReceive('get')->with(['*'])->once()->andReturnNull(); - - $this->assertNull($this->repository->getAllWithDetails()); - } - - /** - * Test that all locations with associated node are returned. - */ - public function testAllLocationsWithNodes() - { - $this->builder->shouldReceive('with')->with('nodes')->once()->andReturnSelf() - ->shouldReceive('get')->with(['*'])->once()->andReturnNull(); - - $this->assertNull($this->repository->getAllWithNodes()); - } - - /** - * Test that a single location with associated node is returned. - */ - public function testLocationWithNodeIsReturned() - { - $model = factory(Location::class)->make(); - - $this->builder->shouldReceive('with')->with('nodes.servers')->once()->andReturnSelf() - ->shouldReceive('find')->with(1, ['*'])->once()->andReturn($model); - - $response = $this->repository->getWithNodes(1); - $this->assertInstanceOf(Location::class, $response); - $this->assertEquals($model, $response); - } - - /** - * Test that an exception is thrown when getting location with nodes if no location is found. - * - * @expectedException \Pterodactyl\Exceptions\Repository\RecordNotFoundException - */ - public function testExceptionIsThrownIfNoLocationIsFoundWithNodes() - { - $this->builder->shouldReceive('with')->with('nodes.servers')->once()->andReturnSelf() - ->shouldReceive('find')->with(1, ['*'])->once()->andReturnNull(); - - $this->repository->getWithNodes(1); - } -} diff --git a/tests/Unit/Services/Allocations/AssignmentServiceTest.php b/tests/Unit/Services/Allocations/AssignmentServiceTest.php index 7f91955d5..805b789a3 100644 --- a/tests/Unit/Services/Allocations/AssignmentServiceTest.php +++ b/tests/Unit/Services/Allocations/AssignmentServiceTest.php @@ -84,7 +84,7 @@ class AssignmentServiceTest extends TestCase 'ip_alias' => null, 'server_id' => null, ], - ])->once()->andReturnNull(); + ])->once()->andReturn(true); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->handle($this->node->id, $data); @@ -123,7 +123,7 @@ class AssignmentServiceTest extends TestCase 'ip_alias' => null, 'server_id' => null, ], - ])->once()->andReturnNull(); + ])->once()->andReturn(true); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->handle($this->node->id, $data); @@ -149,7 +149,7 @@ class AssignmentServiceTest extends TestCase 'ip_alias' => 'my.alias.net', 'server_id' => null, ], - ])->once()->andReturnNull(); + ])->once()->andReturn(true); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->handle($this->node->id, $data); @@ -177,7 +177,7 @@ class AssignmentServiceTest extends TestCase 'ip_alias' => null, 'server_id' => null, ], - ])->once()->andReturnNull(); + ])->once()->andReturn(true); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->handle($this->node->id, $data); @@ -202,7 +202,7 @@ class AssignmentServiceTest extends TestCase 'ip_alias' => null, 'server_id' => null, ], - ])->once()->andReturnNull(); + ])->once()->andReturn(true); $this->repository->shouldReceive('insertIgnore')->with([ [ @@ -212,7 +212,7 @@ class AssignmentServiceTest extends TestCase 'ip_alias' => null, 'server_id' => null, ], - ])->once()->andReturnNull(); + ])->once()->andReturn(true); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->handle($this->node->id, $data); @@ -303,7 +303,7 @@ class AssignmentServiceTest extends TestCase 'ip_alias' => null, 'server_id' => null, ], - ])->once()->andReturnNull(); + ])->once()->andReturn(true); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->handle($this->node, $data); diff --git a/tests/Unit/Services/DaemonKeys/DaemonKeyDeletionServiceTest.php b/tests/Unit/Services/DaemonKeys/DaemonKeyDeletionServiceTest.php index 85067bf9e..558c1eb45 100644 --- a/tests/Unit/Services/DaemonKeys/DaemonKeyDeletionServiceTest.php +++ b/tests/Unit/Services/DaemonKeys/DaemonKeyDeletionServiceTest.php @@ -97,7 +97,7 @@ class DaemonKeyDeletionServiceTest extends TestCase ['server_id', '=', $server->id], ])->once()->andReturn($key); - $this->repository->shouldReceive('delete')->with($key->id)->once()->andReturnNull(); + $this->repository->shouldReceive('delete')->with($key->id)->once()->andReturn(1); $this->daemonRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf() ->shouldReceive('revokeAccessKey')->with($key->secret)->once()->andReturnNull(); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); @@ -121,7 +121,7 @@ class DaemonKeyDeletionServiceTest extends TestCase ['server_id', '=', $server->id], ])->once()->andReturn($key); - $this->repository->shouldReceive('delete')->with($key->id)->once()->andReturnNull(); + $this->repository->shouldReceive('delete')->with($key->id)->once()->andReturn(1); $this->daemonRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf() ->shouldReceive('revokeAccessKey')->with($key->secret)->once()->andReturnNull(); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); @@ -144,7 +144,7 @@ class DaemonKeyDeletionServiceTest extends TestCase ['server_id', '=', $server->id], ])->once()->andReturn($key); - $this->repository->shouldReceive('delete')->with($key->id)->once()->andReturnNull(); + $this->repository->shouldReceive('delete')->with($key->id)->once()->andReturn(1); $this->daemonRepository->shouldReceive('setNode')->with($server->node_id)->once()->andThrow($this->exception); $this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnNull(); $this->connection->shouldReceive('rollBack')->withNoArgs()->once()->andReturnNull(); diff --git a/tests/Unit/Services/Databases/DatabasePasswordServiceTest.php b/tests/Unit/Services/Databases/DatabasePasswordServiceTest.php index 54d46b950..2388e2d34 100644 --- a/tests/Unit/Services/Databases/DatabasePasswordServiceTest.php +++ b/tests/Unit/Services/Databases/DatabasePasswordServiceTest.php @@ -66,11 +66,11 @@ class DatabasePasswordServiceTest extends TestCase $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf(); $this->repository->shouldReceive('update')->with($model->id, ['password' => 'enc123'])->once()->andReturn(true); - $this->repository->shouldReceive('dropUser')->with($model->username, $model->remote)->once()->andReturnNull(); - $this->repository->shouldReceive('createUser')->with($model->username, $model->remote, 'test123')->once()->andReturnNull(); - $this->repository->shouldReceive('assignUserToDatabase')->with($model->database, $model->username, $model->remote)->once()->andReturnNull(); - $this->repository->shouldReceive('flush')->withNoArgs()->once()->andReturnNull(); - $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); + $this->repository->shouldReceive('dropUser')->with($model->username, $model->remote)->once()->andReturn(true); + $this->repository->shouldReceive('createUser')->with($model->username, $model->remote, 'test123')->once()->andReturn(true); + $this->repository->shouldReceive('assignUserToDatabase')->with($model->database, $model->username, $model->remote)->once()->andReturn(true); + $this->repository->shouldReceive('flush')->withNoArgs()->once()->andReturn(true); + $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturn(true); $response = $this->getService()->handle($useModel ? $model : 1234, 'test123'); $this->assertNotEmpty($response); diff --git a/tests/Unit/Services/Eggs/EggUpdateServiceTest.php b/tests/Unit/Services/Eggs/EggUpdateServiceTest.php index 89f02c49c..db548b962 100644 --- a/tests/Unit/Services/Eggs/EggUpdateServiceTest.php +++ b/tests/Unit/Services/Eggs/EggUpdateServiceTest.php @@ -9,7 +9,6 @@ namespace Tests\Unit\Services\Services\Options; -use Exception; use Mockery as m; use Tests\TestCase; use Pterodactyl\Models\Egg; diff --git a/tests/Unit/Services/Eggs/Sharing/EggUpdateImporterServiceTest.php b/tests/Unit/Services/Eggs/Sharing/EggUpdateImporterServiceTest.php index 28bbdc4a8..df95ee214 100644 --- a/tests/Unit/Services/Eggs/Sharing/EggUpdateImporterServiceTest.php +++ b/tests/Unit/Services/Eggs/Sharing/EggUpdateImporterServiceTest.php @@ -86,8 +86,8 @@ class EggUpdateImporterServiceTest extends TestCase 'env_variable' => $variable->env_variable, ], collect($variable)->except(['egg_id', 'env_variable'])->toArray())->once()->andReturnNull(); - $this->variableRepository->shouldReceive('withColumns')->with(['id', 'env_variable'])->once()->andReturnSelf() - ->shouldReceive('findWhere')->with([['egg_id', '=', $egg->id]])->once()->andReturn([$variable]); + $this->variableRepository->shouldReceive('setColumns')->with(['id', 'env_variable'])->once()->andReturnSelf() + ->shouldReceive('findWhere')->with([['egg_id', '=', $egg->id]])->once()->andReturn(collect([$variable])); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); @@ -126,13 +126,13 @@ class EggUpdateImporterServiceTest extends TestCase 'env_variable' => $variable1->env_variable, ], collect($variable1)->except(['egg_id', 'env_variable'])->toArray())->once()->andReturnNull(); - $this->variableRepository->shouldReceive('withColumns')->with(['id', 'env_variable'])->once()->andReturnSelf() - ->shouldReceive('findWhere')->with([['egg_id', '=', $egg->id]])->once()->andReturn([$variable1, $variable2]); + $this->variableRepository->shouldReceive('setColumns')->with(['id', 'env_variable'])->once()->andReturnSelf() + ->shouldReceive('findWhere')->with([['egg_id', '=', $egg->id]])->once()->andReturn(collect([$variable1, $variable2])); $this->variableRepository->shouldReceive('deleteWhere')->with([ ['egg_id', '=', $egg->id], ['env_variable', '=', $variable2->env_variable], - ])->once()->andReturnNull(); + ])->once()->andReturn(1); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); diff --git a/tests/Unit/Services/Eggs/Variables/VariableUpdateServiceTest.php b/tests/Unit/Services/Eggs/Variables/VariableUpdateServiceTest.php index bf1f209ae..84d082b33 100644 --- a/tests/Unit/Services/Eggs/Variables/VariableUpdateServiceTest.php +++ b/tests/Unit/Services/Eggs/Variables/VariableUpdateServiceTest.php @@ -76,7 +76,7 @@ class VariableUpdateServiceTest extends TestCase */ public function testVariableIsUpdatedWhenValidEnvironmentVariableIsPassed() { - $this->repository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->repository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findCountWhere')->with([ ['env_variable', '=', 'TEST_VAR_123'], ['egg_id', '=', $this->model->option_id], @@ -116,7 +116,7 @@ class VariableUpdateServiceTest extends TestCase */ public function testDataPassedIntoHandlerTakesLowerPriorityThanDataSet() { - $this->repository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->repository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findCountWhere')->with([ ['env_variable', '=', 'TEST_VAR_123'], ['egg_id', '=', $this->model->option_id], @@ -138,7 +138,7 @@ class VariableUpdateServiceTest extends TestCase */ public function testExceptionIsThrownIfEnvironmentVariableIsNotUnique() { - $this->repository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->repository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findCountWhere')->with([ ['env_variable', '=', 'TEST_VAR_123'], ['egg_id', '=', $this->model->option_id], diff --git a/tests/Unit/Services/Nodes/NodeDeletionServiceTest.php b/tests/Unit/Services/Nodes/NodeDeletionServiceTest.php index 5c0a44878..a7ae2df05 100644 --- a/tests/Unit/Services/Nodes/NodeDeletionServiceTest.php +++ b/tests/Unit/Services/Nodes/NodeDeletionServiceTest.php @@ -62,14 +62,11 @@ class NodeDeletionServiceTest extends TestCase */ public function testNodeIsDeletedIfNoServersAreAttached() { - $this->serverRepository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->serverRepository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findCountWhere')->with([['node_id', '=', 1]])->once()->andReturn(0); - $this->repository->shouldReceive('delete')->with(1)->once()->andReturn(true); + $this->repository->shouldReceive('delete')->with(1)->once()->andReturn(1); - $this->assertTrue( - $this->service->handle(1), - 'Assert that deletion returns a positive boolean value.' - ); + $this->assertEquals(1, $this->service->handle(1)); } /** @@ -79,7 +76,7 @@ class NodeDeletionServiceTest extends TestCase */ public function testExceptionIsThrownIfServersAreAttachedToNode() { - $this->serverRepository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->serverRepository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findCountWhere')->with([['node_id', '=', 1]])->once()->andReturn(1); $this->translator->shouldReceive('trans')->with('exceptions.node.servers_attached')->once()->andReturnNull(); $this->repository->shouldNotReceive('delete'); @@ -94,13 +91,10 @@ class NodeDeletionServiceTest extends TestCase { $node = factory(Node::class)->make(); - $this->serverRepository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->serverRepository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findCountWhere')->with([['node_id', '=', $node->id]])->once()->andReturn(0); - $this->repository->shouldReceive('delete')->with($node->id)->once()->andReturn(true); + $this->repository->shouldReceive('delete')->with($node->id)->once()->andReturn(1); - $this->assertTrue( - $this->service->handle($node), - 'Assert that deletion returns a positive boolean value.' - ); + $this->assertEquals(1, $this->service->handle($node)); } } diff --git a/tests/Unit/Services/Packs/PackDeletionServiceTest.php b/tests/Unit/Services/Packs/PackDeletionServiceTest.php index 5c169f3de..75e6684e1 100644 --- a/tests/Unit/Services/Packs/PackDeletionServiceTest.php +++ b/tests/Unit/Services/Packs/PackDeletionServiceTest.php @@ -76,7 +76,7 @@ class PackDeletionServiceTest extends TestCase $this->serverRepository->shouldReceive('findCountWhere')->with([['pack_id', '=', $model->id]])->once()->andReturn(0); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('delete')->with($model->id)->once()->andReturnNull(); + $this->repository->shouldReceive('delete')->with($model->id)->once()->andReturn(1); $this->storage->shouldReceive('disk')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('deleteDirectory')->with('packs/' . $model->uuid)->once()->andReturnNull(); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); @@ -91,11 +91,11 @@ class PackDeletionServiceTest extends TestCase { $model = factory(Pack::class)->make(); - $this->repository->shouldReceive('withColumns')->with(['id', 'uuid'])->once()->andReturnSelf() + $this->repository->shouldReceive('setColumns')->with(['id', 'uuid'])->once()->andReturnSelf() ->shouldReceive('find')->with($model->id)->once()->andReturn($model); $this->serverRepository->shouldReceive('findCountWhere')->with([['pack_id', '=', $model->id]])->once()->andReturn(0); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('delete')->with($model->id)->once()->andReturnNull(); + $this->repository->shouldReceive('delete')->with($model->id)->once()->andReturn(1); $this->storage->shouldReceive('disk')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('deleteDirectory')->with('packs/' . $model->uuid)->once()->andReturnNull(); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); diff --git a/tests/Unit/Services/Packs/PackUpdateServiceTest.php b/tests/Unit/Services/Packs/PackUpdateServiceTest.php index 8a09311f1..7078a003c 100644 --- a/tests/Unit/Services/Packs/PackUpdateServiceTest.php +++ b/tests/Unit/Services/Packs/PackUpdateServiceTest.php @@ -85,7 +85,7 @@ class PackUpdateServiceTest extends TestCase { $model = factory(Pack::class)->make(); - $this->repository->shouldReceive('withColumns')->with(['id', 'egg_id'])->once()->andReturnSelf() + $this->repository->shouldReceive('setColumns')->with(['id', 'egg_id'])->once()->andReturnSelf() ->shouldReceive('find')->with($model->id)->once()->andReturn($model); $this->repository->shouldReceive('withoutFresh->update')->with($model->id, [ 'locked' => false, diff --git a/tests/Unit/Services/Servers/ServerCreationServiceTest.php b/tests/Unit/Services/Servers/ServerCreationServiceTest.php index 4df486d5c..b50ad1d84 100644 --- a/tests/Unit/Services/Servers/ServerCreationServiceTest.php +++ b/tests/Unit/Services/Servers/ServerCreationServiceTest.php @@ -116,7 +116,7 @@ class ServerCreationServiceTest extends TestCase 'egg_id' => $model->egg_id, ]))->once()->andReturn($model); - $this->allocationRepository->shouldReceive('assignAllocationsToServer')->with($model->id, [$model->allocation_id])->once()->andReturnNull(); + $this->allocationRepository->shouldReceive('assignAllocationsToServer')->with($model->id, [$model->allocation_id])->once()->andReturn(1); $this->validatorService->shouldReceive('setUserLevel')->with(User::USER_LEVEL_ADMIN)->once()->andReturnNull(); $this->validatorService->shouldReceive('handle')->with($model->egg_id, [])->once()->andReturn( @@ -129,7 +129,7 @@ class ServerCreationServiceTest extends TestCase 'variable_id' => 123, 'variable_value' => 'var1-value', ], - ])->once()->andReturnNull(); + ])->once()->andReturn(true); $this->configurationStructureService->shouldReceive('handle')->with($model)->once()->andReturn(['test' => 'struct']); $this->daemonServerRepository->shouldReceive('setNode')->with($model->node_id)->once()->andReturnSelf(); @@ -154,7 +154,7 @@ class ServerCreationServiceTest extends TestCase $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); $this->repository->shouldReceive('create')->once()->andReturn($model); - $this->allocationRepository->shouldReceive('assignAllocationsToServer')->once()->andReturnNull(); + $this->allocationRepository->shouldReceive('assignAllocationsToServer')->once()->andReturn(1); $this->validatorService->shouldReceive('setUserLevel')->once()->andReturnNull(); $this->validatorService->shouldReceive('handle')->once()->andReturn(collect([])); $this->configurationStructureService->shouldReceive('handle')->once()->andReturn([]); diff --git a/tests/Unit/Services/Servers/ServerDeletionServiceTest.php b/tests/Unit/Services/Servers/ServerDeletionServiceTest.php index 93fa478f2..26d7fa103 100644 --- a/tests/Unit/Services/Servers/ServerDeletionServiceTest.php +++ b/tests/Unit/Services/Servers/ServerDeletionServiceTest.php @@ -116,13 +116,13 @@ class ServerDeletionServiceTest extends TestCase ->shouldReceive('delete')->withNoArgs()->once()->andReturnNull(); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->databaseRepository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->databaseRepository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findWhere')->with([ ['server_id', '=', $this->model->id], ])->once()->andReturn(collect([(object) ['id' => 50]])); $this->databaseManagementService->shouldReceive('delete')->with(50)->once()->andReturnNull(); - $this->repository->shouldReceive('delete')->with($this->model->id)->once()->andReturnNull(); + $this->repository->shouldReceive('delete')->with($this->model->id)->once()->andReturn(1); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->handle($this->model); @@ -140,13 +140,13 @@ class ServerDeletionServiceTest extends TestCase $this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnNull(); $this->writer->shouldReceive('warning')->with($this->exception)->once()->andReturnNull(); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->databaseRepository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->databaseRepository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findWhere')->with([ ['server_id', '=', $this->model->id], ])->once()->andReturn(collect([(object) ['id' => 50]])); $this->databaseManagementService->shouldReceive('delete')->with(50)->once()->andReturnNull(); - $this->repository->shouldReceive('delete')->with($this->model->id)->once()->andReturnNull(); + $this->repository->shouldReceive('delete')->with($this->model->id)->once()->andReturn(1); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->withForce()->handle($this->model); @@ -176,21 +176,21 @@ class ServerDeletionServiceTest extends TestCase */ public function testIntegerCanBePassedInPlaceOfServerModel() { - $this->repository->shouldReceive('withColumns')->with(['id', 'node_id', 'uuid'])->once()->andReturnSelf() + $this->repository->shouldReceive('setColumns')->with(['id', 'node_id', 'uuid'])->once()->andReturnSelf() ->shouldReceive('find')->with($this->model->id)->once()->andReturn($this->model); $this->daemonServerRepository->shouldReceive('setNode')->with($this->model->node_id)->once()->andReturnSelf() ->shouldReceive('setAccessServer')->with($this->model->uuid)->once()->andReturnSelf() - ->shouldReceive('delete')->withNoArgs()->once()->andReturnNull(); + ->shouldReceive('delete')->withNoArgs()->once()->andReturn(1); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->databaseRepository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->databaseRepository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findWhere')->with([ ['server_id', '=', $this->model->id], ])->once()->andReturn(collect([(object) ['id' => 50]])); $this->databaseManagementService->shouldReceive('delete')->with(50)->once()->andReturnNull(); - $this->repository->shouldReceive('delete')->with($this->model->id)->once()->andReturnNull(); + $this->repository->shouldReceive('delete')->with($this->model->id)->once()->andReturn(1); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->handle($this->model->id); diff --git a/tests/Unit/Services/Sftp/AuthenticateUsingPasswordServiceTest.php b/tests/Unit/Services/Sftp/AuthenticateUsingPasswordServiceTest.php index 904f10a0a..26584522f 100644 --- a/tests/Unit/Services/Sftp/AuthenticateUsingPasswordServiceTest.php +++ b/tests/Unit/Services/Sftp/AuthenticateUsingPasswordServiceTest.php @@ -49,10 +49,10 @@ class AuthenticateUsingPasswordServiceTest extends TestCase $user = factory(User::class)->make(['root_admin' => 0]); $server = factory(Server::class)->make(['node_id' => 1, 'owner_id' => $user->id]); - $this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); + $this->userRepository->shouldReceive('setColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); $this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', $user->username]])->once()->andReturn($user); - $this->repository->shouldReceive('withColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf(); + $this->repository->shouldReceive('setColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf(); $this->repository->shouldReceive('getByUuid')->with($server->uuidShort)->once()->andReturn($server); $this->keyProviderService->shouldReceive('handle')->with($server, $user)->once()->andReturn('server_token'); @@ -74,10 +74,10 @@ class AuthenticateUsingPasswordServiceTest extends TestCase $user = factory(User::class)->make(['root_admin' => 1]); $server = factory(Server::class)->make(['node_id' => 1, 'owner_id' => $user->id + 1]); - $this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); + $this->userRepository->shouldReceive('setColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); $this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', $user->username]])->once()->andReturn($user); - $this->repository->shouldReceive('withColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf(); + $this->repository->shouldReceive('setColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf(); $this->repository->shouldReceive('getByUuid')->with($server->uuidShort)->once()->andReturn($server); $this->keyProviderService->shouldReceive('handle')->with($server, $user)->once()->andReturn('server_token'); @@ -110,7 +110,7 @@ class AuthenticateUsingPasswordServiceTest extends TestCase { $user = factory(User::class)->make(); - $this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); + $this->userRepository->shouldReceive('setColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); $this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', $user->username]])->once()->andReturn($user); $this->getService()->handle($user->username, 'wrongpassword', 1, '1234'); @@ -123,7 +123,7 @@ class AuthenticateUsingPasswordServiceTest extends TestCase */ public function testExceptionIsThrownIfNoUserAccountIsFound() { - $this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); + $this->userRepository->shouldReceive('setColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); $this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', 'something']])->once()->andThrow(new RecordNotFoundException); $this->getService()->handle('something', 'password', 1, '1234'); @@ -140,10 +140,10 @@ class AuthenticateUsingPasswordServiceTest extends TestCase $user = factory(User::class)->make(['root_admin' => 0]); $server = factory(Server::class)->make(['node_id' => 1, 'owner_id' => $user->id + 1]); - $this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); + $this->userRepository->shouldReceive('setColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); $this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', $user->username]])->once()->andReturn($user); - $this->repository->shouldReceive('withColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf(); + $this->repository->shouldReceive('setColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf(); $this->repository->shouldReceive('getByUuid')->with($server->uuidShort)->once()->andReturn($server); $this->getService()->handle($user->username, 'password', 1, $server->uuidShort); @@ -160,10 +160,10 @@ class AuthenticateUsingPasswordServiceTest extends TestCase $user = factory(User::class)->make(['root_admin' => 0]); $server = factory(Server::class)->make(['node_id' => 2, 'owner_id' => $user->id]); - $this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); + $this->userRepository->shouldReceive('setColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf(); $this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', $user->username]])->once()->andReturn($user); - $this->repository->shouldReceive('withColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf(); + $this->repository->shouldReceive('setColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf(); $this->repository->shouldReceive('getByUuid')->with($server->uuidShort)->once()->andReturn($server); $this->getService()->handle($user->username, 'password', 1, $server->uuidShort); diff --git a/tests/Unit/Services/Subusers/PermissionCreationServiceTest.php b/tests/Unit/Services/Subusers/PermissionCreationServiceTest.php index 477cd6c6c..ddfd8c551 100644 --- a/tests/Unit/Services/Subusers/PermissionCreationServiceTest.php +++ b/tests/Unit/Services/Subusers/PermissionCreationServiceTest.php @@ -48,7 +48,7 @@ class PermissionCreationServiceTest extends TestCase ->shouldReceive('insert')->with([ ['subuser_id' => 1, 'permission' => 'reset-sftp'], ['subuser_id' => 1, 'permission' => 'view-sftp'], - ])->once()->andReturnNull(); + ])->once()->andReturn(true); $this->service->handle(1, $permissions); $this->assertTrue(true); diff --git a/tests/Unit/Services/Subusers/SubuserDeletionServiceTest.php b/tests/Unit/Services/Subusers/SubuserDeletionServiceTest.php index ed8c5fab1..b32b272ed 100644 --- a/tests/Unit/Services/Subusers/SubuserDeletionServiceTest.php +++ b/tests/Unit/Services/Subusers/SubuserDeletionServiceTest.php @@ -55,7 +55,7 @@ class SubuserDeletionServiceTest extends TestCase $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); $this->keyDeletionService->shouldReceive('handle')->with($subuser->server_id, $subuser->user_id)->once()->andReturnNull(); - $this->repository->shouldReceive('delete')->with($subuser->id)->once()->andReturnNull(); + $this->repository->shouldReceive('delete')->with($subuser->id)->once()->andReturn(1); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->getService()->handle($subuser); diff --git a/tests/Unit/Services/Subusers/SubuserUpdateServiceTest.php b/tests/Unit/Services/Subusers/SubuserUpdateServiceTest.php index 6b9f8ab32..550411337 100644 --- a/tests/Unit/Services/Subusers/SubuserUpdateServiceTest.php +++ b/tests/Unit/Services/Subusers/SubuserUpdateServiceTest.php @@ -86,7 +86,7 @@ class SubuserUpdateServiceTest extends TestCase $this->repository->shouldReceive('loadServerAndUserRelations')->with($subuser)->once()->andReturn($subuser); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->permissionRepository->shouldReceive('deleteWhere')->with([['subuser_id', '=', $subuser->id]])->once()->andReturnNull(); + $this->permissionRepository->shouldReceive('deleteWhere')->with([['subuser_id', '=', $subuser->id]])->once()->andReturn(1); $this->permissionService->shouldReceive('handle')->with($subuser->id, ['some-permission'])->once()->andReturnNull(); $this->keyProviderService->shouldReceive('handle')->with($subuser->server, $subuser->user, false)->once()->andReturn('test123'); @@ -112,7 +112,7 @@ class SubuserUpdateServiceTest extends TestCase $this->repository->shouldReceive('loadServerAndUserRelations')->with($subuser)->once()->andReturn($subuser); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->permissionRepository->shouldReceive('deleteWhere')->with([['subuser_id', '=', $subuser->id]])->once()->andReturnNull(); + $this->permissionRepository->shouldReceive('deleteWhere')->with([['subuser_id', '=', $subuser->id]])->once()->andReturn(1); $this->permissionService->shouldReceive('handle')->with($subuser->id, [])->once()->andReturnNull(); $this->keyProviderService->shouldReceive('handle')->with($subuser->server, $subuser->user, false)->once()->andReturn('test123'); diff --git a/tests/Unit/Services/Users/UserDeletionServiceTest.php b/tests/Unit/Services/Users/UserDeletionServiceTest.php index 1eed3358a..2876ce147 100644 --- a/tests/Unit/Services/Users/UserDeletionServiceTest.php +++ b/tests/Unit/Services/Users/UserDeletionServiceTest.php @@ -68,14 +68,11 @@ class UserDeletionServiceTest extends TestCase */ public function testUserIsDeletedIfNoServersAreAttachedToAccount() { - $this->serverRepository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->serverRepository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findCountWhere')->with([['owner_id', '=', $this->user->id]])->once()->andReturn(0); - $this->repository->shouldReceive('delete')->with($this->user->id)->once()->andReturn(true); + $this->repository->shouldReceive('delete')->with($this->user->id)->once()->andReturn(1); - $this->assertTrue( - $this->service->handle($this->user->id), - 'Assert that service responds true.' - ); + $this->assertEquals(1, $this->service->handle($this->user->id)); } /** @@ -85,7 +82,7 @@ class UserDeletionServiceTest extends TestCase */ public function testExceptionIsThrownIfServersAreAttachedToAccount() { - $this->serverRepository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->serverRepository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findCountWhere')->with([['owner_id', '=', $this->user->id]])->once()->andReturn(1); $this->translator->shouldReceive('trans')->with('admin/user.exceptions.user_has_servers')->once()->andReturnNull(); @@ -97,13 +94,10 @@ class UserDeletionServiceTest extends TestCase */ public function testModelCanBePassedInPlaceOfUserId() { - $this->serverRepository->shouldReceive('withColumns')->with('id')->once()->andReturnSelf() + $this->serverRepository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() ->shouldReceive('findCountWhere')->with([['owner_id', '=', $this->user->id]])->once()->andReturn(0); - $this->repository->shouldReceive('delete')->with($this->user->id)->once()->andReturn(true); + $this->repository->shouldReceive('delete')->with($this->user->id)->once()->andReturn(1); - $this->assertTrue( - $this->service->handle($this->user), - 'Assert that service responds true.' - ); + $this->assertEquals(1, $this->service->handle($this->user)); } } From 5f9fe4a69b388b5a4e31ddc038d90a3639421695 Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Fri, 5 Jan 2018 16:33:50 -0600 Subject: [PATCH 03/20] Update calls to missing function --- .../Commands/User/DisableTwoFactorCommand.php | 2 +- app/Jobs/Schedule/RunTaskJob.php | 2 +- app/Repositories/Eloquent/ServerRepository.php | 2 +- .../Allocations/SetDefaultAllocationService.php | 2 +- app/Services/Api/PermissionService.php | 2 +- .../DaemonKeys/DaemonKeyCreationService.php | 2 +- app/Services/DaemonKeys/DaemonKeyUpdateService.php | 2 +- app/Services/Databases/DatabasePasswordService.php | 2 +- app/Services/Eggs/EggUpdateService.php | 2 +- app/Services/Eggs/Scripts/InstallScriptService.php | 2 +- .../Eggs/Sharing/EggUpdateImporterService.php | 2 +- .../Eggs/Variables/VariableUpdateService.php | 2 +- app/Services/Nests/NestUpdateService.php | 2 +- app/Services/Nodes/NodeUpdateService.php | 2 +- app/Services/Packs/PackUpdateService.php | 2 +- .../Schedules/Tasks/TaskCreationService.php | 2 +- .../Servers/DetailsModificationService.php | 4 ++-- app/Services/Servers/ReinstallServerService.php | 2 +- .../Servers/StartupModificationService.php | 2 +- app/Services/Servers/SuspensionService.php | 2 +- .../Subusers/PermissionCreationService.php | 2 +- app/Services/Users/ToggleTwoFactorService.php | 2 +- app/Services/Users/TwoFactorSetupService.php | 2 +- .../Commands/User/DisableTwoFactorCommandTest.php | 4 ++-- tests/Unit/Jobs/Schedule/RunTaskJobTest.php | 4 ++-- .../SetDefaultAllocationServiceTest.php | 4 ++-- tests/Unit/Services/Api/PermissionServiceTest.php | 2 +- .../DaemonKeys/DaemonKeyCreationServiceTest.php | 2 +- .../DaemonKeys/DaemonKeyUpdateServiceTest.php | 2 +- .../Databases/DatabasePasswordServiceTest.php | 2 +- tests/Unit/Services/Eggs/EggUpdateServiceTest.php | 6 +++--- .../Eggs/Scripts/InstallScriptServiceTest.php | 6 +++--- .../Eggs/Sharing/EggUpdateImporterServiceTest.php | 4 ++-- .../Eggs/Variables/VariableUpdateServiceTest.php | 10 +++++----- .../Unit/Services/Nests/NestUpdateServiceTest.php | 4 ++-- .../Unit/Services/Nodes/NodeUpdateServiceTest.php | 8 ++++---- .../Unit/Services/Packs/PackUpdateServiceTest.php | 4 ++-- .../Schedules/Tasks/TaskCreationServiceTest.php | 4 ++-- .../Servers/DetailsModificationServiceTest.php | 14 +++++++------- .../Servers/ReinstallServerServiceTest.php | 8 ++++---- .../Servers/StartupModificationServiceTest.php | 4 ++-- .../Services/Servers/SuspensionServiceTest.php | 6 +++--- .../Subusers/PermissionCreationServiceTest.php | 2 +- .../Services/Users/ToggleTwoFactorServiceTest.php | 6 +++--- .../Services/Users/TwoFactorSetupServiceTest.php | 2 +- 45 files changed, 78 insertions(+), 78 deletions(-) diff --git a/app/Console/Commands/User/DisableTwoFactorCommand.php b/app/Console/Commands/User/DisableTwoFactorCommand.php index 7df23b41e..f2cab910d 100644 --- a/app/Console/Commands/User/DisableTwoFactorCommand.php +++ b/app/Console/Commands/User/DisableTwoFactorCommand.php @@ -56,7 +56,7 @@ class DisableTwoFactorCommand extends Command $email = $this->option('email') ?? $this->ask(trans('command/messages.user.ask_email')); $user = $this->repository->setColumns(['id', 'email'])->findFirstWhere([['email', '=', $email]]); - $this->repository->withoutFresh()->update($user->id, [ + $this->repository->withoutFreshModel()->update($user->id, [ 'use_totp' => false, 'totp_secret' => null, ]); diff --git a/app/Jobs/Schedule/RunTaskJob.php b/app/Jobs/Schedule/RunTaskJob.php index 88590883a..15ee850e9 100644 --- a/app/Jobs/Schedule/RunTaskJob.php +++ b/app/Jobs/Schedule/RunTaskJob.php @@ -161,7 +161,7 @@ class RunTaskJob extends Job implements ShouldQueue private function markScheduleComplete() { $repository = app()->make(ScheduleRepositoryInterface::class); - $repository->withoutFresh()->update($this->schedule, [ + $repository->withoutFreshModel()->update($this->schedule, [ 'is_processing' => false, 'last_run_at' => Carbon::now()->toDateTimeString(), ]); diff --git a/app/Repositories/Eloquent/ServerRepository.php b/app/Repositories/Eloquent/ServerRepository.php index 49fa53c41..02ecef2f1 100644 --- a/app/Repositories/Eloquent/ServerRepository.php +++ b/app/Repositories/Eloquent/ServerRepository.php @@ -236,7 +236,7 @@ class ServerRepository extends EloquentRepository implements ServerRepositoryInt $instance->whereNotIn('id', $this->getUserAccessServers($user->id)); } - return $instance->setSearchTerm($this->getSearchTerm())->paginate(25); + return $instance->search($this->getSearchTerm())->paginate(25); } /** diff --git a/app/Services/Allocations/SetDefaultAllocationService.php b/app/Services/Allocations/SetDefaultAllocationService.php index 66a858be3..552914097 100644 --- a/app/Services/Allocations/SetDefaultAllocationService.php +++ b/app/Services/Allocations/SetDefaultAllocationService.php @@ -83,7 +83,7 @@ class SetDefaultAllocationService } $this->connection->beginTransaction(); - $this->serverRepository->withoutFresh()->update($server->id, ['allocation_id' => $model->id]); + $this->serverRepository->withoutFreshModel()->update($server->id, ['allocation_id' => $model->id]); // Update on the daemon. try { diff --git a/app/Services/Api/PermissionService.php b/app/Services/Api/PermissionService.php index 14bdc235d..24dbf381f 100644 --- a/app/Services/Api/PermissionService.php +++ b/app/Services/Api/PermissionService.php @@ -40,7 +40,7 @@ class PermissionService public function create($key, $permission) { // @todo handle an array of permissions to do a mass assignment? - return $this->repository->withoutFresh()->create([ + return $this->repository->withoutFreshModel()->create([ 'key_id' => $key, 'permission' => $permission, ]); diff --git a/app/Services/DaemonKeys/DaemonKeyCreationService.php b/app/Services/DaemonKeys/DaemonKeyCreationService.php index b9431d28f..23aa1c0aa 100644 --- a/app/Services/DaemonKeys/DaemonKeyCreationService.php +++ b/app/Services/DaemonKeys/DaemonKeyCreationService.php @@ -75,7 +75,7 @@ class DaemonKeyCreationService { $secret = DaemonKeyRepositoryInterface::INTERNAL_KEY_IDENTIFIER . str_random(40); - $this->repository->withoutFresh()->create([ + $this->repository->withoutFreshModel()->create([ 'user_id' => $user, 'server_id' => $server, 'secret' => $secret, diff --git a/app/Services/DaemonKeys/DaemonKeyUpdateService.php b/app/Services/DaemonKeys/DaemonKeyUpdateService.php index 337b3d173..750d833d9 100644 --- a/app/Services/DaemonKeys/DaemonKeyUpdateService.php +++ b/app/Services/DaemonKeys/DaemonKeyUpdateService.php @@ -78,7 +78,7 @@ class DaemonKeyUpdateService Assert::integerish($key, 'First argument passed to handle must be an integer, received %s.'); $secret = DaemonKeyRepositoryInterface::INTERNAL_KEY_IDENTIFIER . str_random(40); - $this->repository->withoutFresh()->update($key, [ + $this->repository->withoutFreshModel()->update($key, [ 'secret' => $secret, 'expires_at' => $this->carbon->now()->addMinutes($this->config->get('pterodactyl.api.key_expire_time'))->toDateTimeString(), ]); diff --git a/app/Services/Databases/DatabasePasswordService.php b/app/Services/Databases/DatabasePasswordService.php index 4f6443ced..8f8a9582d 100644 --- a/app/Services/Databases/DatabasePasswordService.php +++ b/app/Services/Databases/DatabasePasswordService.php @@ -69,7 +69,7 @@ class DatabasePasswordService $this->dynamic->set('dynamic', $database->database_host_id); $this->connection->beginTransaction(); - $updated = $this->repository->withoutFresh()->update($database->id, [ + $updated = $this->repository->withoutFreshModel()->update($database->id, [ 'password' => $this->encrypter->encrypt($password), ]); diff --git a/app/Services/Eggs/EggUpdateService.php b/app/Services/Eggs/EggUpdateService.php index 2932b7457..14d655178 100644 --- a/app/Services/Eggs/EggUpdateService.php +++ b/app/Services/Eggs/EggUpdateService.php @@ -57,6 +57,6 @@ class EggUpdateService } } - $this->repository->withoutFresh()->update($egg->id, $data); + $this->repository->withoutFreshModel()->update($egg->id, $data); } } diff --git a/app/Services/Eggs/Scripts/InstallScriptService.php b/app/Services/Eggs/Scripts/InstallScriptService.php index 094469944..0d9e66bcc 100644 --- a/app/Services/Eggs/Scripts/InstallScriptService.php +++ b/app/Services/Eggs/Scripts/InstallScriptService.php @@ -52,7 +52,7 @@ class InstallScriptService } } - $this->repository->withoutFresh()->update($egg->id, [ + $this->repository->withoutFreshModel()->update($egg->id, [ 'script_install' => array_get($data, 'script_install'), 'script_is_privileged' => array_get($data, 'script_is_privileged', 1), 'script_entry' => array_get($data, 'script_entry'), diff --git a/app/Services/Eggs/Sharing/EggUpdateImporterService.php b/app/Services/Eggs/Sharing/EggUpdateImporterService.php index 3cb275ff7..50342667d 100644 --- a/app/Services/Eggs/Sharing/EggUpdateImporterService.php +++ b/app/Services/Eggs/Sharing/EggUpdateImporterService.php @@ -89,7 +89,7 @@ class EggUpdateImporterService // Update Existing Variables collect($parsed->variables)->each(function ($variable) use ($egg) { - $this->variableRepository->withoutFresh()->updateOrCreate([ + $this->variableRepository->withoutFreshModel()->updateOrCreate([ 'egg_id' => $egg, 'env_variable' => $variable->env_variable, ], collect($variable)->except(['egg_id', 'env_variable'])->toArray()); diff --git a/app/Services/Eggs/Variables/VariableUpdateService.php b/app/Services/Eggs/Variables/VariableUpdateService.php index 91694b166..12930f892 100644 --- a/app/Services/Eggs/Variables/VariableUpdateService.php +++ b/app/Services/Eggs/Variables/VariableUpdateService.php @@ -64,7 +64,7 @@ class VariableUpdateService $options = array_get($data, 'options') ?? []; - return $this->repository->withoutFresh()->update($variable->id, array_merge($data, [ + return $this->repository->withoutFreshModel()->update($variable->id, array_merge($data, [ 'user_viewable' => in_array('user_viewable', $options), 'user_editable' => in_array('user_editable', $options), ])); diff --git a/app/Services/Nests/NestUpdateService.php b/app/Services/Nests/NestUpdateService.php index 12f3a506a..c3cdcdd5d 100644 --- a/app/Services/Nests/NestUpdateService.php +++ b/app/Services/Nests/NestUpdateService.php @@ -42,6 +42,6 @@ class NestUpdateService unset($data['author']); } - $this->repository->withoutFresh()->update($nest, $data); + $this->repository->withoutFreshModel()->update($nest, $data); } } diff --git a/app/Services/Nodes/NodeUpdateService.php b/app/Services/Nodes/NodeUpdateService.php index ace620b28..4a969255b 100644 --- a/app/Services/Nodes/NodeUpdateService.php +++ b/app/Services/Nodes/NodeUpdateService.php @@ -72,7 +72,7 @@ class NodeUpdateService unset($data['reset_secret']); } - $updateResponse = $this->repository->withoutFresh()->update($node->id, $data); + $updateResponse = $this->repository->withoutFreshModel()->update($node->id, $data); try { $this->configRepository->setNode($node->id)->update(); diff --git a/app/Services/Packs/PackUpdateService.php b/app/Services/Packs/PackUpdateService.php index 3354a66f5..a22a55b9f 100644 --- a/app/Services/Packs/PackUpdateService.php +++ b/app/Services/Packs/PackUpdateService.php @@ -70,6 +70,6 @@ class PackUpdateService $data['visible'] = isset($data['visible']); $data['locked'] = isset($data['locked']); - return $this->repository->withoutFresh()->update($pack->id, $data); + return $this->repository->withoutFreshModel()->update($pack->id, $data); } } diff --git a/app/Services/Schedules/Tasks/TaskCreationService.php b/app/Services/Schedules/Tasks/TaskCreationService.php index 9ea1c1783..8ed06e5fd 100644 --- a/app/Services/Schedules/Tasks/TaskCreationService.php +++ b/app/Services/Schedules/Tasks/TaskCreationService.php @@ -56,7 +56,7 @@ class TaskCreationService throw new TaskIntervalTooLongException(trans('exceptions.tasks.chain_interval_too_long')); } - $repository = ($returnModel) ? $this->repository : $this->repository->withoutFresh(); + $repository = ($returnModel) ? $this->repository : $this->repository->withoutFreshModel(); $task = $repository->create([ 'schedule_id' => $schedule, 'sequence_id' => $data['sequence_id'], diff --git a/app/Services/Servers/DetailsModificationService.php b/app/Services/Servers/DetailsModificationService.php index d18bccd73..f500ab3d2 100644 --- a/app/Services/Servers/DetailsModificationService.php +++ b/app/Services/Servers/DetailsModificationService.php @@ -94,7 +94,7 @@ class DetailsModificationService } $this->connection->beginTransaction(); - $this->repository->withoutFresh()->update($server->id, [ + $this->repository->withoutFreshModel()->update($server->id, [ 'owner_id' => array_get($data, 'owner_id'), 'name' => array_get($data, 'name'), 'description' => array_get($data, 'description', ''), @@ -125,7 +125,7 @@ class DetailsModificationService } $this->connection->beginTransaction(); - $this->repository->withoutFresh()->update($server->id, ['image' => $image]); + $this->repository->withoutFreshModel()->update($server->id, ['image' => $image]); try { $this->daemonServerRepository->setNode($server->node_id)->setAccessServer($server->uuid)->update([ diff --git a/app/Services/Servers/ReinstallServerService.php b/app/Services/Servers/ReinstallServerService.php index d5292adf2..7b8a09728 100644 --- a/app/Services/Servers/ReinstallServerService.php +++ b/app/Services/Servers/ReinstallServerService.php @@ -72,7 +72,7 @@ class ReinstallServerService } $this->database->beginTransaction(); - $this->repository->withoutFresh()->update($server->id, [ + $this->repository->withoutFreshModel()->update($server->id, [ 'installed' => 0, ]); diff --git a/app/Services/Servers/StartupModificationService.php b/app/Services/Servers/StartupModificationService.php index 784b60a05..62c614bc8 100644 --- a/app/Services/Servers/StartupModificationService.php +++ b/app/Services/Servers/StartupModificationService.php @@ -91,7 +91,7 @@ class StartupModificationService $results = $this->validatorService->handle(array_get($data, 'egg_id', $server->egg_id), array_get($data, 'environment', [])); $results->each(function ($result) use ($server) { - $this->serverVariableRepository->withoutFresh()->updateOrCreate([ + $this->serverVariableRepository->withoutFreshModel()->updateOrCreate([ 'server_id' => $server->id, 'variable_id' => $result->id, ], [ diff --git a/app/Services/Servers/SuspensionService.php b/app/Services/Servers/SuspensionService.php index dec29da50..045d92cb3 100644 --- a/app/Services/Servers/SuspensionService.php +++ b/app/Services/Servers/SuspensionService.php @@ -91,7 +91,7 @@ class SuspensionService } $this->database->beginTransaction(); - $this->repository->withoutFresh()->update($server->id, [ + $this->repository->withoutFreshModel()->update($server->id, [ 'suspended' => $action === 'suspend', ]); diff --git a/app/Services/Subusers/PermissionCreationService.php b/app/Services/Subusers/PermissionCreationService.php index d44d63008..0173e8015 100644 --- a/app/Services/Subusers/PermissionCreationService.php +++ b/app/Services/Subusers/PermissionCreationService.php @@ -56,6 +56,6 @@ class PermissionCreationService } } - $this->repository->withoutFresh()->insert($insertPermissions); + $this->repository->withoutFreshModel()->insert($insertPermissions); } } diff --git a/app/Services/Users/ToggleTwoFactorService.php b/app/Services/Users/ToggleTwoFactorService.php index e03a76389..6fe8bc9dd 100644 --- a/app/Services/Users/ToggleTwoFactorService.php +++ b/app/Services/Users/ToggleTwoFactorService.php @@ -75,7 +75,7 @@ class ToggleTwoFactorService throw new TwoFactorAuthenticationTokenInvalid; } - $this->repository->withoutFresh()->update($user->id, [ + $this->repository->withoutFreshModel()->update($user->id, [ 'totp_authenticated_at' => Carbon::now(), 'use_totp' => (is_null($toggleState) ? ! $user->use_totp : $toggleState), ]); diff --git a/app/Services/Users/TwoFactorSetupService.php b/app/Services/Users/TwoFactorSetupService.php index a8554ccfc..4d2ecff8a 100644 --- a/app/Services/Users/TwoFactorSetupService.php +++ b/app/Services/Users/TwoFactorSetupService.php @@ -72,7 +72,7 @@ class TwoFactorSetupService $secret = $this->google2FA->generateSecretKey($this->config->get('pterodactyl.auth.2fa.bytes')); $image = $this->google2FA->getQRCodeGoogleUrl($this->config->get('app.name'), $user->email, $secret); - $this->repository->withoutFresh()->update($user->id, [ + $this->repository->withoutFreshModel()->update($user->id, [ 'totp_secret' => $this->encrypter->encrypt($secret), ]); diff --git a/tests/Unit/Commands/User/DisableTwoFactorCommandTest.php b/tests/Unit/Commands/User/DisableTwoFactorCommandTest.php index d741e8be4..32f9e43eb 100644 --- a/tests/Unit/Commands/User/DisableTwoFactorCommandTest.php +++ b/tests/Unit/Commands/User/DisableTwoFactorCommandTest.php @@ -49,7 +49,7 @@ class DisableTwoFactorCommandTest extends CommandTestCase $this->repository->shouldReceive('setColumns')->with(['id', 'email'])->once()->andReturnSelf() ->shouldReceive('findFirstWhere')->with([['email', '=', $user->email]])->once()->andReturn($user); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($user->id, [ 'use_totp' => false, 'totp_secret' => null, @@ -70,7 +70,7 @@ class DisableTwoFactorCommandTest extends CommandTestCase $this->repository->shouldReceive('setColumns')->with(['id', 'email'])->once()->andReturnSelf() ->shouldReceive('findFirstWhere')->with([['email', '=', $user->email]])->once()->andReturn($user); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($user->id, [ 'use_totp' => false, 'totp_secret' => null, diff --git a/tests/Unit/Jobs/Schedule/RunTaskJobTest.php b/tests/Unit/Jobs/Schedule/RunTaskJobTest.php index c72ab33b5..c26bfbaf3 100644 --- a/tests/Unit/Jobs/Schedule/RunTaskJobTest.php +++ b/tests/Unit/Jobs/Schedule/RunTaskJobTest.php @@ -98,7 +98,7 @@ class RunTaskJobTest extends TestCase $this->taskRepository->shouldReceive('update')->with($task->id, ['is_queued' => false])->once()->andReturnNull(); $this->taskRepository->shouldReceive('getNextTask')->with($schedule->id, $task->sequence_id)->once()->andReturnNull(); - $this->scheduleRepository->shouldReceive('withoutFresh->update')->with($schedule->id, [ + $this->scheduleRepository->shouldReceive('withoutFreshModel->update')->with($schedule->id, [ 'is_processing' => false, 'last_run_at' => Carbon::now()->toDateTimeString(), ])->once()->andReturnNull(); @@ -128,7 +128,7 @@ class RunTaskJobTest extends TestCase $this->taskRepository->shouldReceive('update')->with($task->id, ['is_queued' => false])->once()->andReturnNull(); $this->taskRepository->shouldReceive('getNextTask')->with($schedule->id, $task->sequence_id)->once()->andReturnNull(); - $this->scheduleRepository->shouldReceive('withoutFresh->update')->with($schedule->id, [ + $this->scheduleRepository->shouldReceive('withoutFreshModel->update')->with($schedule->id, [ 'is_processing' => false, 'last_run_at' => Carbon::now()->toDateTimeString(), ])->once()->andReturnNull(); diff --git a/tests/Unit/Services/Allocations/SetDefaultAllocationServiceTest.php b/tests/Unit/Services/Allocations/SetDefaultAllocationServiceTest.php index 72a837e78..99916bc6b 100644 --- a/tests/Unit/Services/Allocations/SetDefaultAllocationServiceTest.php +++ b/tests/Unit/Services/Allocations/SetDefaultAllocationServiceTest.php @@ -68,7 +68,7 @@ class SetDefaultAllocationServiceTest extends TestCase $this->repository->shouldReceive('findWhere')->with([['server_id', '=', $model->id]])->once()->andReturn($allocations); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->serverRepository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf(); + $this->serverRepository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf(); $this->serverRepository->shouldReceive('update')->with($model->id, [ 'allocation_id' => $allocations->first()->id, ])->once()->andReturnNull(); @@ -118,7 +118,7 @@ class SetDefaultAllocationServiceTest extends TestCase $this->repository->shouldReceive('findWhere')->with([['server_id', '=', $model->id]])->once()->andReturn(collect([$allocation])); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->serverRepository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf(); + $this->serverRepository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf(); $this->serverRepository->shouldReceive('update')->with($model->id, [ 'allocation_id' => $allocation->id, ])->once()->andReturnNull(); diff --git a/tests/Unit/Services/Api/PermissionServiceTest.php b/tests/Unit/Services/Api/PermissionServiceTest.php index 432f0289a..384acec72 100644 --- a/tests/Unit/Services/Api/PermissionServiceTest.php +++ b/tests/Unit/Services/Api/PermissionServiceTest.php @@ -43,7 +43,7 @@ class PermissionServiceTest extends TestCase */ public function test_create_function() { - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('create')->with(['key_id' => 1, 'permission' => 'test-permission']) ->once()->andReturn(true); diff --git a/tests/Unit/Services/DaemonKeys/DaemonKeyCreationServiceTest.php b/tests/Unit/Services/DaemonKeys/DaemonKeyCreationServiceTest.php index b376b8061..8efcb2f42 100644 --- a/tests/Unit/Services/DaemonKeys/DaemonKeyCreationServiceTest.php +++ b/tests/Unit/Services/DaemonKeys/DaemonKeyCreationServiceTest.php @@ -83,7 +83,7 @@ class DaemonKeyCreationServiceTest extends TestCase ->shouldReceive('addMinutes')->with(100)->once()->andReturnSelf() ->shouldReceive('toDateTimeString')->withNoArgs()->once()->andReturn('00:00:00'); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('create')->with([ 'user_id' => 1, 'server_id' => 2, diff --git a/tests/Unit/Services/DaemonKeys/DaemonKeyUpdateServiceTest.php b/tests/Unit/Services/DaemonKeys/DaemonKeyUpdateServiceTest.php index 999bdaf06..badc29bf1 100644 --- a/tests/Unit/Services/DaemonKeys/DaemonKeyUpdateServiceTest.php +++ b/tests/Unit/Services/DaemonKeys/DaemonKeyUpdateServiceTest.php @@ -70,7 +70,7 @@ class DaemonKeyUpdateServiceTest extends TestCase ->shouldReceive('addMinutes')->with(100)->once()->andReturnSelf() ->shouldReceive('toDateTimeString')->withNoArgs()->once()->andReturn('00:00:00'); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf(); + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf(); $this->repository->shouldReceive('update')->with(123, [ 'secret' => $secret, 'expires_at' => '00:00:00', diff --git a/tests/Unit/Services/Databases/DatabasePasswordServiceTest.php b/tests/Unit/Services/Databases/DatabasePasswordServiceTest.php index 2388e2d34..946f977d4 100644 --- a/tests/Unit/Services/Databases/DatabasePasswordServiceTest.php +++ b/tests/Unit/Services/Databases/DatabasePasswordServiceTest.php @@ -63,7 +63,7 @@ class DatabasePasswordServiceTest extends TestCase $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); $this->encrypter->shouldReceive('encrypt')->with('test123')->once()->andReturn('enc123'); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf(); + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf(); $this->repository->shouldReceive('update')->with($model->id, ['password' => 'enc123'])->once()->andReturn(true); $this->repository->shouldReceive('dropUser')->with($model->username, $model->remote)->once()->andReturn(true); diff --git a/tests/Unit/Services/Eggs/EggUpdateServiceTest.php b/tests/Unit/Services/Eggs/EggUpdateServiceTest.php index db548b962..5e1d29bb4 100644 --- a/tests/Unit/Services/Eggs/EggUpdateServiceTest.php +++ b/tests/Unit/Services/Eggs/EggUpdateServiceTest.php @@ -52,7 +52,7 @@ class EggUpdateServiceTest extends TestCase */ public function testEggIsUpdatedWhenNoConfigFromIsProvided() { - $this->repository->shouldReceive('withoutFresh->update') + $this->repository->shouldReceive('withoutFreshModel->update') ->with($this->model->id, ['test_field' => 'field_value'])->once()->andReturnNull(); $this->service->handle($this->model, ['test_field' => 'field_value']); @@ -70,7 +70,7 @@ class EggUpdateServiceTest extends TestCase ['id', '=', 1], ])->once()->andReturn(1); - $this->repository->shouldReceive('withoutFresh->update') + $this->repository->shouldReceive('withoutFreshModel->update') ->with($this->model->id, ['config_from' => 1])->once()->andReturnNull(); $this->service->handle($this->model, ['config_from' => 1]); @@ -102,7 +102,7 @@ class EggUpdateServiceTest extends TestCase public function testIntegerCanBePassedInPlaceOfModel() { $this->repository->shouldReceive('find')->with($this->model->id)->once()->andReturn($this->model); - $this->repository->shouldReceive('withoutFresh->update') + $this->repository->shouldReceive('withoutFreshModel->update') ->with($this->model->id, ['test_field' => 'field_value'])->once()->andReturnNull(); $this->service->handle($this->model->id, ['test_field' => 'field_value']); diff --git a/tests/Unit/Services/Eggs/Scripts/InstallScriptServiceTest.php b/tests/Unit/Services/Eggs/Scripts/InstallScriptServiceTest.php index ac29f44c4..0bb9e7800 100644 --- a/tests/Unit/Services/Eggs/Scripts/InstallScriptServiceTest.php +++ b/tests/Unit/Services/Eggs/Scripts/InstallScriptServiceTest.php @@ -66,7 +66,7 @@ class InstallScriptServiceTest extends TestCase $this->data['copy_script_from'] = 1; $this->repository->shouldReceive('isCopiableScript')->with(1, $this->model->nest_id)->once()->andReturn(true); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->model->id, $this->data)->andReturnNull(); $this->service->handle($this->model, $this->data); @@ -93,7 +93,7 @@ class InstallScriptServiceTest extends TestCase */ public function testUpdateWithoutNewCopyScriptFromAttribute() { - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->model->id, $this->data)->andReturnNull(); $this->service->handle($this->model, $this->data); @@ -105,7 +105,7 @@ class InstallScriptServiceTest extends TestCase public function testFunctionAcceptsIntegerInPlaceOfModel() { $this->repository->shouldReceive('find')->with($this->model->id)->once()->andReturn($this->model); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->model->id, $this->data)->andReturnNull(); $this->service->handle($this->model->id, $this->data); diff --git a/tests/Unit/Services/Eggs/Sharing/EggUpdateImporterServiceTest.php b/tests/Unit/Services/Eggs/Sharing/EggUpdateImporterServiceTest.php index df95ee214..1818058c9 100644 --- a/tests/Unit/Services/Eggs/Sharing/EggUpdateImporterServiceTest.php +++ b/tests/Unit/Services/Eggs/Sharing/EggUpdateImporterServiceTest.php @@ -81,7 +81,7 @@ class EggUpdateImporterServiceTest extends TestCase 'name' => $egg->name, ]), true, true)->once()->andReturn($egg); - $this->variableRepository->shouldReceive('withoutFresh->updateOrCreate')->with([ + $this->variableRepository->shouldReceive('withoutFreshModel->updateOrCreate')->with([ 'egg_id' => $egg->id, 'env_variable' => $variable->env_variable, ], collect($variable)->except(['egg_id', 'env_variable'])->toArray())->once()->andReturnNull(); @@ -121,7 +121,7 @@ class EggUpdateImporterServiceTest extends TestCase 'name' => $egg->name, ]), true, true)->once()->andReturn($egg); - $this->variableRepository->shouldReceive('withoutFresh->updateOrCreate')->with([ + $this->variableRepository->shouldReceive('withoutFreshModel->updateOrCreate')->with([ 'egg_id' => $egg->id, 'env_variable' => $variable1->env_variable, ], collect($variable1)->except(['egg_id', 'env_variable'])->toArray())->once()->andReturnNull(); diff --git a/tests/Unit/Services/Eggs/Variables/VariableUpdateServiceTest.php b/tests/Unit/Services/Eggs/Variables/VariableUpdateServiceTest.php index 84d082b33..8bfa67689 100644 --- a/tests/Unit/Services/Eggs/Variables/VariableUpdateServiceTest.php +++ b/tests/Unit/Services/Eggs/Variables/VariableUpdateServiceTest.php @@ -45,7 +45,7 @@ class VariableUpdateServiceTest extends TestCase */ public function testVariableIsUpdatedWhenNoEnvironmentVariableIsPassed() { - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->model->id, [ 'user_viewable' => false, 'user_editable' => false, @@ -61,7 +61,7 @@ class VariableUpdateServiceTest extends TestCase public function testVariableIdCanBePassedInPlaceOfModel() { $this->repository->shouldReceive('find')->with($this->model->id)->once()->andReturn($this->model); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->model->id, [ 'user_viewable' => false, 'user_editable' => false, @@ -83,7 +83,7 @@ class VariableUpdateServiceTest extends TestCase ['id', '!=', $this->model->id], ])->once()->andReturn(0); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->model->id, [ 'user_viewable' => false, 'user_editable' => false, @@ -101,7 +101,7 @@ class VariableUpdateServiceTest extends TestCase */ public function testNullOptionValueIsPassedAsArray() { - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->model->id, [ 'user_viewable' => false, 'user_editable' => false, @@ -123,7 +123,7 @@ class VariableUpdateServiceTest extends TestCase ['id', '!=', $this->model->id], ])->once()->andReturn(0); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->model->id, [ 'user_viewable' => false, 'user_editable' => false, diff --git a/tests/Unit/Services/Nests/NestUpdateServiceTest.php b/tests/Unit/Services/Nests/NestUpdateServiceTest.php index e5b03e974..0aa2b388f 100644 --- a/tests/Unit/Services/Nests/NestUpdateServiceTest.php +++ b/tests/Unit/Services/Nests/NestUpdateServiceTest.php @@ -43,7 +43,7 @@ class NestUpdateServiceTest extends TestCase */ public function testAuthorArrayKeyIsRemovedIfPassed() { - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with(1, ['otherfield' => 'value'])->once()->andReturnNull(); $this->service->handle(1, ['author' => 'author1', 'otherfield' => 'value']); @@ -54,7 +54,7 @@ class NestUpdateServiceTest extends TestCase */ public function testServiceIsUpdatedWhenNoAuthorKeyIsPassed() { - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with(1, ['otherfield' => 'value'])->once()->andReturnNull(); $this->service->handle(1, ['otherfield' => 'value']); diff --git a/tests/Unit/Services/Nodes/NodeUpdateServiceTest.php b/tests/Unit/Services/Nodes/NodeUpdateServiceTest.php index da851e6c0..0a68c80b0 100644 --- a/tests/Unit/Services/Nodes/NodeUpdateServiceTest.php +++ b/tests/Unit/Services/Nodes/NodeUpdateServiceTest.php @@ -84,7 +84,7 @@ class NodeUpdateServiceTest extends TestCase $this->getFunctionMock('\\Pterodactyl\\Services\\Nodes', 'str_random') ->expects($this->once())->willReturn('random_string'); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->node->id, [ 'name' => 'NewName', 'daemonSecret' => 'random_string', @@ -101,7 +101,7 @@ class NodeUpdateServiceTest extends TestCase */ public function testNodeIsUpdatedAndDaemonSecretIsNotChanged() { - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->node->id, [ 'name' => 'NewName', ])->andReturn(true); @@ -117,7 +117,7 @@ class NodeUpdateServiceTest extends TestCase */ public function testExceptionCausedByDaemonIsHandled() { - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->node->id, [ 'name' => 'NewName', ])->andReturn(true); @@ -144,7 +144,7 @@ class NodeUpdateServiceTest extends TestCase public function testFunctionCanAcceptANodeIdInPlaceOfModel() { $this->repository->shouldReceive('find')->with($this->node->id)->once()->andReturn($this->node); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->node->id, [ 'name' => 'NewName', ])->andReturn(true); diff --git a/tests/Unit/Services/Packs/PackUpdateServiceTest.php b/tests/Unit/Services/Packs/PackUpdateServiceTest.php index 7078a003c..614807435 100644 --- a/tests/Unit/Services/Packs/PackUpdateServiceTest.php +++ b/tests/Unit/Services/Packs/PackUpdateServiceTest.php @@ -53,7 +53,7 @@ class PackUpdateServiceTest extends TestCase public function testPackIsUpdated() { $model = factory(Pack::class)->make(); - $this->repository->shouldReceive('withoutFresh->update')->with($model->id, [ + $this->repository->shouldReceive('withoutFreshModel->update')->with($model->id, [ 'locked' => false, 'visible' => false, 'selectable' => false, @@ -87,7 +87,7 @@ class PackUpdateServiceTest extends TestCase $this->repository->shouldReceive('setColumns')->with(['id', 'egg_id'])->once()->andReturnSelf() ->shouldReceive('find')->with($model->id)->once()->andReturn($model); - $this->repository->shouldReceive('withoutFresh->update')->with($model->id, [ + $this->repository->shouldReceive('withoutFreshModel->update')->with($model->id, [ 'locked' => false, 'visible' => false, 'selectable' => false, diff --git a/tests/Unit/Services/Schedules/Tasks/TaskCreationServiceTest.php b/tests/Unit/Services/Schedules/Tasks/TaskCreationServiceTest.php index b70ca5275..f6c797ec1 100644 --- a/tests/Unit/Services/Schedules/Tasks/TaskCreationServiceTest.php +++ b/tests/Unit/Services/Schedules/Tasks/TaskCreationServiceTest.php @@ -81,7 +81,7 @@ class TaskCreationServiceTest extends TestCase { $schedule = factory(Schedule::class)->make(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('create')->with([ 'schedule_id' => $schedule->id, 'sequence_id' => 1, @@ -108,7 +108,7 @@ class TaskCreationServiceTest extends TestCase */ public function testIdCanBePassedInPlaceOfScheduleModel() { - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('create')->with([ 'schedule_id' => 1234, 'sequence_id' => 1, diff --git a/tests/Unit/Services/Servers/DetailsModificationServiceTest.php b/tests/Unit/Services/Servers/DetailsModificationServiceTest.php index 7d1e19862..3d04b0106 100644 --- a/tests/Unit/Services/Servers/DetailsModificationServiceTest.php +++ b/tests/Unit/Services/Servers/DetailsModificationServiceTest.php @@ -103,7 +103,7 @@ class DetailsModificationServiceTest extends TestCase $data = ['owner_id' => 1, 'name' => 'New Name', 'description' => 'New Description']; $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($server->id, [ 'owner_id' => $data['owner_id'], 'name' => $data['name'], @@ -129,7 +129,7 @@ class DetailsModificationServiceTest extends TestCase $this->repository->shouldReceive('find')->with($server->id)->once()->andReturn($server); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($server->id, [ 'owner_id' => $data['owner_id'], 'name' => $data['name'], @@ -155,7 +155,7 @@ class DetailsModificationServiceTest extends TestCase $data = ['owner_id' => 2, 'name' => 'New Name', 'description' => 'New Description']; $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($server->id, [ 'owner_id' => $data['owner_id'], 'name' => $data['name'], @@ -178,7 +178,7 @@ class DetailsModificationServiceTest extends TestCase $server = factory(Server::class)->make(['node_id' => 1]); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($server->id, [ 'image' => 'new/image', ])->once()->andReturnNull(); @@ -206,7 +206,7 @@ class DetailsModificationServiceTest extends TestCase $this->repository->shouldReceive('find')->with($server->id)->once()->andReturn($server); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($server->id, [ 'image' => 'new/image', ])->once()->andReturnNull(); @@ -233,7 +233,7 @@ class DetailsModificationServiceTest extends TestCase $server = factory(Server::class)->make(['node_id' => 1]); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($server->id, [ 'image' => 'new/image', ])->once()->andReturnNull(); @@ -266,7 +266,7 @@ class DetailsModificationServiceTest extends TestCase $server = factory(Server::class)->make(['node_id' => 1]); $this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($server->id, [ 'image' => 'new/image', ])->once()->andReturnNull(); diff --git a/tests/Unit/Services/Servers/ReinstallServerServiceTest.php b/tests/Unit/Services/Servers/ReinstallServerServiceTest.php index b7635467a..82f018670 100644 --- a/tests/Unit/Services/Servers/ReinstallServerServiceTest.php +++ b/tests/Unit/Services/Servers/ReinstallServerServiceTest.php @@ -89,7 +89,7 @@ class ReinstallServerServiceTest extends TestCase $this->repository->shouldNotReceive('find'); $this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->server->id, [ 'installed' => 0, ])->once()->andReturnNull(); @@ -110,7 +110,7 @@ class ReinstallServerServiceTest extends TestCase $this->repository->shouldReceive('find')->with($this->server->id)->once()->andReturn($this->server); $this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->server->id, [ 'installed' => 0, ])->once()->andReturnNull(); @@ -129,7 +129,7 @@ class ReinstallServerServiceTest extends TestCase public function testExceptionThrownByGuzzleShouldBeReRenderedAsDisplayable() { $this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->server->id, [ 'installed' => 0, ])->once()->andReturnNull(); @@ -161,7 +161,7 @@ class ReinstallServerServiceTest extends TestCase public function testExceptionNotThrownByGuzzleShouldNotBeTransformedToDisplayable() { $this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->server->id, [ 'installed' => 0, ])->once()->andReturnNull(); diff --git a/tests/Unit/Services/Servers/StartupModificationServiceTest.php b/tests/Unit/Services/Servers/StartupModificationServiceTest.php index ca1dc33c0..0c06b1799 100644 --- a/tests/Unit/Services/Servers/StartupModificationServiceTest.php +++ b/tests/Unit/Services/Servers/StartupModificationServiceTest.php @@ -81,7 +81,7 @@ class StartupModificationServiceTest extends TestCase collect([(object) ['id' => 1, 'value' => 'stored-value']]) ); - $this->serverVariableRepository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf(); + $this->serverVariableRepository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf(); $this->serverVariableRepository->shouldReceive('updateOrCreate')->with([ 'server_id' => $model->id, 'variable_id' => 1, @@ -116,7 +116,7 @@ class StartupModificationServiceTest extends TestCase collect([(object) ['id' => 1, 'value' => 'stored-value']]) ); - $this->serverVariableRepository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf(); + $this->serverVariableRepository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf(); $this->serverVariableRepository->shouldReceive('updateOrCreate')->with([ 'server_id' => $model->id, 'variable_id' => 1, diff --git a/tests/Unit/Services/Servers/SuspensionServiceTest.php b/tests/Unit/Services/Servers/SuspensionServiceTest.php index c24f6e0f0..e899ca747 100644 --- a/tests/Unit/Services/Servers/SuspensionServiceTest.php +++ b/tests/Unit/Services/Servers/SuspensionServiceTest.php @@ -101,7 +101,7 @@ class SuspensionServiceTest extends TestCase $this->server->suspended = 0; $this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->server->id, ['suspended' => true])->once()->andReturnNull(); $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id)->once()->andReturnSelf() @@ -120,7 +120,7 @@ class SuspensionServiceTest extends TestCase $this->server->suspended = 1; $this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->server->id, ['suspended' => false])->once()->andReturnNull(); $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id)->once()->andReturnSelf() @@ -159,7 +159,7 @@ class SuspensionServiceTest extends TestCase $this->server->suspended = 0; $this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->server->id, ['suspended' => true])->once()->andReturnNull(); $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id) diff --git a/tests/Unit/Services/Subusers/PermissionCreationServiceTest.php b/tests/Unit/Services/Subusers/PermissionCreationServiceTest.php index ddfd8c551..397d3d88a 100644 --- a/tests/Unit/Services/Subusers/PermissionCreationServiceTest.php +++ b/tests/Unit/Services/Subusers/PermissionCreationServiceTest.php @@ -44,7 +44,7 @@ class PermissionCreationServiceTest extends TestCase { $permissions = ['reset-sftp', 'view-sftp']; - $this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf() + $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('insert')->with([ ['subuser_id' => 1, 'permission' => 'reset-sftp'], ['subuser_id' => 1, 'permission' => 'view-sftp'], diff --git a/tests/Unit/Services/Users/ToggleTwoFactorServiceTest.php b/tests/Unit/Services/Users/ToggleTwoFactorServiceTest.php index c8d1cc852..0b8f453cc 100644 --- a/tests/Unit/Services/Users/ToggleTwoFactorServiceTest.php +++ b/tests/Unit/Services/Users/ToggleTwoFactorServiceTest.php @@ -63,7 +63,7 @@ class ToggleTwoFactorServiceTest extends TestCase $model = factory(User::class)->make(['totp_secret' => self::USER_TOTP_SECRET, 'use_totp' => false]); $this->google2FA->shouldReceive('verifyKey')->with(self::DECRYPTED_USER_SECRET, 'test-token', self::TEST_WINDOW_INT)->once()->andReturn(true); - $this->repository->shouldReceive('withoutFresh->update')->with($model->id, [ + $this->repository->shouldReceive('withoutFreshModel->update')->with($model->id, [ 'totp_authenticated_at' => Carbon::now(), 'use_totp' => true, ])->once()->andReturnNull(); @@ -79,7 +79,7 @@ class ToggleTwoFactorServiceTest extends TestCase $model = factory(User::class)->make(['totp_secret' => self::USER_TOTP_SECRET, 'use_totp' => true]); $this->google2FA->shouldReceive('verifyKey')->with(self::DECRYPTED_USER_SECRET, 'test-token', self::TEST_WINDOW_INT)->once()->andReturn(true); - $this->repository->shouldReceive('withoutFresh->update')->with($model->id, [ + $this->repository->shouldReceive('withoutFreshModel->update')->with($model->id, [ 'totp_authenticated_at' => Carbon::now(), 'use_totp' => false, ])->once()->andReturnNull(); @@ -95,7 +95,7 @@ class ToggleTwoFactorServiceTest extends TestCase $model = factory(User::class)->make(['totp_secret' => self::USER_TOTP_SECRET, 'use_totp' => false]); $this->google2FA->shouldReceive('verifyKey')->with(self::DECRYPTED_USER_SECRET, 'test-token', self::TEST_WINDOW_INT)->once()->andReturn(true); - $this->repository->shouldReceive('withoutFresh->update')->with($model->id, [ + $this->repository->shouldReceive('withoutFreshModel->update')->with($model->id, [ 'totp_authenticated_at' => Carbon::now(), 'use_totp' => false, ])->once()->andReturnNull(); diff --git a/tests/Unit/Services/Users/TwoFactorSetupServiceTest.php b/tests/Unit/Services/Users/TwoFactorSetupServiceTest.php index d6f5f8b90..8cb097537 100644 --- a/tests/Unit/Services/Users/TwoFactorSetupServiceTest.php +++ b/tests/Unit/Services/Users/TwoFactorSetupServiceTest.php @@ -58,7 +58,7 @@ class TwoFactorSetupServiceTest extends TestCase $this->config->shouldReceive('get')->with('app.name')->once()->andReturn('CompanyName'); $this->google2FA->shouldReceive('getQRCodeGoogleUrl')->with('CompanyName', $model->email, 'secretKey')->once()->andReturn('http://url.com'); $this->encrypter->shouldReceive('encrypt')->with('secretKey')->once()->andReturn('encryptedSecret'); - $this->repository->shouldReceive('withoutFresh->update')->with($model->id, ['totp_secret' => 'encryptedSecret'])->once()->andReturnNull(); + $this->repository->shouldReceive('withoutFreshModel->update')->with($model->id, ['totp_secret' => 'encryptedSecret'])->once()->andReturnNull(); $response = $this->getService()->handle($model); $this->assertNotEmpty($response); From d2afc29a80950ba190612db23e75946de757925b Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Fri, 5 Jan 2018 18:27:47 -0600 Subject: [PATCH 04/20] Refactor how repositories for the daemon work. --- .../Commands/Server/RebuildServerCommand.php | 2 +- .../Daemon/BaseRepositoryInterface.php | 43 +++--- .../Daemon/CommandRepositoryInterface.php | 11 +- .../ConfigurationRepositoryInterface.php | 11 +- .../Daemon/FileRepositoryInterface.php | 22 ++- .../Daemon/PowerRepositoryInterface.php | 11 +- .../Daemon/ServerRepositoryInterface.php | 23 +-- .../Controllers/Admin/ServersController.php | 4 +- app/Http/Controllers/Base/IndexController.php | 5 +- .../Server/Files/FileActionsController.php | 5 +- .../Server/Files/RemoteRequestController.php | 10 +- .../Server/UpdateFileContentsFormRequest.php | 5 +- app/Jobs/Schedule/RunTaskJob.php | 10 +- app/Models/DaemonKey.php | 14 +- app/Repositories/Daemon/BaseRepository.php | 129 ++++++++-------- app/Repositories/Daemon/CommandRepository.php | 19 +-- .../Daemon/ConfigurationRepository.php | 15 +- app/Repositories/Daemon/FileRepository.php | 65 ++++---- app/Repositories/Daemon/PowerRepository.php | 23 ++- app/Repositories/Daemon/ServerRepository.php | 64 +++++--- .../Eloquent/DaemonKeyRepository.php | 2 +- app/Repositories/Eloquent/UserRepository.php | 2 +- app/Repositories/Wings/BaseRepository.php | 146 ------------------ app/Repositories/Wings/CommandRepository.php | 30 ---- .../Wings/ConfigurationRepository.php | 24 --- app/Repositories/Wings/FileRepository.php | 114 -------------- app/Repositories/Wings/PowerRepository.php | 40 ----- app/Repositories/Wings/ServerRepository.php | 89 ----------- .../SetDefaultAllocationService.php | 2 +- .../DaemonKeys/DaemonKeyDeletionService.php | 2 +- .../RevokeMultipleDaemonKeysService.php | 8 +- app/Services/Nodes/NodeUpdateService.php | 2 +- .../Servers/BuildModificationService.php | 2 +- .../Servers/ContainerRebuildService.php | 57 ++----- .../Servers/DetailsModificationService.php | 2 +- .../Servers/ReinstallServerService.php | 23 +-- .../Servers/ServerCreationService.php | 3 +- .../Servers/ServerDeletionService.php | 2 +- .../Servers/StartupModificationService.php | 2 +- app/Services/Servers/SuspensionService.php | 2 +- .../Subusers/SubuserUpdateService.php | 2 +- app/Services/Users/UserUpdateService.php | 1 - .../Controllers/Base/IndexControllerTest.php | 13 +- .../Files/FileActionsControllerTest.php | 11 +- .../Files/RemoteRequestControllerTest.php | 17 +- tests/Unit/Jobs/Schedule/RunTaskJobTest.php | 22 ++- .../SetDefaultAllocationServiceTest.php | 12 +- .../DaemonKeyDeletionServiceTest.php | 11 +- .../RevokeMultipleDaemonKeysServiceTest.php | 23 +-- .../Services/Nodes/NodeUpdateServiceTest.php | 17 +- .../Servers/ContainerRebuildServiceTest.php | 95 ++---------- .../DetailsModificationServiceTest.php | 13 +- .../Servers/ReinstallServerServiceTest.php | 45 ++---- .../Servers/ServerCreationServiceTest.php | 11 +- .../Servers/ServerDeletionServiceTest.php | 16 +- .../StartupModificationServiceTest.php | 11 +- .../Servers/SuspensionServiceTest.php | 13 +- .../Subusers/SubuserUpdateServiceTest.php | 7 +- 58 files changed, 388 insertions(+), 997 deletions(-) delete mode 100644 app/Repositories/Wings/BaseRepository.php delete mode 100644 app/Repositories/Wings/CommandRepository.php delete mode 100644 app/Repositories/Wings/ConfigurationRepository.php delete mode 100644 app/Repositories/Wings/FileRepository.php delete mode 100644 app/Repositories/Wings/PowerRepository.php delete mode 100644 app/Repositories/Wings/ServerRepository.php diff --git a/app/Console/Commands/Server/RebuildServerCommand.php b/app/Console/Commands/Server/RebuildServerCommand.php index c6b562b06..ac239b1ee 100644 --- a/app/Console/Commands/Server/RebuildServerCommand.php +++ b/app/Console/Commands/Server/RebuildServerCommand.php @@ -77,7 +77,7 @@ class RebuildServerCommand extends Command $json = array_merge($this->configurationStructureService->handle($server), ['rebuild' => true]); try { - $this->daemonRepository->setNode($server->node_id)->setAccessServer($server->uuid)->update($json); + $this->daemonRepository->setServer($server)->update($json); } catch (RequestException $exception) { $this->output->error(trans('command/messages.server.rebuild_failed', [ 'name' => $server->name, diff --git a/app/Contracts/Repository/Daemon/BaseRepositoryInterface.php b/app/Contracts/Repository/Daemon/BaseRepositoryInterface.php index 803edca64..398469265 100644 --- a/app/Contracts/Repository/Daemon/BaseRepositoryInterface.php +++ b/app/Contracts/Repository/Daemon/BaseRepositoryInterface.php @@ -1,68 +1,65 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository\Daemon; +use GuzzleHttp\Client; +use Pterodactyl\Models\Node; +use Pterodactyl\Models\Server; + interface BaseRepositoryInterface { /** * Set the node model to be used for this daemon connection. * - * @param int $id + * @param \Pterodactyl\Models\Node $node * @return $this - * - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function setNode($id); + public function setNode(Node $node); /** * Return the node model being used. * * @return \Pterodactyl\Models\Node */ - public function getNode(); + public function getNode(): Node; /** - * Set the UUID for the server to be used in the X-Access-Server header for daemon requests. + * Set the Server model to use when requesting information from the Daemon. * - * @param null|string $server + * @param \Pterodactyl\Models\Server $server * @return $this */ - public function setAccessServer($server = null); + public function setServer(Server $server); /** - * Return the UUID of the server being used in requests. + * Return the Server model. * - * @return string + * @return \Pterodactyl\Models\Server|null */ - public function getAccessServer(); + public function getServer(); /** * Set the token to be used in the X-Access-Token header for requests to the daemon. * - * @param null|string $token + * @param string $token * @return $this */ - public function setAccessToken($token = null); + public function setToken(string $token); /** * Return the access token being used for requests. * - * @return string + * @return string|null */ - public function getAccessToken(); + public function getToken(); /** * Return an instance of the Guzzle HTTP Client to be used for requests. * * @param array $headers * @return \GuzzleHttp\Client + * + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function getHttpClient(array $headers = []); + public function getHttpClient(array $headers = []): Client; } diff --git a/app/Contracts/Repository/Daemon/CommandRepositoryInterface.php b/app/Contracts/Repository/Daemon/CommandRepositoryInterface.php index 398c1dc16..ff6c33cce 100644 --- a/app/Contracts/Repository/Daemon/CommandRepositoryInterface.php +++ b/app/Contracts/Repository/Daemon/CommandRepositoryInterface.php @@ -1,14 +1,9 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository\Daemon; +use Psr\Http\Message\ResponseInterface; + interface CommandRepositoryInterface extends BaseRepositoryInterface { /** @@ -17,5 +12,5 @@ interface CommandRepositoryInterface extends BaseRepositoryInterface * @param string $command * @return \Psr\Http\Message\ResponseInterface */ - public function send($command); + public function send(string $command): ResponseInterface; } diff --git a/app/Contracts/Repository/Daemon/ConfigurationRepositoryInterface.php b/app/Contracts/Repository/Daemon/ConfigurationRepositoryInterface.php index d0a3772da..2b8bceda9 100644 --- a/app/Contracts/Repository/Daemon/ConfigurationRepositoryInterface.php +++ b/app/Contracts/Repository/Daemon/ConfigurationRepositoryInterface.php @@ -1,14 +1,9 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository\Daemon; +use Psr\Http\Message\ResponseInterface; + interface ConfigurationRepositoryInterface extends BaseRepositoryInterface { /** @@ -17,5 +12,5 @@ interface ConfigurationRepositoryInterface extends BaseRepositoryInterface * @param array $overrides * @return \Psr\Http\Message\ResponseInterface */ - public function update(array $overrides = []); + public function update(array $overrides = []): ResponseInterface; } diff --git a/app/Contracts/Repository/Daemon/FileRepositoryInterface.php b/app/Contracts/Repository/Daemon/FileRepositoryInterface.php index 6b9facc09..aba7af0ea 100644 --- a/app/Contracts/Repository/Daemon/FileRepositoryInterface.php +++ b/app/Contracts/Repository/Daemon/FileRepositoryInterface.php @@ -1,35 +1,31 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository\Daemon; +use stdClass; +use Psr\Http\Message\ResponseInterface; + interface FileRepositoryInterface extends BaseRepositoryInterface { /** * Return stat information for a given file. * * @param string $path - * @return object + * @return \stdClass * * @throws \GuzzleHttp\Exception\RequestException */ - public function getFileStat($path); + public function getFileStat(string $path): stdClass; /** * Return the contents of a given file if it can be edited in the Panel. * * @param string $path - * @return object + * @return \stdClass * * @throws \GuzzleHttp\Exception\RequestException */ - public function getContent($path); + public function getContent(string $path): stdClass; /** * Save new contents to a given file. @@ -40,7 +36,7 @@ interface FileRepositoryInterface extends BaseRepositoryInterface * * @throws \GuzzleHttp\Exception\RequestException */ - public function putContent($path, $content); + public function putContent(string $path, string $content): ResponseInterface; /** * Return a directory listing for a given path. @@ -50,5 +46,5 @@ interface FileRepositoryInterface extends BaseRepositoryInterface * * @throws \GuzzleHttp\Exception\RequestException */ - public function getDirectory($path); + public function getDirectory(string $path): array; } diff --git a/app/Contracts/Repository/Daemon/PowerRepositoryInterface.php b/app/Contracts/Repository/Daemon/PowerRepositoryInterface.php index 255109cfd..6b6210431 100644 --- a/app/Contracts/Repository/Daemon/PowerRepositoryInterface.php +++ b/app/Contracts/Repository/Daemon/PowerRepositoryInterface.php @@ -1,14 +1,9 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository\Daemon; +use Psr\Http\Message\ResponseInterface; + interface PowerRepositoryInterface extends BaseRepositoryInterface { const SIGNAL_START = 'start'; @@ -24,5 +19,5 @@ interface PowerRepositoryInterface extends BaseRepositoryInterface * * @throws \Pterodactyl\Exceptions\Repository\Daemon\InvalidPowerSignalException */ - public function sendSignal($signal); + public function sendSignal(string $signal): ResponseInterface; } diff --git a/app/Contracts/Repository/Daemon/ServerRepositoryInterface.php b/app/Contracts/Repository/Daemon/ServerRepositoryInterface.php index 19806ac49..a00686a05 100644 --- a/app/Contracts/Repository/Daemon/ServerRepositoryInterface.php +++ b/app/Contracts/Repository/Daemon/ServerRepositoryInterface.php @@ -1,11 +1,4 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Contracts\Repository\Daemon; @@ -30,7 +23,7 @@ interface ServerRepositoryInterface extends BaseRepositoryInterface * @param array $data * @return \Psr\Http\Message\ResponseInterface */ - public function update(array $data); + public function update(array $data): ResponseInterface; /** * Mark a server to be reinstalled on the system. @@ -38,42 +31,42 @@ interface ServerRepositoryInterface extends BaseRepositoryInterface * @param array|null $data * @return \Psr\Http\Message\ResponseInterface */ - public function reinstall($data = null); + public function reinstall(array $data = null): ResponseInterface; /** * Mark a server as needing a container rebuild the next time the server is booted. * * @return \Psr\Http\Message\ResponseInterface */ - public function rebuild(); + public function rebuild(): ResponseInterface; /** * Suspend a server on the daemon. * * @return \Psr\Http\Message\ResponseInterface */ - public function suspend(); + public function suspend(): ResponseInterface; /** * Un-suspend a server on the daemon. * * @return \Psr\Http\Message\ResponseInterface */ - public function unsuspend(); + public function unsuspend(): ResponseInterface; /** * Delete a server on the daemon. * * @return \Psr\Http\Message\ResponseInterface */ - public function delete(); + public function delete(): ResponseInterface; /** * Return detials on a specific server. * * @return \Psr\Http\Message\ResponseInterface */ - public function details(); + public function details(): ResponseInterface; /** * Revoke an access key on the daemon before the time is expired. @@ -83,5 +76,5 @@ interface ServerRepositoryInterface extends BaseRepositoryInterface * * @throws \GuzzleHttp\Exception\RequestException */ - public function revokeAccessKey($key); + public function revokeAccessKey($key): ResponseInterface; } diff --git a/app/Http/Controllers/Admin/ServersController.php b/app/Http/Controllers/Admin/ServersController.php index fb393e65c..e2bfa8fd4 100644 --- a/app/Http/Controllers/Admin/ServersController.php +++ b/app/Http/Controllers/Admin/ServersController.php @@ -457,12 +457,10 @@ class ServersController extends Controller * * @param \Pterodactyl\Models\Server $server * @return \Illuminate\Http\RedirectResponse - * - * @throws \Pterodactyl\Exceptions\DisplayException */ public function rebuildContainer(Server $server) { - $this->containerRebuildService->rebuild($server); + $this->containerRebuildService->handle($server); $this->alert->success(trans('admin/server.alerts.rebuild_on_boot'))->flash(); return redirect()->route('admin.servers.view.manage', $server->id); diff --git a/app/Http/Controllers/Base/IndexController.php b/app/Http/Controllers/Base/IndexController.php index 7c2cc2f1c..70b5250f0 100644 --- a/app/Http/Controllers/Base/IndexController.php +++ b/app/Http/Controllers/Base/IndexController.php @@ -80,10 +80,7 @@ class IndexController extends Controller } try { - $response = $this->daemonRepository->setNode($server->node_id) - ->setAccessServer($server->uuid) - ->setAccessToken($token) - ->details(); + $response = $this->daemonRepository->setServer($server)->setToken($token)->details(); } catch (RequestException $exception) { throw new HttpException(500, $exception->getMessage()); } diff --git a/app/Http/Controllers/Server/Files/FileActionsController.php b/app/Http/Controllers/Server/Files/FileActionsController.php index 08e6fa881..ca3c093aa 100644 --- a/app/Http/Controllers/Server/Files/FileActionsController.php +++ b/app/Http/Controllers/Server/Files/FileActionsController.php @@ -96,7 +96,6 @@ class FileActionsController extends Controller * @return \Illuminate\View\View * * @throws \Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ public function view(UpdateFileContentsFormRequest $request, string $uuid, string $file): View { @@ -104,9 +103,7 @@ class FileActionsController extends Controller $dirname = pathinfo($file, PATHINFO_DIRNAME); try { - $content = $this->repository->setNode($server->node_id)->setAccessServer($server->uuid) - ->setAccessToken($request->attributes->get('server_token')) - ->getContent($file); + $content = $this->repository->setServer($server)->setToken($request->attributes->get('server_token'))->getContent($file); } catch (RequestException $exception) { throw new DaemonConnectionException($exception); } diff --git a/app/Http/Controllers/Server/Files/RemoteRequestController.php b/app/Http/Controllers/Server/Files/RemoteRequestController.php index 81dba4cab..f792e3ccd 100644 --- a/app/Http/Controllers/Server/Files/RemoteRequestController.php +++ b/app/Http/Controllers/Server/Files/RemoteRequestController.php @@ -66,10 +66,7 @@ class RemoteRequestController extends Controller } try { - $listing = $this->repository->setNode($server->node_id) - ->setAccessServer($server->uuid) - ->setAccessToken($request->attributes->get('server_token')) - ->getDirectory($requestDirectory); + $listing = $this->repository->setServer($server)->setToken($request->attributes->get('server_token'))->getDirectory($requestDirectory); } catch (RequestException $exception) { throw new DaemonConnectionException($exception); } @@ -90,7 +87,6 @@ class RemoteRequestController extends Controller * * @throws \Illuminate\Auth\Access\AuthorizationException * @throws \Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ public function store(Request $request): Response { @@ -98,9 +94,7 @@ class RemoteRequestController extends Controller $this->authorize('save-files', $server); try { - $this->repository->setNode($server->node_id) - ->setAccessServer($server->uuid) - ->setAccessToken($request->attributes->get('server_token')) + $this->repository->setServer($server)->setToken($request->attributes->get('server_token')) ->putContent($request->input('file'), $request->input('contents') ?? ''); return response('', 204); diff --git a/app/Http/Requests/Server/UpdateFileContentsFormRequest.php b/app/Http/Requests/Server/UpdateFileContentsFormRequest.php index d2337ba6a..da316cc22 100644 --- a/app/Http/Requests/Server/UpdateFileContentsFormRequest.php +++ b/app/Http/Requests/Server/UpdateFileContentsFormRequest.php @@ -69,7 +69,6 @@ class UpdateFileContentsFormRequest extends ServerFormRequest * @throws \Pterodactyl\Exceptions\DisplayException * @throws \Pterodactyl\Exceptions\Http\Server\FileSizeTooLargeException * @throws \Pterodactyl\Exceptions\Http\Server\FileTypeNotEditableException - * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ private function checkFileCanBeEdited($server, $token) { @@ -77,9 +76,7 @@ class UpdateFileContentsFormRequest extends ServerFormRequest $repository = app()->make(FileRepositoryInterface::class); try { - $stats = $repository->setNode($server->node_id)->setAccessServer($server->uuid) - ->setAccessToken($token) - ->getFileStat($this->route()->parameter('file')); + $stats = $repository->setServer($server)->setToken($token)->getFileStat($this->route()->parameter('file')); } catch (RequestException $exception) { switch ($exception->getCode()) { case 404: diff --git a/app/Jobs/Schedule/RunTaskJob.php b/app/Jobs/Schedule/RunTaskJob.php index 15ee850e9..021fa496b 100644 --- a/app/Jobs/Schedule/RunTaskJob.php +++ b/app/Jobs/Schedule/RunTaskJob.php @@ -98,15 +98,13 @@ class RunTaskJob extends Job implements ShouldQueue // Perform the provided task aganist the daemon. switch ($task->action) { case 'power': - $this->powerRepository->setNode($server->node_id) - ->setAccessServer($server->uuid) - ->setAccessToken($keyProviderService->handle($server, $user)) + $this->powerRepository->setServer($server) + ->setToken($keyProviderService->handle($server, $user)) ->sendSignal($task->payload); break; case 'command': - $this->commandRepository->setNode($server->node_id) - ->setAccessServer($server->uuid) - ->setAccessToken($keyProviderService->handle($server, $user)) + $this->commandRepository->setServer($server) + ->setToken($keyProviderService->handle($server, $user)) ->send($task->payload); break; default: diff --git a/app/Models/DaemonKey.php b/app/Models/DaemonKey.php index 625df0c9c..59cab2354 100644 --- a/app/Models/DaemonKey.php +++ b/app/Models/DaemonKey.php @@ -27,12 +27,13 @@ namespace Pterodactyl\Models; use Sofa\Eloquence\Eloquence; use Sofa\Eloquence\Validable; use Illuminate\Database\Eloquent\Model; +use Znck\Eloquent\Traits\BelongsToThrough; use Sofa\Eloquence\Contracts\CleansAttributes; use Sofa\Eloquence\Contracts\Validable as ValidableContract; class DaemonKey extends Model implements CleansAttributes, ValidableContract { - use Eloquence, Validable; + use BelongsToThrough, Eloquence, Validable; /** * @var string @@ -91,6 +92,17 @@ class DaemonKey extends Model implements CleansAttributes, ValidableContract return $this->belongsTo(Server::class); } + /** + * Return the node relation. + * + * @return \Znck\Eloquent\Relations\BelongsToThrough + * @throws \Exception + */ + public function node() + { + return $this->belongsToThrough(Node::class, Server::class); + } + /** * Return the user relation. * diff --git a/app/Repositories/Daemon/BaseRepository.php b/app/Repositories/Daemon/BaseRepository.php index 42e343aeb..8b401526a 100644 --- a/app/Repositories/Daemon/BaseRepository.php +++ b/app/Repositories/Daemon/BaseRepository.php @@ -1,149 +1,152 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Daemon; +use RuntimeException; use GuzzleHttp\Client; -use Webmozart\Assert\Assert; +use Pterodactyl\Models\Node; +use Pterodactyl\Models\Server; use Illuminate\Foundation\Application; use Pterodactyl\Contracts\Repository\NodeRepositoryInterface; -use Illuminate\Contracts\Config\Repository as ConfigRepository; use Pterodactyl\Contracts\Repository\Daemon\BaseRepositoryInterface; -class BaseRepository implements BaseRepositoryInterface +abstract class BaseRepository implements BaseRepositoryInterface { /** * @var \Illuminate\Foundation\Application */ - protected $app; + private $app; /** - * @var + * @var \Pterodactyl\Models\Server */ - protected $accessServer; + private $server; /** - * @var + * @var string|null */ - protected $accessToken; + private $token; /** - * @var + * @var \Pterodactyl\Models\Node */ - protected $node; - - /** - * @var \Illuminate\Contracts\Config\Repository - */ - protected $config; + private $node; /** * @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface */ - protected $nodeRepository; + private $nodeRepository; /** * BaseRepository constructor. * * @param \Illuminate\Foundation\Application $app - * @param \Illuminate\Contracts\Config\Repository $config * @param \Pterodactyl\Contracts\Repository\NodeRepositoryInterface $nodeRepository */ - public function __construct( - Application $app, - ConfigRepository $config, - NodeRepositoryInterface $nodeRepository - ) { + public function __construct(Application $app, NodeRepositoryInterface $nodeRepository) + { $this->app = $app; - $this->config = $config; $this->nodeRepository = $nodeRepository; } /** - * {@inheritdoc} + * Set the node model to be used for this daemon connection. + * + * @param \Pterodactyl\Models\Node $node + * @return $this */ - public function setNode($id) + public function setNode(Node $node) { - Assert::numeric($id, 'The first argument passed to setNode must be numeric, received %s.'); - - $this->node = $this->nodeRepository->find($id); + $this->node = $node; return $this; } /** - * {@inheritdoc} + * Return the node model being used. + * + * @return \Pterodactyl\Models\Node */ - public function getNode() + public function getNode(): Node { return $this->node; } /** - * {@inheritdoc} + * Set the Server model to use when requesting information from the Daemon. + * + * @param \Pterodactyl\Models\Server $server + * @return $this */ - public function setAccessServer($server = null) + public function setServer(Server $server) { - Assert::nullOrString($server, 'The first argument passed to setAccessServer must be null or a string, received %s.'); - - $this->accessServer = $server; + $this->server = $server; return $this; } /** - * {@inheritdoc} + * Return the Server model. + * + * @return \Pterodactyl\Models\Server|null */ - public function getAccessServer() + public function getServer() { - return $this->accessServer; + return $this->server; } /** - * {@inheritdoc} + * Set the token to be used in the X-Access-Token header for requests to the daemon. + * + * @param string $token + * @return $this */ - public function setAccessToken($token = null) + public function setToken(string $token) { - Assert::nullOrString($token, 'The first argument passed to setAccessToken must be null or a string, received %s.'); - - $this->accessToken = $token; + $this->token = $token; return $this; } /** - * {@inheritdoc} + * Return the access token being used for requests. + * + * @return string|null */ - public function getAccessToken() + public function getToken() { - return $this->accessToken; + return $this->token; } /** - * {@inheritdoc} + * Return an instance of the Guzzle HTTP Client to be used for requests. + * + * @param array $headers + * @return \GuzzleHttp\Client */ - public function getHttpClient(array $headers = []) + public function getHttpClient(array $headers = []): Client { - if (! is_null($this->accessServer)) { - $headers['X-Access-Server'] = $this->getAccessServer(); + // If no node is set, load the relationship onto the Server model + // and pass that to the setNode function. + if (! $this->getNode() instanceof Node) { + if (! $this->getServer() instanceof Server) { + throw new RuntimeException('An instance of ' . Node::class . ' or ' . Server::class . ' must be set on this repository in order to return a client.'); + } + + $this->getServer()->loadMissing('node'); + $this->setNode($this->getServer()->getRelation('node')); } - if (! is_null($this->accessToken)) { - $headers['X-Access-Token'] = $this->getAccessToken(); - } elseif (! is_null($this->node)) { - $headers['X-Access-Token'] = $this->getNode()->daemonSecret; + if ($this->getServer() instanceof Server) { + $headers['X-Access-Server'] = $this->getServer()->uuid; } + $headers['X-Access-Token'] = $this->getToken() ?? $this->getNode()->daemonSecret; + return new Client([ 'base_uri' => sprintf('%s://%s:%s/v1/', $this->getNode()->scheme, $this->getNode()->fqdn, $this->getNode()->daemonListen), - 'timeout' => $this->config->get('pterodactyl.guzzle.timeout'), - 'connect_timeout' => $this->config->get('pterodactyl.guzzle.connect_timeout'), + 'timeout' => config('pterodactyl.guzzle.timeout'), + 'connect_timeout' => config('pterodactyl.guzzle.connect_timeout'), 'headers' => $headers, ]); } diff --git a/app/Repositories/Daemon/CommandRepository.php b/app/Repositories/Daemon/CommandRepository.php index 29720c69d..31cb6b9b7 100644 --- a/app/Repositories/Daemon/CommandRepository.php +++ b/app/Repositories/Daemon/CommandRepository.php @@ -1,26 +1,21 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Daemon; -use Webmozart\Assert\Assert; +use Psr\Http\Message\ResponseInterface; use Pterodactyl\Contracts\Repository\Daemon\CommandRepositoryInterface; class CommandRepository extends BaseRepository implements CommandRepositoryInterface { /** - * {@inheritdoc} + * Send a command to a server. + * + * @param string $command + * @return \Psr\Http\Message\ResponseInterface + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ - public function send($command) + public function send(string $command): ResponseInterface { - Assert::stringNotEmpty($command, 'First argument passed to send must be a non-empty string, received %s.'); - return $this->getHttpClient()->request('POST', 'server/command', [ 'json' => [ 'command' => $command, diff --git a/app/Repositories/Daemon/ConfigurationRepository.php b/app/Repositories/Daemon/ConfigurationRepository.php index 42cf476e2..f1b063694 100644 --- a/app/Repositories/Daemon/ConfigurationRepository.php +++ b/app/Repositories/Daemon/ConfigurationRepository.php @@ -1,22 +1,19 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Daemon; +use Psr\Http\Message\ResponseInterface; use Pterodactyl\Contracts\Repository\Daemon\ConfigurationRepositoryInterface; class ConfigurationRepository extends BaseRepository implements ConfigurationRepositoryInterface { /** - * {@inheritdoc} + * Update the configuration details for the specified node using data from the database. + * + * @param array $overrides + * @return \Psr\Http\Message\ResponseInterface */ - public function update(array $overrides = []) + public function update(array $overrides = []): ResponseInterface { $node = $this->getNode(); $structure = [ diff --git a/app/Repositories/Daemon/FileRepository.php b/app/Repositories/Daemon/FileRepository.php index 3a5bb980a..2f702d13d 100644 --- a/app/Repositories/Daemon/FileRepository.php +++ b/app/Repositories/Daemon/FileRepository.php @@ -1,23 +1,23 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Daemon; -use Webmozart\Assert\Assert; +use stdClass; +use Psr\Http\Message\ResponseInterface; use Pterodactyl\Contracts\Repository\Daemon\FileRepositoryInterface; class FileRepository extends BaseRepository implements FileRepositoryInterface { - public function getFileStat($path) + /** + * Return stat information for a given file. + * + * @param string $path + * @return \stdClass + * + * @throws \GuzzleHttp\Exception\RequestException + */ + public function getFileStat(string $path): stdClass { - Assert::stringNotEmpty($path, 'First argument passed to getStat must be a non-empty string, received %s.'); - $file = pathinfo($path); $file['dirname'] = in_array($file['dirname'], ['.', './', '/']) ? null : trim($file['dirname'], '/') . '/'; @@ -30,12 +30,15 @@ class FileRepository extends BaseRepository implements FileRepositoryInterface } /** - * {@inheritdoc} + * Return the contents of a given file if it can be edited in the Panel. + * + * @param string $path + * @return \stdClass + * + * @throws \GuzzleHttp\Exception\RequestException */ - public function getContent($path) + public function getContent(string $path): stdClass { - Assert::stringNotEmpty($path, 'First argument passed to getContent must be a non-empty string, received %s.'); - $file = pathinfo($path); $file['dirname'] = in_array($file['dirname'], ['.', './', '/']) ? null : trim($file['dirname'], '/') . '/'; @@ -48,13 +51,16 @@ class FileRepository extends BaseRepository implements FileRepositoryInterface } /** - * {@inheritdoc} + * Save new contents to a given file. + * + * @param string $path + * @param string $content + * @return \Psr\Http\Message\ResponseInterface + * + * @throws \GuzzleHttp\Exception\RequestException */ - public function putContent($path, $content) + public function putContent(string $path, string $content): ResponseInterface { - Assert::stringNotEmpty($path, 'First argument passed to putContent must be a non-empty string, received %s.'); - Assert::string($content, 'Second argument passed to putContent must be a string, received %s.'); - $file = pathinfo($path); $file['dirname'] = in_array($file['dirname'], ['.', './', '/']) ? null : trim($file['dirname'], '/') . '/'; @@ -67,20 +73,19 @@ class FileRepository extends BaseRepository implements FileRepositoryInterface } /** - * {@inheritdoc} + * Return a directory listing for a given path. + * + * @param string $path + * @return array + * + * @throws \GuzzleHttp\Exception\RequestException */ - public function getDirectory($path) + public function getDirectory(string $path): array { - Assert::string($path, 'First argument passed to getDirectory must be a string, received %s.'); - - $response = $this->getHttpClient()->request('GET', sprintf( - 'server/directory/%s', - rawurlencode($path) - )); + $response = $this->getHttpClient()->request('GET', sprintf('server/directory/%s', rawurlencode($path))); $contents = json_decode($response->getBody()); - $files = []; - $folders = []; + $files = $folders = []; foreach ($contents as $value) { if ($value->directory) { diff --git a/app/Repositories/Daemon/PowerRepository.php b/app/Repositories/Daemon/PowerRepository.php index 2feaa8010..20fc79338 100644 --- a/app/Repositories/Daemon/PowerRepository.php +++ b/app/Repositories/Daemon/PowerRepository.php @@ -1,27 +1,23 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Repositories\Daemon; -use Webmozart\Assert\Assert; +use Psr\Http\Message\ResponseInterface; use Pterodactyl\Contracts\Repository\Daemon\PowerRepositoryInterface; use Pterodactyl\Exceptions\Repository\Daemon\InvalidPowerSignalException; class PowerRepository extends BaseRepository implements PowerRepositoryInterface { /** - * {@inheritdoc} + * Send a power signal to a server. + * + * @param string $signal + * @return \Psr\Http\Message\ResponseInterface + * + * @throws \Pterodactyl\Exceptions\Repository\Daemon\InvalidPowerSignalException */ - public function sendSignal($signal) + public function sendSignal(string $signal): ResponseInterface { - Assert::stringNotEmpty($signal, 'The first argument passed to sendSignal must be a non-empty string, received %s.'); - switch ($signal) { case self::SIGNAL_START: case self::SIGNAL_STOP: @@ -32,9 +28,8 @@ class PowerRepository extends BaseRepository implements PowerRepositoryInterface 'action' => $signal, ], ]); - break; default: - throw new InvalidPowerSignalException('The signal ' . $signal . ' is not defined and could not be processed.'); + throw new InvalidPowerSignalException('The signal "' . $signal . '" is not defined and could not be processed.'); } } } diff --git a/app/Repositories/Daemon/ServerRepository.php b/app/Repositories/Daemon/ServerRepository.php index d46749e5d..3af381d1c 100644 --- a/app/Repositories/Daemon/ServerRepository.php +++ b/app/Repositories/Daemon/ServerRepository.php @@ -19,9 +19,8 @@ class ServerRepository extends BaseRepository implements ServerRepositoryInterfa */ public function create(array $structure, array $overrides = []): ResponseInterface { - // Loop through overrides. foreach ($overrides as $key => $value) { - array_set($structure, $key, $value); + $structure[$key] = value($value); } return $this->getHttpClient()->request('POST', 'servers', [ @@ -30,9 +29,12 @@ class ServerRepository extends BaseRepository implements ServerRepositoryInterfa } /** - * {@inheritdoc} + * Update server details on the daemon. + * + * @param array $data + * @return \Psr\Http\Message\ResponseInterface */ - public function update(array $data) + public function update(array $data): ResponseInterface { return $this->getHttpClient()->request('PATCH', 'server', [ 'json' => $data, @@ -40,65 +42,77 @@ class ServerRepository extends BaseRepository implements ServerRepositoryInterfa } /** - * {@inheritdoc} + * Mark a server to be reinstalled on the system. + * + * @param array|null $data + * @return \Psr\Http\Message\ResponseInterface */ - public function reinstall($data = null) + public function reinstall(array $data = null): ResponseInterface { - Assert::nullOrIsArray($data, 'First argument passed to reinstall must be null or an array, received %s.'); - - if (is_null($data)) { - return $this->getHttpClient()->request('POST', 'server/reinstall'); - } - return $this->getHttpClient()->request('POST', 'server/reinstall', [ - 'json' => $data, + 'json' => $data ?? [], ]); } /** - * {@inheritdoc} + * Mark a server as needing a container rebuild the next time the server is booted. + * + * @return \Psr\Http\Message\ResponseInterface */ - public function rebuild() + public function rebuild(): ResponseInterface { return $this->getHttpClient()->request('POST', 'server/rebuild'); } /** - * {@inheritdoc} + * Suspend a server on the daemon. + * + * @return \Psr\Http\Message\ResponseInterface */ - public function suspend() + public function suspend(): ResponseInterface { return $this->getHttpClient()->request('POST', 'server/suspend'); } /** - * {@inheritdoc} + * Un-suspend a server on the daemon. + * + * @return \Psr\Http\Message\ResponseInterface */ - public function unsuspend() + public function unsuspend(): ResponseInterface { return $this->getHttpClient()->request('POST', 'server/unsuspend'); } /** - * {@inheritdoc} + * Delete a server on the daemon. + * + * @return \Psr\Http\Message\ResponseInterface */ - public function delete() + public function delete(): ResponseInterface { return $this->getHttpClient()->request('DELETE', 'servers'); } /** - * {@inheritdoc} + * Return detials on a specific server. + * + * @return \Psr\Http\Message\ResponseInterface */ - public function details() + public function details(): ResponseInterface { return $this->getHttpClient()->request('GET', 'server'); } /** - * {@inheritdoc} + * Revoke an access key on the daemon before the time is expired. + * + * @param string|array $key + * @return \Psr\Http\Message\ResponseInterface + * + * @throws \GuzzleHttp\Exception\RequestException */ - public function revokeAccessKey($key) + public function revokeAccessKey($key): ResponseInterface { if (is_array($key)) { return $this->getHttpClient()->request('POST', 'keys', [ diff --git a/app/Repositories/Eloquent/DaemonKeyRepository.php b/app/Repositories/Eloquent/DaemonKeyRepository.php index ba246f458..c53f8a471 100644 --- a/app/Repositories/Eloquent/DaemonKeyRepository.php +++ b/app/Repositories/Eloquent/DaemonKeyRepository.php @@ -70,7 +70,7 @@ class DaemonKeyRepository extends EloquentRepository implements DaemonKeyReposit */ public function getKeysForRevocation(User $user): Collection { - return $this->getBuilder()->with('server:id,uuid,node_id')->where('user_id', $user->id)->get($this->getColumns()); + return $this->getBuilder()->with('node')->where('user_id', $user->id)->get($this->getColumns()); } /** diff --git a/app/Repositories/Eloquent/UserRepository.php b/app/Repositories/Eloquent/UserRepository.php index 4b033dc14..3a0a07942 100644 --- a/app/Repositories/Eloquent/UserRepository.php +++ b/app/Repositories/Eloquent/UserRepository.php @@ -30,7 +30,7 @@ class UserRepository extends EloquentRepository implements UserRepositoryInterfa public function getAllUsersWithCounts(): LengthAwarePaginator { return $this->getBuilder()->withCount('servers', 'subuserOf') - ->setSearchTerm($this->getSearchTerm()) + ->search($this->getSearchTerm()) ->paginate(50, $this->getColumns()); } diff --git a/app/Repositories/Wings/BaseRepository.php b/app/Repositories/Wings/BaseRepository.php deleted file mode 100644 index eee71104a..000000000 --- a/app/Repositories/Wings/BaseRepository.php +++ /dev/null @@ -1,146 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Pterodactyl\Repositories\Wings; - -use GuzzleHttp\Client; -use Webmozart\Assert\Assert; -use Illuminate\Foundation\Application; -use Pterodactyl\Contracts\Repository\NodeRepositoryInterface; -use Illuminate\Contracts\Config\Repository as ConfigRepository; -use Pterodactyl\Contracts\Repository\Daemon\BaseRepositoryInterface; - -class BaseRepository implements BaseRepositoryInterface -{ - /** - * @var \Illuminate\Foundation\Application - */ - protected $app; - - /** - * @var - */ - protected $accessServer; - - /** - * @var - */ - protected $accessToken; - - /** - * @var - */ - protected $node; - - /** - * @var \Illuminate\Contracts\Config\Repository - */ - protected $config; - - /** - * @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface - */ - protected $nodeRepository; - - /** - * BaseRepository constructor. - * - * @param \Illuminate\Foundation\Application $app - * @param \Illuminate\Contracts\Config\Repository $config - * @param \Pterodactyl\Contracts\Repository\NodeRepositoryInterface $nodeRepository - */ - public function __construct( - Application $app, - ConfigRepository $config, - NodeRepositoryInterface $nodeRepository - ) { - $this->app = $app; - $this->config = $config; - $this->nodeRepository = $nodeRepository; - } - - /** - * {@inheritdoc} - */ - public function setNode($id) - { - Assert::numeric($id, 'The first argument passed to setNode must be numeric, received %s.'); - - $this->node = $this->nodeRepository->find($id); - - return $this; - } - - /** - * {@inheritdoc} - */ - public function getNode() - { - return $this->node; - } - - /** - * {@inheritdoc} - */ - public function setAccessServer($server = null) - { - Assert::nullOrString($server, 'The first argument passed to setAccessServer must be null or a string, received %s.'); - - $this->accessServer = $server; - - return $this; - } - - /** - * {@inheritdoc} - */ - public function getAccessServer() - { - return $this->accessServer; - } - - /** - * {@inheritdoc} - */ - public function setAccessToken($token = null) - { - Assert::nullOrString($token, 'The first argument passed to setAccessToken must be null or a string, received %s.'); - - $this->accessToken = $token; - - return $this; - } - - /** - * {@inheritdoc} - */ - public function getAccessToken() - { - return $this->accessToken; - } - - /** - * {@inheritdoc} - */ - public function getHttpClient(array $headers = []) - { - if (! is_null($this->accessToken)) { - $headers['Authorization'] = 'Bearer ' . $this->getAccessToken(); - } elseif (! is_null($this->node)) { - $headers['Authorization'] = 'Bearer ' . $this->getNode()->daemonSecret; - } - - return new Client([ - 'base_uri' => sprintf('%s://%s:%s/v1/', $this->getNode()->scheme, $this->getNode()->fqdn, $this->getNode()->daemonListen), - 'timeout' => $this->config->get('pterodactyl.guzzle.timeout'), - 'connect_timeout' => $this->config->get('pterodactyl.guzzle.connect_timeout'), - 'headers' => $headers, - ]); - } -} diff --git a/app/Repositories/Wings/CommandRepository.php b/app/Repositories/Wings/CommandRepository.php deleted file mode 100644 index 7c1e3eb19..000000000 --- a/app/Repositories/Wings/CommandRepository.php +++ /dev/null @@ -1,30 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Pterodactyl\Repositories\Wings; - -use Webmozart\Assert\Assert; -use Pterodactyl\Contracts\Repository\Daemon\CommandRepositoryInterface; - -class CommandRepository extends BaseRepository implements CommandRepositoryInterface -{ - /** - * {@inheritdoc} - */ - public function send($command) - { - Assert::stringNotEmpty($command, 'First argument passed to send must be a non-empty string, received %s.'); - - return $this->getHttpClient()->request('POST', 'server/' . $this->getAccessServer() . '/command', [ - 'json' => [ - 'command' => $command, - ], - ]); - } -} diff --git a/app/Repositories/Wings/ConfigurationRepository.php b/app/Repositories/Wings/ConfigurationRepository.php deleted file mode 100644 index db487d6ae..000000000 --- a/app/Repositories/Wings/ConfigurationRepository.php +++ /dev/null @@ -1,24 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Pterodactyl\Repositories\Wings; - -use Pterodactyl\Exceptions\PterodactylException; -use Pterodactyl\Contracts\Repository\Daemon\ConfigurationRepositoryInterface; - -class ConfigurationRepository extends BaseRepository implements ConfigurationRepositoryInterface -{ - /** - * {@inheritdoc} - */ - public function update(array $overrides = []) - { - throw new PterodactylException('This has not yet been configured.'); - } -} diff --git a/app/Repositories/Wings/FileRepository.php b/app/Repositories/Wings/FileRepository.php deleted file mode 100644 index ab515cab8..000000000 --- a/app/Repositories/Wings/FileRepository.php +++ /dev/null @@ -1,114 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Pterodactyl\Repositories\Wings; - -use Webmozart\Assert\Assert; -use Pterodactyl\Contracts\Repository\Daemon\FileRepositoryInterface; - -class FileRepository extends BaseRepository implements FileRepositoryInterface -{ - /** - * {@inheritdoc} - */ - public function getFileStat($path) - { - Assert::stringNotEmpty($path, 'First argument passed to getStat must be a non-empty string, received %s.'); - - $file = pathinfo($path); - $file['dirname'] = in_array($file['dirname'], ['.', './', '/']) ? null : trim($file['dirname'], '/') . '/'; - - $response = $this->getHttpClient()->request('GET', sprintf( - 'server/' . $this->getAccessServer() . '/file/stat/%s', - rawurlencode($file['dirname'] . $file['basename']) - )); - - return json_decode($response->getBody()); - } - - /** - * {@inheritdoc} - */ - public function getContent($path) - { - Assert::stringNotEmpty($path, 'First argument passed to getContent must be a non-empty string, received %s.'); - - $file = pathinfo($path); - $file['dirname'] = in_array($file['dirname'], ['.', './', '/']) ? null : trim($file['dirname'], '/') . '/'; - - $response = $this->getHttpClient()->request('GET', sprintf( - 'server/' . $this->getAccessServer() . '/file/f/%s', - rawurlencode($file['dirname'] . $file['basename']) - )); - - return object_get(json_decode($response->getBody()), 'content'); - } - - /** - * {@inheritdoc} - */ - public function putContent($path, $content) - { - Assert::stringNotEmpty($path, 'First argument passed to putContent must be a non-empty string, received %s.'); - Assert::string($content, 'Second argument passed to putContent must be a string, received %s.'); - - $file = pathinfo($path); - $file['dirname'] = in_array($file['dirname'], ['.', './', '/']) ? null : trim($file['dirname'], '/') . '/'; - - return $this->getHttpClient()->request('POST', 'server/' . $this->getAccessServer() . '/file/save', [ - 'json' => [ - 'path' => rawurlencode($file['dirname'] . $file['basename']), - 'content' => $content, - ], - ]); - } - - /** - * {@inheritdoc} - */ - public function getDirectory($path) - { - Assert::string($path, 'First argument passed to getDirectory must be a string, received %s.'); - - $response = $this->getHttpClient()->request('GET', sprintf( - 'server/' . $this->getAccessServer() . '/directory/%s', - rawurlencode($path) - )); - - $contents = json_decode($response->getBody()); - $files = []; - $folders = []; - - foreach ($contents as $value) { - if ($value->directory) { - array_push($folders, [ - 'entry' => $value->name, - 'directory' => trim($path, '/'), - 'size' => null, - 'date' => strtotime($value->modified), - 'mime' => $value->mime, - ]); - } elseif ($value->file) { - array_push($files, [ - 'entry' => $value->name, - 'directory' => trim($path, '/'), - 'extension' => pathinfo($value->name, PATHINFO_EXTENSION), - 'size' => human_readable($value->size), - 'date' => strtotime($value->modified), - 'mime' => $value->mime, - ]); - } - } - - return [ - 'files' => $files, - 'folders' => $folders, - ]; - } -} diff --git a/app/Repositories/Wings/PowerRepository.php b/app/Repositories/Wings/PowerRepository.php deleted file mode 100644 index 281cdca28..000000000 --- a/app/Repositories/Wings/PowerRepository.php +++ /dev/null @@ -1,40 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Pterodactyl\Repositories\Wings; - -use Webmozart\Assert\Assert; -use Pterodactyl\Contracts\Repository\Daemon\PowerRepositoryInterface; -use Pterodactyl\Exceptions\Repository\Daemon\InvalidPowerSignalException; - -class PowerRepository extends BaseRepository implements PowerRepositoryInterface -{ - /** - * {@inheritdoc} - */ - public function sendSignal($signal) - { - Assert::stringNotEmpty($signal, 'The first argument passed to sendSignal must be a non-empty string, received %s.'); - - switch ($signal) { - case self::SIGNAL_START: - case self::SIGNAL_STOP: - case self::SIGNAL_RESTART: - case self::SIGNAL_KILL: - return $this->getHttpClient()->request('PUT', 'server/' . $this->getAccessServer() . '/power', [ - 'json' => [ - 'action' => $signal, - ], - ]); - break; - default: - throw new InvalidPowerSignalException('The signal ' . $signal . ' is not defined and could not be processed.'); - } - } -} diff --git a/app/Repositories/Wings/ServerRepository.php b/app/Repositories/Wings/ServerRepository.php deleted file mode 100644 index 3a7653d96..000000000 --- a/app/Repositories/Wings/ServerRepository.php +++ /dev/null @@ -1,89 +0,0 @@ -. - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ - -namespace Pterodactyl\Repositories\Wings; - -use Psr\Http\Message\ResponseInterface; -use Pterodactyl\Exceptions\PterodactylException; -use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface; - -class ServerRepository extends BaseRepository implements ServerRepositoryInterface -{ - /** - * {@inheritdoc} - */ - public function create(array $structure, array $overrides = []): ResponseInterface - { - throw new PterodactylException('This feature is not yet implemented.'); - } - - /** - * {@inheritdoc} - */ - public function update(array $data) - { - throw new PterodactylException('This feature is not yet implemented.'); - } - - /** - * {@inheritdoc} - */ - public function reinstall($data = null) - { - throw new PterodactylException('This feature is not yet implemented.'); - } - - /** - * {@inheritdoc} - */ - public function rebuild() - { - return $this->getHttpClient()->request('POST', 'server/' . $this->getAccessServer() . '/rebuild'); - } - - /** - * {@inheritdoc} - */ - public function suspend() - { - return $this->getHttpClient()->request('POST', 'server/' . $this->getAccessServer() . '/suspend'); - } - - /** - * {@inheritdoc} - */ - public function unsuspend() - { - return $this->getHttpClient()->request('POST', 'server/' . $this->getAccessServer() . '/unsuspend'); - } - - /** - * {@inheritdoc} - */ - public function delete() - { - return $this->getHttpClient()->request('DELETE', 'server/' . $this->getAccessServer()); - } - - /** - * {@inheritdoc} - */ - public function details() - { - return $this->getHttpClient()->request('GET', 'server/' . $this->getAccessServer()); - } - - /** - * {@inheritdoc} - */ - public function revokeAccessKey($key) - { - throw new PterodactylException('This feature is not yet implemented.'); - } -} diff --git a/app/Services/Allocations/SetDefaultAllocationService.php b/app/Services/Allocations/SetDefaultAllocationService.php index 552914097..6e9010316 100644 --- a/app/Services/Allocations/SetDefaultAllocationService.php +++ b/app/Services/Allocations/SetDefaultAllocationService.php @@ -87,7 +87,7 @@ class SetDefaultAllocationService // Update on the daemon. try { - $this->daemonRepository->setAccessServer($server->uuid)->setNode($server->node_id)->update([ + $this->daemonRepository->setServer($server)->update([ 'build' => [ 'default' => [ 'ip' => $model->ip, diff --git a/app/Services/DaemonKeys/DaemonKeyDeletionService.php b/app/Services/DaemonKeys/DaemonKeyDeletionService.php index 6cc605eb8..553258ce7 100644 --- a/app/Services/DaemonKeys/DaemonKeyDeletionService.php +++ b/app/Services/DaemonKeys/DaemonKeyDeletionService.php @@ -108,7 +108,7 @@ class DaemonKeyDeletionService $this->repository->delete($key->id); try { - $this->daemonRepository->setNode($server->node_id)->revokeAccessKey($key->secret); + $this->daemonRepository->setServer($server)->revokeAccessKey($key->secret); } catch (RequestException $exception) { $response = $exception->getResponse(); $this->connection->rollBack(); diff --git a/app/Services/DaemonKeys/RevokeMultipleDaemonKeysService.php b/app/Services/DaemonKeys/RevokeMultipleDaemonKeysService.php index 93b8b2041..7059be88e 100644 --- a/app/Services/DaemonKeys/RevokeMultipleDaemonKeysService.php +++ b/app/Services/DaemonKeys/RevokeMultipleDaemonKeysService.php @@ -46,22 +46,20 @@ class RevokeMultipleDaemonKeysService * * @param \Pterodactyl\Models\User $user * @param bool $ignoreConnectionErrors - * - * @throws \Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException */ public function handle(User $user, bool $ignoreConnectionErrors = false) { $keys = $this->repository->getKeysForRevocation($user); - $keys->groupBy('server.node_id')->each(function ($group, $node) use ($ignoreConnectionErrors) { + $keys->groupBy('node.id')->each(function ($group, $nodeId) use ($ignoreConnectionErrors) { try { - $this->daemonRepository->setNode($node)->revokeAccessKey(collect($group)->pluck('secret')->toArray()); + $this->daemonRepository->setNode(collect($group)->first()->getRelation('node'))->revokeAccessKey(collect($group)->pluck('secret')->toArray()); } catch (RequestException $exception) { if (! $ignoreConnectionErrors) { throw new DaemonConnectionException($exception); } - $this->setConnectionException($node, $exception); + $this->setConnectionException($nodeId, $exception); } $this->repository->deleteKeys(collect($group)->pluck('id')->toArray()); diff --git a/app/Services/Nodes/NodeUpdateService.php b/app/Services/Nodes/NodeUpdateService.php index 4a969255b..ce81d6f8a 100644 --- a/app/Services/Nodes/NodeUpdateService.php +++ b/app/Services/Nodes/NodeUpdateService.php @@ -75,7 +75,7 @@ class NodeUpdateService $updateResponse = $this->repository->withoutFreshModel()->update($node->id, $data); try { - $this->configRepository->setNode($node->id)->update(); + $this->configRepository->setNode($node)->update(); } catch (RequestException $exception) { $response = $exception->getResponse(); $this->writer->warning($exception); diff --git a/app/Services/Servers/BuildModificationService.php b/app/Services/Servers/BuildModificationService.php index 9aa1fa4c5..3b452e1ed 100644 --- a/app/Services/Servers/BuildModificationService.php +++ b/app/Services/Servers/BuildModificationService.php @@ -154,7 +154,7 @@ class BuildModificationService })->toArray()); try { - $this->daemonServerRepository->setNode($server->node_id)->setAccessServer($server->uuid)->update([ + $this->daemonServerRepository->setServer($server->uuid)->update([ 'build' => $this->getBuild(), ]); diff --git a/app/Services/Servers/ContainerRebuildService.php b/app/Services/Servers/ContainerRebuildService.php index 49c51ed5a..0dc25b0e4 100644 --- a/app/Services/Servers/ContainerRebuildService.php +++ b/app/Services/Servers/ContainerRebuildService.php @@ -1,77 +1,42 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Pterodactyl\Services\Servers; -use Illuminate\Log\Writer; use Pterodactyl\Models\Server; use GuzzleHttp\Exception\RequestException; -use Pterodactyl\Exceptions\DisplayException; -use Pterodactyl\Contracts\Repository\ServerRepositoryInterface; -use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface as DaemonServerRepositoryInterface; +use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException; +use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface; class ContainerRebuildService { - /** - * @var \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface - */ - protected $daemonServerRepository; - /** * @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface */ - protected $repository; - - /** - * @var \Illuminate\Log\Writer - */ - protected $writer; + private $repository; /** * ContainerRebuildService constructor. * - * @param \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface $daemonServerRepository - * @param \Pterodactyl\Contracts\Repository\ServerRepositoryInterface $repository - * @param \Illuminate\Log\Writer $writer + * @param \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface $repository */ - public function __construct( - DaemonServerRepositoryInterface $daemonServerRepository, - ServerRepositoryInterface $repository, - Writer $writer - ) { - $this->daemonServerRepository = $daemonServerRepository; + public function __construct(ServerRepositoryInterface $repository) + { $this->repository = $repository; - $this->writer = $writer; } /** * Mark a server for rebuild on next boot cycle. * - * @param int|\Pterodactyl\Models\Server $server + * @param \Pterodactyl\Models\Server $server * - * @throws \Pterodactyl\Exceptions\DisplayException + * @throws \Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException */ - public function rebuild($server) + public function handle(Server $server) { - if (! $server instanceof Server) { - $server = $this->repository->find($server); - } - try { - $this->daemonServerRepository->setNode($server->node_id)->setAccessServer($server->uuid)->rebuild(); + $this->repository->setServer($server)->rebuild(); } catch (RequestException $exception) { - $response = $exception->getResponse(); - $this->writer->warning($exception); - - throw new DisplayException(trans('admin/server.exceptions.daemon_exception', [ - 'code' => is_null($response) ? 'E_CONN_REFUSED' : $response->getStatusCode(), - ])); + throw new DaemonConnectionException($exception); } } } diff --git a/app/Services/Servers/DetailsModificationService.php b/app/Services/Servers/DetailsModificationService.php index f500ab3d2..5ba4f779b 100644 --- a/app/Services/Servers/DetailsModificationService.php +++ b/app/Services/Servers/DetailsModificationService.php @@ -128,7 +128,7 @@ class DetailsModificationService $this->repository->withoutFreshModel()->update($server->id, ['image' => $image]); try { - $this->daemonServerRepository->setNode($server->node_id)->setAccessServer($server->uuid)->update([ + $this->daemonServerRepository->setServer($server)->update([ 'build' => [ 'image' => $image, ], diff --git a/app/Services/Servers/ReinstallServerService.php b/app/Services/Servers/ReinstallServerService.php index 7b8a09728..682813e36 100644 --- a/app/Services/Servers/ReinstallServerService.php +++ b/app/Services/Servers/ReinstallServerService.php @@ -9,12 +9,11 @@ namespace Pterodactyl\Services\Servers; -use Illuminate\Log\Writer; use Pterodactyl\Models\Server; use GuzzleHttp\Exception\RequestException; use Illuminate\Database\ConnectionInterface; -use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Contracts\Repository\ServerRepositoryInterface; +use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException; use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface as DaemonServerRepositoryInterface; class ReinstallServerService @@ -34,29 +33,21 @@ class ReinstallServerService */ protected $repository; - /** - * @var \Illuminate\Log\Writer - */ - protected $writer; - /** * ReinstallService constructor. * * @param \Illuminate\Database\ConnectionInterface $database * @param \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface $daemonServerRepository * @param \Pterodactyl\Contracts\Repository\ServerRepositoryInterface $repository - * @param \Illuminate\Log\Writer $writer */ public function __construct( ConnectionInterface $database, DaemonServerRepositoryInterface $daemonServerRepository, - ServerRepositoryInterface $repository, - Writer $writer + ServerRepositoryInterface $repository ) { $this->daemonServerRepository = $daemonServerRepository; $this->database = $database; $this->repository = $repository; - $this->writer = $writer; } /** @@ -64,6 +55,7 @@ class ReinstallServerService * * @throws \Pterodactyl\Exceptions\DisplayException * @throws \Pterodactyl\Exceptions\Model\DataValidationException + * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException */ public function reinstall($server) { @@ -77,15 +69,10 @@ class ReinstallServerService ]); try { - $this->daemonServerRepository->setNode($server->node_id)->setAccessServer($server->uuid)->reinstall(); + $this->daemonServerRepository->setServer($server)->reinstall(); $this->database->commit(); } catch (RequestException $exception) { - $response = $exception->getResponse(); - $this->writer->warning($exception); - - throw new DisplayException(trans('admin/server.exceptions.daemon_exception', [ - 'code' => is_null($response) ? 'E_CONN_REFUSED' : $response->getStatusCode(), - ])); + throw new DaemonConnectionException($exception); } } } diff --git a/app/Services/Servers/ServerCreationService.php b/app/Services/Servers/ServerCreationService.php index 5aa1d7b24..82c49000c 100644 --- a/app/Services/Servers/ServerCreationService.php +++ b/app/Services/Servers/ServerCreationService.php @@ -163,8 +163,9 @@ class ServerCreationService $structure = $this->configurationStructureService->handle($server); // Create the server on the daemon & commit it to the database. + $node = $this->nodeRepository->find($server->node_id); try { - $this->daemonServerRepository->setNode($server->node_id)->create($structure, [ + $this->daemonServerRepository->setNode($node)->create($structure, [ 'start_on_completion' => (bool) array_get($data, 'start_on_completion', false), ]); $this->connection->commit(); diff --git a/app/Services/Servers/ServerDeletionService.php b/app/Services/Servers/ServerDeletionService.php index 4ae5c645d..e6c098165 100644 --- a/app/Services/Servers/ServerDeletionService.php +++ b/app/Services/Servers/ServerDeletionService.php @@ -110,7 +110,7 @@ class ServerDeletionService } try { - $this->daemonServerRepository->setNode($server->node_id)->setAccessServer($server->uuid)->delete(); + $this->daemonServerRepository->setServer($server)->delete(); } catch (RequestException $exception) { $response = $exception->getResponse(); diff --git a/app/Services/Servers/StartupModificationService.php b/app/Services/Servers/StartupModificationService.php index 62c614bc8..76a10ad0d 100644 --- a/app/Services/Servers/StartupModificationService.php +++ b/app/Services/Servers/StartupModificationService.php @@ -112,7 +112,7 @@ class StartupModificationService ]); try { - $this->daemonServerRepository->setNode($server->node_id)->setAccessServer($server->uuid)->update($daemonData); + $this->daemonServerRepository->setServer($server)->update($daemonData); } catch (RequestException $exception) { $this->connection->rollBack(); throw new DaemonConnectionException($exception); diff --git a/app/Services/Servers/SuspensionService.php b/app/Services/Servers/SuspensionService.php index 045d92cb3..1feb2887d 100644 --- a/app/Services/Servers/SuspensionService.php +++ b/app/Services/Servers/SuspensionService.php @@ -96,7 +96,7 @@ class SuspensionService ]); try { - $this->daemonServerRepository->setNode($server->node_id)->setAccessServer($server->uuid)->$action(); + $this->daemonServerRepository->setServer($server)->$action(); $this->database->commit(); return true; diff --git a/app/Services/Subusers/SubuserUpdateService.php b/app/Services/Subusers/SubuserUpdateService.php index 9cf02e4b4..f56e47b9d 100644 --- a/app/Services/Subusers/SubuserUpdateService.php +++ b/app/Services/Subusers/SubuserUpdateService.php @@ -96,7 +96,7 @@ class SubuserUpdateService try { $token = $this->keyProviderService->handle($subuser->getRelation('server'), $subuser->getRelation('user'), false); - $this->daemonRepository->setNode($subuser->getRelation('server')->node_id)->revokeAccessKey($token); + $this->daemonRepository->setServer($subuser->getRelation('server'))->revokeAccessKey($token); } catch (RequestException $exception) { $this->connection->rollBack(); throw new DaemonConnectionException($exception); diff --git a/app/Services/Users/UserUpdateService.php b/app/Services/Users/UserUpdateService.php index 9e755dd9f..1a767ae1a 100644 --- a/app/Services/Users/UserUpdateService.php +++ b/app/Services/Users/UserUpdateService.php @@ -55,7 +55,6 @@ class UserUpdateService * * @throws \Pterodactyl\Exceptions\Model\DataValidationException * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException - * @throws \Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException */ public function handle(User $user, array $data): Collection { diff --git a/tests/Unit/Http/Controllers/Base/IndexControllerTest.php b/tests/Unit/Http/Controllers/Base/IndexControllerTest.php index 8dab9007a..6056747ed 100644 --- a/tests/Unit/Http/Controllers/Base/IndexControllerTest.php +++ b/tests/Unit/Http/Controllers/Base/IndexControllerTest.php @@ -11,6 +11,7 @@ namespace Tests\Unit\Http\Controllers\Base; use Mockery as m; use Pterodactyl\Models\User; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use Tests\Assertions\ControllerAssertionsTrait; use Tests\Unit\Http\Controllers\ControllerTestCase; @@ -85,20 +86,18 @@ class IndexControllerTest extends ControllerTestCase { $user = $this->generateRequestUserModel(); $server = factory(Server::class)->make(['suspended' => 0, 'installed' => 1]); + $psrResponse = new Response; $this->repository->shouldReceive('findFirstWhere')->with([['uuidShort', '=', $server->uuidShort]])->once()->andReturn($server); $this->keyProviderService->shouldReceive('handle')->with($server, $user)->once()->andReturn('test123'); - $this->daemonRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($server->uuid)->once()->andReturnSelf() - ->shouldReceive('setAccessToken')->with('test123')->once()->andReturnSelf() - ->shouldReceive('details')->withNoArgs()->once()->andReturnSelf(); - - $this->daemonRepository->shouldReceive('getBody')->withNoArgs()->once()->andReturn('["test"]'); + $this->daemonRepository->shouldReceive('setServer')->with($server)->once()->andReturnSelf() + ->shouldReceive('setToken')->with('test123')->once()->andReturnSelf() + ->shouldReceive('details')->withNoArgs()->once()->andReturn($psrResponse); $response = $this->controller->status($this->request, $server->uuidShort); $this->assertIsJsonResponse($response); - $this->assertResponseJsonEquals(['test'], $response); + $this->assertResponseJsonEquals(json_encode($psrResponse->getBody()), $response); } /** diff --git a/tests/Unit/Http/Controllers/Server/Files/FileActionsControllerTest.php b/tests/Unit/Http/Controllers/Server/Files/FileActionsControllerTest.php index f6d8cac0c..1e5cac0a7 100644 --- a/tests/Unit/Http/Controllers/Server/Files/FileActionsControllerTest.php +++ b/tests/Unit/Http/Controllers/Server/Files/FileActionsControllerTest.php @@ -98,10 +98,9 @@ class FileActionsControllerTest extends ControllerTestCase $this->setRequestAttribute('file_stats', 'fileStatsObject'); $this->mockInjectJavascript(['stat' => 'fileStatsObject']); - $this->repository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($server->uuid)->once()->andReturnSelf() - ->shouldReceive('setAccessToken')->with('abc123')->once()->andReturnSelf() - ->shouldReceive('getContent')->with($file)->once()->andReturn('file contents'); + $this->repository->shouldReceive('setServer')->with($server)->once()->andReturnSelf() + ->shouldReceive('setToken')->with('abc123')->once()->andReturnSelf() + ->shouldReceive('getContent')->with($file)->once()->andReturn((object) ['test']); $response = $controller->view($this->request, '1234', $file); $this->assertIsViewResponse($response); @@ -112,7 +111,7 @@ class FileActionsControllerTest extends ControllerTestCase $this->assertViewHasKey('directory', $response); $this->assertViewKeyEquals('file', $file, $response); $this->assertViewKeyEquals('stat', 'fileStatsObject', $response); - $this->assertViewKeyEquals('contents', 'file contents', $response); + $this->assertViewKeyEquals('contents', (object) ['test'], $response); $this->assertViewKeyEquals('directory', $expected, $response); } @@ -131,7 +130,7 @@ class FileActionsControllerTest extends ControllerTestCase $this->setRequestAttribute('server_token', 'abc123'); $this->setRequestAttribute('file_stats', 'fileStatsObject'); - $this->repository->shouldReceive('setNode')->with($server->node_id)->once()->andThrow($this->getExceptionMock()); + $this->repository->shouldReceive('setServer')->with($server)->once()->andThrow($this->getExceptionMock()); try { $controller->view($this->request, '1234', 'file.txt'); diff --git a/tests/Unit/Http/Controllers/Server/Files/RemoteRequestControllerTest.php b/tests/Unit/Http/Controllers/Server/Files/RemoteRequestControllerTest.php index b44b225e2..6291a748a 100644 --- a/tests/Unit/Http/Controllers/Server/Files/RemoteRequestControllerTest.php +++ b/tests/Unit/Http/Controllers/Server/Files/RemoteRequestControllerTest.php @@ -10,6 +10,7 @@ namespace Tests\Unit\Http\Controllers\Server\Files; use Mockery as m; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use Tests\Traits\MocksRequestException; use GuzzleHttp\Exception\RequestException; @@ -58,9 +59,8 @@ class RemoteRequestControllerTest extends ControllerTestCase $controller->shouldReceive('authorize')->with('list-files', $server)->once()->andReturnNull(); $this->request->shouldReceive('input')->with('directory', '/')->once()->andReturn('/'); - $this->repository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($server->uuid)->once()->andReturnSelf() - ->shouldReceive('setAccessToken')->with('abc123')->once()->andReturnSelf() + $this->repository->shouldReceive('setServer')->with($server)->once()->andReturnSelf() + ->shouldReceive('setToken')->with('abc123')->once()->andReturnSelf() ->shouldReceive('getDirectory')->with('/')->once()->andReturn(['folders' => 1, 'files' => 2]); $this->config->shouldReceive('get')->with('pterodactyl.files.editable')->once()->andReturn([]); @@ -91,7 +91,7 @@ class RemoteRequestControllerTest extends ControllerTestCase $controller->shouldReceive('authorize')->with('list-files', $server)->once()->andReturnNull(); $this->request->shouldReceive('input')->with('directory', '/')->once()->andReturn('/'); - $this->repository->shouldReceive('setNode')->with($server->node_id)->once()->andThrow($this->getExceptionMock()); + $this->repository->shouldReceive('setServer')->with($server)->once()->andThrow($this->getExceptionMock()); try { $controller->directory($this->request); @@ -115,10 +115,9 @@ class RemoteRequestControllerTest extends ControllerTestCase $controller->shouldReceive('authorize')->with('save-files', $server)->once()->andReturnNull(); $this->request->shouldReceive('input')->with('file')->once()->andReturn('file.txt'); $this->request->shouldReceive('input')->with('contents')->once()->andReturn('file contents'); - $this->repository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($server->uuid)->once()->andReturnSelf() - ->shouldReceive('setAccessToken')->with('abc123')->once()->andReturnSelf() - ->shouldReceive('putContent')->with('file.txt', 'file contents')->once()->andReturnNull(); + $this->repository->shouldReceive('setServer')->with($server)->once()->andReturnSelf() + ->shouldReceive('setToken')->with('abc123')->once()->andReturnSelf() + ->shouldReceive('putContent')->with('file.txt', 'file contents')->once()->andReturn(new Response); $response = $controller->store($this->request); $this->assertIsResponse($response); @@ -137,7 +136,7 @@ class RemoteRequestControllerTest extends ControllerTestCase $this->setRequestAttribute('server', $server); $controller->shouldReceive('authorize')->with('save-files', $server)->once()->andReturnNull(); - $this->repository->shouldReceive('setNode')->with($server->node_id)->once()->andThrow($this->getExceptionMock()); + $this->repository->shouldReceive('setServer')->with($server)->once()->andThrow($this->getExceptionMock()); try { $controller->store($this->request); diff --git a/tests/Unit/Jobs/Schedule/RunTaskJobTest.php b/tests/Unit/Jobs/Schedule/RunTaskJobTest.php index c26bfbaf3..a32d7dfe1 100644 --- a/tests/Unit/Jobs/Schedule/RunTaskJobTest.php +++ b/tests/Unit/Jobs/Schedule/RunTaskJobTest.php @@ -14,6 +14,7 @@ use Carbon\Carbon; use Tests\TestCase; use Pterodactyl\Models\Task; use Pterodactyl\Models\User; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use Pterodactyl\Models\Schedule; use Illuminate\Support\Facades\Bus; @@ -90,10 +91,9 @@ class RunTaskJobTest extends TestCase $this->taskRepository->shouldReceive('getTaskWithServer')->with($task->id)->once()->andReturn($task); $this->keyProviderService->shouldReceive('handle')->with($server, $server->user)->once()->andReturn('123456'); - $this->powerRepository->shouldReceive('setNode')->with($task->server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($task->server->uuid)->once()->andReturnSelf() - ->shouldReceive('setAccessToken')->with('123456')->once()->andReturnSelf() - ->shouldReceive('sendSignal')->with($task->payload)->once()->andReturnNull(); + $this->powerRepository->shouldReceive('setServer')->with($task->server)->once()->andReturnSelf() + ->shouldReceive('setToken')->with('123456')->once()->andReturnSelf() + ->shouldReceive('sendSignal')->with($task->payload)->once()->andReturn(new Response); $this->taskRepository->shouldReceive('update')->with($task->id, ['is_queued' => false])->once()->andReturnNull(); $this->taskRepository->shouldReceive('getNextTask')->with($schedule->id, $task->sequence_id)->once()->andReturnNull(); @@ -120,10 +120,9 @@ class RunTaskJobTest extends TestCase $this->taskRepository->shouldReceive('getTaskWithServer')->with($task->id)->once()->andReturn($task); $this->keyProviderService->shouldReceive('handle')->with($server, $server->user)->once()->andReturn('123456'); - $this->commandRepository->shouldReceive('setNode')->with($task->server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($task->server->uuid)->once()->andReturnSelf() - ->shouldReceive('setAccessToken')->with('123456')->once()->andReturnSelf() - ->shouldReceive('send')->with($task->payload)->once()->andReturnNull(); + $this->commandRepository->shouldReceive('setServer')->with($task->server)->once()->andReturnSelf() + ->shouldReceive('setToken')->with('123456')->once()->andReturnSelf() + ->shouldReceive('send')->with($task->payload)->once()->andReturn(new Response); $this->taskRepository->shouldReceive('update')->with($task->id, ['is_queued' => false])->once()->andReturnNull(); $this->taskRepository->shouldReceive('getNextTask')->with($schedule->id, $task->sequence_id)->once()->andReturnNull(); @@ -150,10 +149,9 @@ class RunTaskJobTest extends TestCase $this->taskRepository->shouldReceive('getTaskWithServer')->with($task->id)->once()->andReturn($task); $this->keyProviderService->shouldReceive('handle')->with($server, $server->user)->once()->andReturn('123456'); - $this->commandRepository->shouldReceive('setNode')->with($task->server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($task->server->uuid)->once()->andReturnSelf() - ->shouldReceive('setAccessToken')->with('123456')->once()->andReturnSelf() - ->shouldReceive('send')->with($task->payload)->once()->andReturnNull(); + $this->commandRepository->shouldReceive('setServer')->with($task->server)->once()->andReturnSelf() + ->shouldReceive('setToken')->with('123456')->once()->andReturnSelf() + ->shouldReceive('send')->with($task->payload)->once()->andReturn(new Response); $this->taskRepository->shouldReceive('update')->with($task->id, ['is_queued' => false])->once()->andReturnNull(); diff --git a/tests/Unit/Services/Allocations/SetDefaultAllocationServiceTest.php b/tests/Unit/Services/Allocations/SetDefaultAllocationServiceTest.php index 99916bc6b..e382a8636 100644 --- a/tests/Unit/Services/Allocations/SetDefaultAllocationServiceTest.php +++ b/tests/Unit/Services/Allocations/SetDefaultAllocationServiceTest.php @@ -4,6 +4,7 @@ namespace Tests\Unit\Services\Allocations; use Mockery as m; use Tests\TestCase; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use Pterodactyl\Models\Allocation; use Tests\Traits\MocksRequestException; @@ -71,10 +72,9 @@ class SetDefaultAllocationServiceTest extends TestCase $this->serverRepository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf(); $this->serverRepository->shouldReceive('update')->with($model->id, [ 'allocation_id' => $allocations->first()->id, - ])->once()->andReturnNull(); + ])->once()->andReturn(new Response); - $this->daemonRepository->shouldReceive('setAccessServer')->with($model->uuid)->once()->andReturnSelf(); - $this->daemonRepository->shouldReceive('setNode')->with($model->node_id)->once()->andReturnSelf(); + $this->daemonRepository->shouldReceive('setServer')->with($model)->once()->andReturnSelf(); $this->daemonRepository->shouldReceive('update')->with([ 'build' => [ 'default' => [ @@ -85,7 +85,7 @@ class SetDefaultAllocationServiceTest extends TestCase return $item->pluck('port'); })->toArray(), ], - ])->once()->andReturnNull(); + ])->once()->andReturn(new Response); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $response = $this->getService()->handle($useModel ? $model : 1234, $allocations->first()->id); @@ -121,9 +121,9 @@ class SetDefaultAllocationServiceTest extends TestCase $this->serverRepository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf(); $this->serverRepository->shouldReceive('update')->with($model->id, [ 'allocation_id' => $allocation->id, - ])->once()->andReturnNull(); + ])->once()->andReturn(new Response); - $this->daemonRepository->shouldReceive('setAccessServer->setNode->update')->once()->andThrow($this->getExceptionMock()); + $this->daemonRepository->shouldReceive('setServer->update')->once()->andThrow($this->getExceptionMock()); $this->connection->shouldReceive('rollBack')->withNoArgs()->once()->andReturnNull(); try { diff --git a/tests/Unit/Services/DaemonKeys/DaemonKeyDeletionServiceTest.php b/tests/Unit/Services/DaemonKeys/DaemonKeyDeletionServiceTest.php index 558c1eb45..74007dda6 100644 --- a/tests/Unit/Services/DaemonKeys/DaemonKeyDeletionServiceTest.php +++ b/tests/Unit/Services/DaemonKeys/DaemonKeyDeletionServiceTest.php @@ -12,6 +12,7 @@ namespace Tests\Unit\Services\DaemonKeys; use Mockery as m; use Tests\TestCase; use Illuminate\Log\Writer; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use Pterodactyl\Models\DaemonKey; use GuzzleHttp\Exception\RequestException; @@ -98,8 +99,8 @@ class DaemonKeyDeletionServiceTest extends TestCase ])->once()->andReturn($key); $this->repository->shouldReceive('delete')->with($key->id)->once()->andReturn(1); - $this->daemonRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf() - ->shouldReceive('revokeAccessKey')->with($key->secret)->once()->andReturnNull(); + $this->daemonRepository->shouldReceive('setServer')->with($server)->once()->andReturnSelf() + ->shouldReceive('revokeAccessKey')->with($key->secret)->once()->andReturn(new Response); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->handle($server, 100); @@ -122,8 +123,8 @@ class DaemonKeyDeletionServiceTest extends TestCase ])->once()->andReturn($key); $this->repository->shouldReceive('delete')->with($key->id)->once()->andReturn(1); - $this->daemonRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf() - ->shouldReceive('revokeAccessKey')->with($key->secret)->once()->andReturnNull(); + $this->daemonRepository->shouldReceive('setServer')->with($server)->once()->andReturnSelf() + ->shouldReceive('revokeAccessKey')->with($key->secret)->once()->andReturn(new Response); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->handle($server->id, 100); @@ -145,7 +146,7 @@ class DaemonKeyDeletionServiceTest extends TestCase ])->once()->andReturn($key); $this->repository->shouldReceive('delete')->with($key->id)->once()->andReturn(1); - $this->daemonRepository->shouldReceive('setNode')->with($server->node_id)->once()->andThrow($this->exception); + $this->daemonRepository->shouldReceive('setServer')->with($server)->once()->andThrow($this->exception); $this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnNull(); $this->connection->shouldReceive('rollBack')->withNoArgs()->once()->andReturnNull(); $this->writer->shouldReceive('warning')->with($this->exception)->once()->andReturnNull(); diff --git a/tests/Unit/Services/DaemonKeys/RevokeMultipleDaemonKeysServiceTest.php b/tests/Unit/Services/DaemonKeys/RevokeMultipleDaemonKeysServiceTest.php index 950824cb3..dbc20d577 100644 --- a/tests/Unit/Services/DaemonKeys/RevokeMultipleDaemonKeysServiceTest.php +++ b/tests/Unit/Services/DaemonKeys/RevokeMultipleDaemonKeysServiceTest.php @@ -4,8 +4,9 @@ namespace Tests\Unit\Services\DaemonKeys; use Mockery as m; use Tests\TestCase; +use Pterodactyl\Models\Node; use Pterodactyl\Models\User; -use Pterodactyl\Models\Server; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\DaemonKey; use Tests\Traits\MocksRequestException; use Pterodactyl\Contracts\Repository\DaemonKeyRepositoryInterface; @@ -43,13 +44,13 @@ class RevokeMultipleDaemonKeysServiceTest extends TestCase public function testSuccessfulKeyRevocation() { $user = factory(User::class)->make(); - $server = factory(Server::class)->make(); + $node = factory(Node::class)->make(); $key = factory(DaemonKey::class)->make(['user_id' => $user->id]); - $key->setRelation('server', $server); + $key->setRelation('node', $node); $this->repository->shouldReceive('getKeysForRevocation')->with($user)->once()->andReturn(collect([$key])); - $this->daemonRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf(); - $this->daemonRepository->shouldReceive('revokeAccessKey')->with([$key->secret])->once()->andReturnNull(); + $this->daemonRepository->shouldReceive('setNode')->with($node)->once()->andReturnSelf(); + $this->daemonRepository->shouldReceive('revokeAccessKey')->with([$key->secret])->once()->andReturn(new Response); $this->repository->shouldReceive('deleteKeys')->with([$key->id])->once()->andReturnNull(); @@ -67,9 +68,9 @@ class RevokeMultipleDaemonKeysServiceTest extends TestCase $this->configureExceptionMock(); $user = factory(User::class)->make(); - $server = factory(Server::class)->make(); + $node = factory(Node::class)->make(); $key = factory(DaemonKey::class)->make(['user_id' => $user->id]); - $key->setRelation('server', $server); + $key->setRelation('node', $node); $this->repository->shouldReceive('getKeysForRevocation')->with($user)->once()->andReturn(collect([$key])); $this->daemonRepository->shouldReceive('setNode->revokeAccessKey')->with([$key->secret])->once()->andThrow($this->getExceptionMock()); @@ -86,9 +87,9 @@ class RevokeMultipleDaemonKeysServiceTest extends TestCase $this->configureExceptionMock(); $user = factory(User::class)->make(); - $server = factory(Server::class)->make(); + $node = factory(Node::class)->make(); $key = factory(DaemonKey::class)->make(['user_id' => $user->id]); - $key->setRelation('server', $server); + $key->setRelation('node', $node); $this->repository->shouldReceive('getKeysForRevocation')->with($user)->once()->andReturn(collect([$key])); $this->daemonRepository->shouldReceive('setNode->revokeAccessKey')->with([$key->secret])->once()->andThrow($this->getExceptionMock()); @@ -98,8 +99,8 @@ class RevokeMultipleDaemonKeysServiceTest extends TestCase $service = $this->getService(); $service->handle($user, true); $this->assertNotEmpty($service->getExceptions()); - $this->assertArrayHasKey($server->node_id, $service->getExceptions()); - $this->assertSame(array_get($service->getExceptions(), $server->node_id), $this->getExceptionMock()); + $this->assertArrayHasKey($node->id, $service->getExceptions()); + $this->assertSame(array_get($service->getExceptions(), $node->id), $this->getExceptionMock()); $this->assertTrue(true); } diff --git a/tests/Unit/Services/Nodes/NodeUpdateServiceTest.php b/tests/Unit/Services/Nodes/NodeUpdateServiceTest.php index 0a68c80b0..ded8b7326 100644 --- a/tests/Unit/Services/Nodes/NodeUpdateServiceTest.php +++ b/tests/Unit/Services/Nodes/NodeUpdateServiceTest.php @@ -15,6 +15,7 @@ use Tests\TestCase; use Illuminate\Log\Writer; use phpmock\phpunit\PHPMock; use Pterodactyl\Models\Node; +use GuzzleHttp\Psr7\Response; use GuzzleHttp\Exception\RequestException; use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Services\Nodes\NodeUpdateService; @@ -90,8 +91,8 @@ class NodeUpdateServiceTest extends TestCase 'daemonSecret' => 'random_string', ])->andReturn(true); - $this->configRepository->shouldReceive('setNode')->with($this->node->id)->once()->andReturnSelf() - ->shouldReceive('update')->withNoArgs()->once()->andReturnNull(); + $this->configRepository->shouldReceive('setNode')->with($this->node)->once()->andReturnSelf() + ->shouldReceive('update')->withNoArgs()->once()->andReturn(new Response); $this->assertTrue($this->service->handle($this->node, ['name' => 'NewName', 'reset_secret' => true])); } @@ -106,8 +107,8 @@ class NodeUpdateServiceTest extends TestCase 'name' => 'NewName', ])->andReturn(true); - $this->configRepository->shouldReceive('setNode')->with($this->node->id)->once()->andReturnSelf() - ->shouldReceive('update')->withNoArgs()->once()->andReturnNull(); + $this->configRepository->shouldReceive('setNode')->with($this->node)->once()->andReturnSelf() + ->shouldReceive('update')->withNoArgs()->once()->andReturn(new Response); $this->assertTrue($this->service->handle($this->node, ['name' => 'NewName'])); } @@ -120,9 +121,9 @@ class NodeUpdateServiceTest extends TestCase $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->node->id, [ 'name' => 'NewName', - ])->andReturn(true); + ])->andReturn(new Response); - $this->configRepository->shouldReceive('setNode')->with($this->node->id)->once()->andThrow($this->exception); + $this->configRepository->shouldReceive('setNode')->with($this->node)->once()->andThrow($this->exception); $this->writer->shouldReceive('warning')->with($this->exception)->once()->andReturnNull(); $this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('getStatusCode')->withNoArgs()->once()->andReturn(400); @@ -149,8 +150,8 @@ class NodeUpdateServiceTest extends TestCase 'name' => 'NewName', ])->andReturn(true); - $this->configRepository->shouldReceive('setNode')->with($this->node->id)->once()->andReturnSelf() - ->shouldReceive('update')->withNoArgs()->once()->andReturnNull(); + $this->configRepository->shouldReceive('setNode')->with($this->node)->once()->andReturnSelf() + ->shouldReceive('update')->withNoArgs()->once()->andReturn(new Response); $this->assertTrue($this->service->handle($this->node->id, ['name' => 'NewName'])); } diff --git a/tests/Unit/Services/Servers/ContainerRebuildServiceTest.php b/tests/Unit/Services/Servers/ContainerRebuildServiceTest.php index d4e1dd8ac..a16c41225 100644 --- a/tests/Unit/Services/Servers/ContainerRebuildServiceTest.php +++ b/tests/Unit/Services/Servers/ContainerRebuildServiceTest.php @@ -1,42 +1,28 @@ . - * - * This software is licensed under the terms of the MIT license. - * https://opensource.org/licenses/MIT - */ namespace Tests\Unit\Services\Servers; use Exception; use Mockery as m; use Tests\TestCase; -use Illuminate\Log\Writer; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use GuzzleHttp\Exception\RequestException; -use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Services\Servers\ContainerRebuildService; -use Pterodactyl\Contracts\Repository\ServerRepositoryInterface; -use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface as DaemonServerRepositoryInterface; +use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface; class ContainerRebuildServiceTest extends TestCase { /** - * @var \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface + * @var \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface|\Mockery\Mock */ - protected $daemonServerRepository; + protected $repository; /** * @var \GuzzleHttp\Exception\RequestException */ protected $exception; - /** - * @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface - */ - protected $repository; - /** * @var \Pterodactyl\Models\Server */ @@ -47,11 +33,6 @@ class ContainerRebuildServiceTest extends TestCase */ protected $service; - /** - * @var \Illuminate\Log\Writer - */ - protected $writer; - /** * Setup tests. */ @@ -59,81 +40,33 @@ class ContainerRebuildServiceTest extends TestCase { parent::setUp(); - $this->daemonServerRepository = m::mock(DaemonServerRepositoryInterface::class); $this->exception = m::mock(RequestException::class)->makePartial(); $this->repository = m::mock(ServerRepositoryInterface::class); - $this->writer = m::mock(Writer::class); $this->server = factory(Server::class)->make(['node_id' => 1]); - - $this->service = new ContainerRebuildService( - $this->daemonServerRepository, - $this->repository, - $this->writer - ); + $this->service = new ContainerRebuildService($this->repository); } /** - * Test that a server is marked for rebuild when it's model is passed to the function. + * Test that a server is marked for rebuild. */ - public function testServerShouldBeMarkedForARebuildWhenModelIsPassed() + public function testServerIsMarkedForRebuild() { - $this->repository->shouldNotReceive('find'); - $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($this->server->uuid)->once()->andReturnSelf() - ->shouldReceive('rebuild')->withNoArgs()->once()->andReturnNull(); + $this->repository->shouldReceive('setServer')->with($this->server)->once()->andReturnSelf() + ->shouldReceive('rebuild')->withNoArgs()->once()->andReturn(new Response); - $this->service->rebuild($this->server); - } - - /** - * Test that a server is marked for rebuild when the ID of the server is passed to the function. - */ - public function testServerShouldBeMarkedForARebuildWhenServerIdIsPassed() - { - $this->repository->shouldReceive('find')->with($this->server->id)->once()->andReturn($this->server); - - $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($this->server->uuid)->once()->andReturnSelf() - ->shouldReceive('rebuild')->withNoArgs()->once()->andReturnNull(); - - $this->service->rebuild($this->server->id); + $this->service->handle($this->server); } /** * Test that an exception thrown by guzzle is rendered as a displayable exception. - */ - public function testExceptionThrownByGuzzleShouldBeReRenderedAsDisplayable() - { - $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id) - ->once()->andThrow($this->exception); - - $this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnSelf() - ->shouldReceive('getStatusCode')->withNoArgs()->once()->andReturn(400); - - $this->writer->shouldReceive('warning')->with($this->exception)->once()->andReturnNull(); - - try { - $this->service->rebuild($this->server); - } catch (Exception $exception) { - $this->assertInstanceOf(DisplayException::class, $exception); - $this->assertEquals( - trans('admin/server.exceptions.daemon_exception', ['code' => 400]), - $exception->getMessage() - ); - } - } - - /** - * Test that an exception thrown by something other than guzzle is not transformed to a displayable. * - * @expectedException \Exception + * @expectedException \Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException */ - public function testExceptionNotThrownByGuzzleShouldNotBeTransformedToDisplayable() + public function testExceptionThrownByGuzzle() { - $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id) - ->once()->andThrow(new Exception()); + $this->repository->shouldReceive('setServer')->with($this->server)->once()->andThrow($this->exception); - $this->service->rebuild($this->server); + $this->service->handle($this->server); } } diff --git a/tests/Unit/Services/Servers/DetailsModificationServiceTest.php b/tests/Unit/Services/Servers/DetailsModificationServiceTest.php index 3d04b0106..410ec5b95 100644 --- a/tests/Unit/Services/Servers/DetailsModificationServiceTest.php +++ b/tests/Unit/Services/Servers/DetailsModificationServiceTest.php @@ -13,6 +13,7 @@ use Exception; use Mockery as m; use Tests\TestCase; use Illuminate\Log\Writer; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use GuzzleHttp\Exception\RequestException; use Illuminate\Database\ConnectionInterface; @@ -183,13 +184,12 @@ class DetailsModificationServiceTest extends TestCase 'image' => 'new/image', ])->once()->andReturnNull(); - $this->daemonServerRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($server->uuid)->once()->andReturnSelf() + $this->daemonServerRepository->shouldReceive('setServer')->with($server)->once()->andReturnSelf() ->shouldReceive('update')->with([ 'build' => [ 'image' => 'new/image', ], - ])->once()->andReturnNull(); + ])->once()->andReturn(new Response); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); @@ -211,13 +211,12 @@ class DetailsModificationServiceTest extends TestCase 'image' => 'new/image', ])->once()->andReturnNull(); - $this->daemonServerRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($server->uuid)->once()->andReturnSelf() + $this->daemonServerRepository->shouldReceive('setServer')->with($server)->once()->andReturnSelf() ->shouldReceive('update')->with([ 'build' => [ 'image' => 'new/image', ], - ])->once()->andReturnNull(); + ])->once()->andReturn(new Response); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); @@ -238,7 +237,7 @@ class DetailsModificationServiceTest extends TestCase 'image' => 'new/image', ])->once()->andReturnNull(); - $this->daemonServerRepository->shouldReceive('setNode')->andThrow($this->exception); + $this->daemonServerRepository->shouldReceive('setServer')->andThrow($this->exception); $this->connection->shouldReceive('rollBack')->withNoArgs()->once()->andReturnNull(); $this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('getStatusCode')->withNoArgs()->once()->andReturn(400); diff --git a/tests/Unit/Services/Servers/ReinstallServerServiceTest.php b/tests/Unit/Services/Servers/ReinstallServerServiceTest.php index 82f018670..349aa571a 100644 --- a/tests/Unit/Services/Servers/ReinstallServerServiceTest.php +++ b/tests/Unit/Services/Servers/ReinstallServerServiceTest.php @@ -12,11 +12,10 @@ namespace Tests\Unit\Services\Servers; use Exception; use Mockery as m; use Tests\TestCase; -use Illuminate\Log\Writer; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use GuzzleHttp\Exception\RequestException; use Illuminate\Database\ConnectionInterface; -use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Services\Servers\ReinstallServerService; use Pterodactyl\Contracts\Repository\ServerRepositoryInterface; use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface as DaemonServerRepositoryInterface; @@ -53,11 +52,6 @@ class ReinstallServerServiceTest extends TestCase */ protected $service; - /** - * @var \Illuminate\Log\Writer - */ - protected $writer; - /** * Setup tests. */ @@ -69,15 +63,13 @@ class ReinstallServerServiceTest extends TestCase $this->database = m::mock(ConnectionInterface::class); $this->exception = m::mock(RequestException::class)->makePartial(); $this->repository = m::mock(ServerRepositoryInterface::class); - $this->writer = m::mock(Writer::class); $this->server = factory(Server::class)->make(['node_id' => 1]); $this->service = new ReinstallServerService( $this->database, $this->daemonServerRepository, - $this->repository, - $this->writer + $this->repository ); } @@ -94,9 +86,8 @@ class ReinstallServerServiceTest extends TestCase 'installed' => 0, ])->once()->andReturnNull(); - $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($this->server->uuid)->once()->andReturnSelf() - ->shouldReceive('reinstall')->withNoArgs()->once()->andReturnNull(); + $this->daemonServerRepository->shouldReceive('setServer')->with($this->server)->once()->andReturnSelf() + ->shouldReceive('reinstall')->withNoArgs()->once()->andReturn(new Response); $this->database->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->reinstall($this->server); @@ -115,9 +106,8 @@ class ReinstallServerServiceTest extends TestCase 'installed' => 0, ])->once()->andReturnNull(); - $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($this->server->uuid)->once()->andReturnSelf() - ->shouldReceive('reinstall')->withNoArgs()->once()->andReturnNull(); + $this->daemonServerRepository->shouldReceive('setServer')->with($this->server)->once()->andReturnSelf() + ->shouldReceive('reinstall')->withNoArgs()->once()->andReturn(new Response); $this->database->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->service->reinstall($this->server->id); @@ -125,6 +115,8 @@ class ReinstallServerServiceTest extends TestCase /** * Test that an exception thrown by guzzle is rendered as a displayable exception. + * + * @expectedException \Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException */ public function testExceptionThrownByGuzzleShouldBeReRenderedAsDisplayable() { @@ -134,23 +126,9 @@ class ReinstallServerServiceTest extends TestCase 'installed' => 0, ])->once()->andReturnNull(); - $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id) - ->once()->andThrow($this->exception); + $this->daemonServerRepository->shouldReceive('setServer')->with($this->server)->once()->andThrow($this->exception); - $this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnSelf() - ->shouldReceive('getStatusCode')->withNoArgs()->once()->andReturn(400); - - $this->writer->shouldReceive('warning')->with($this->exception)->once()->andReturnNull(); - - try { - $this->service->reinstall($this->server); - } catch (Exception $exception) { - $this->assertInstanceOf(DisplayException::class, $exception); - $this->assertEquals( - trans('admin/server.exceptions.daemon_exception', ['code' => 400]), - $exception->getMessage() - ); - } + $this->service->reinstall($this->server); } /** @@ -166,8 +144,7 @@ class ReinstallServerServiceTest extends TestCase 'installed' => 0, ])->once()->andReturnNull(); - $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id) - ->once()->andThrow(new Exception()); + $this->daemonServerRepository->shouldReceive('setServer')->with($this->server)->once()->andThrow(new Exception()); $this->service->reinstall($this->server); } diff --git a/tests/Unit/Services/Servers/ServerCreationServiceTest.php b/tests/Unit/Services/Servers/ServerCreationServiceTest.php index b50ad1d84..51ed61912 100644 --- a/tests/Unit/Services/Servers/ServerCreationServiceTest.php +++ b/tests/Unit/Services/Servers/ServerCreationServiceTest.php @@ -4,6 +4,7 @@ namespace Tests\Unit\Services\Servers; use Mockery as m; use Tests\TestCase; +use Pterodactyl\Models\Node; use Pterodactyl\Models\User; use Tests\Traits\MocksUuids; use Pterodactyl\Models\Server; @@ -132,7 +133,10 @@ class ServerCreationServiceTest extends TestCase ])->once()->andReturn(true); $this->configurationStructureService->shouldReceive('handle')->with($model)->once()->andReturn(['test' => 'struct']); - $this->daemonServerRepository->shouldReceive('setNode')->with($model->node_id)->once()->andReturnSelf(); + $node = factory(Node::class)->make(); + $this->nodeRepository->shouldReceive('find')->with($model->node_id)->once()->andReturn($node); + + $this->daemonServerRepository->shouldReceive('setNode')->with($node)->once()->andReturnSelf(); $this->daemonServerRepository->shouldReceive('create')->with(['test' => 'struct'], ['start_on_completion' => false])->once(); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); @@ -158,7 +162,10 @@ class ServerCreationServiceTest extends TestCase $this->validatorService->shouldReceive('setUserLevel')->once()->andReturnNull(); $this->validatorService->shouldReceive('handle')->once()->andReturn(collect([])); $this->configurationStructureService->shouldReceive('handle')->once()->andReturn([]); - $this->daemonServerRepository->shouldReceive('setNode')->with($model->node_id)->once()->andThrow($this->exception); + + $node = factory(Node::class)->make(); + $this->nodeRepository->shouldReceive('find')->with($model->node_id)->once()->andReturn($node); + $this->daemonServerRepository->shouldReceive('setNode')->with($node)->once()->andThrow($this->exception); $this->connection->shouldReceive('rollBack')->withNoArgs()->once()->andReturnNull(); try { diff --git a/tests/Unit/Services/Servers/ServerDeletionServiceTest.php b/tests/Unit/Services/Servers/ServerDeletionServiceTest.php index 26d7fa103..eb5ffc244 100644 --- a/tests/Unit/Services/Servers/ServerDeletionServiceTest.php +++ b/tests/Unit/Services/Servers/ServerDeletionServiceTest.php @@ -13,6 +13,7 @@ use Exception; use Mockery as m; use Tests\TestCase; use Illuminate\Log\Writer; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use GuzzleHttp\Exception\RequestException; use Illuminate\Database\ConnectionInterface; @@ -111,9 +112,8 @@ class ServerDeletionServiceTest extends TestCase */ public function testServerCanBeDeletedWithoutForce() { - $this->daemonServerRepository->shouldReceive('setNode')->with($this->model->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($this->model->uuid)->once()->andReturnSelf() - ->shouldReceive('delete')->withNoArgs()->once()->andReturnNull(); + $this->daemonServerRepository->shouldReceive('setServer')->with($this->model)->once()->andReturnSelf() + ->shouldReceive('delete')->withNoArgs()->once()->andReturn(new Response); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); $this->databaseRepository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() @@ -133,8 +133,7 @@ class ServerDeletionServiceTest extends TestCase */ public function testServerShouldBeDeletedEvenWhenFailureOccursIfForceIsSet() { - $this->daemonServerRepository->shouldReceive('setNode')->with($this->model->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($this->model->uuid)->once()->andReturnSelf() + $this->daemonServerRepository->shouldReceive('setServer')->with($this->model)->once()->andReturnSelf() ->shouldReceive('delete')->withNoArgs()->once()->andThrow($this->exception); $this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnNull(); @@ -157,7 +156,7 @@ class ServerDeletionServiceTest extends TestCase */ public function testExceptionShouldBeThrownIfDaemonReturnsAnErrorAndForceIsNotSet() { - $this->daemonServerRepository->shouldReceive('setNode->setAccessServer->delete')->once()->andThrow($this->exception); + $this->daemonServerRepository->shouldReceive('setServer->delete')->once()->andThrow($this->exception); $this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnNull(); $this->writer->shouldReceive('warning')->with($this->exception)->once()->andReturnNull(); @@ -179,9 +178,8 @@ class ServerDeletionServiceTest extends TestCase $this->repository->shouldReceive('setColumns')->with(['id', 'node_id', 'uuid'])->once()->andReturnSelf() ->shouldReceive('find')->with($this->model->id)->once()->andReturn($this->model); - $this->daemonServerRepository->shouldReceive('setNode')->with($this->model->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($this->model->uuid)->once()->andReturnSelf() - ->shouldReceive('delete')->withNoArgs()->once()->andReturn(1); + $this->daemonServerRepository->shouldReceive('setServer')->with($this->model)->once()->andReturnSelf() + ->shouldReceive('delete')->withNoArgs()->once()->andReturn(new Response); $this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull(); $this->databaseRepository->shouldReceive('setColumns')->with('id')->once()->andReturnSelf() diff --git a/tests/Unit/Services/Servers/StartupModificationServiceTest.php b/tests/Unit/Services/Servers/StartupModificationServiceTest.php index 0c06b1799..fe8392cfe 100644 --- a/tests/Unit/Services/Servers/StartupModificationServiceTest.php +++ b/tests/Unit/Services/Servers/StartupModificationServiceTest.php @@ -12,6 +12,7 @@ namespace Tests\Unit\Services\Servers; use Mockery as m; use Tests\TestCase; use Pterodactyl\Models\User; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use Illuminate\Database\ConnectionInterface; use Pterodactyl\Services\Servers\EnvironmentService; @@ -88,11 +89,10 @@ class StartupModificationServiceTest extends TestCase ], ['variable_value' => 'stored-value'])->once()->andReturnNull(); $this->environmentService->shouldReceive('handle')->with($model)->once()->andReturn(['env']); - $this->daemonServerRepository->shouldReceive('setNode')->with($model->node_id)->once()->andReturnSelf(); - $this->daemonServerRepository->shouldReceive('setAccessServer')->with($model->uuid)->once()->andReturnSelf(); + $this->daemonServerRepository->shouldReceive('setServer')->with($model)->once()->andReturnSelf(); $this->daemonServerRepository->shouldReceive('update')->with([ 'build' => ['env|overwrite' => ['env']], - ])->once()->andReturnSelf(); + ])->once()->andReturn(new Response); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); @@ -135,8 +135,7 @@ class StartupModificationServiceTest extends TestCase $this->environmentService->shouldReceive('handle')->with($model)->once()->andReturn(['env']); - $this->daemonServerRepository->shouldReceive('setNode')->with($model->node_id)->once()->andReturnSelf(); - $this->daemonServerRepository->shouldReceive('setAccessServer')->with($model->uuid)->once()->andReturnSelf(); + $this->daemonServerRepository->shouldReceive('setServer')->with($model)->once()->andReturnSelf(); $this->daemonServerRepository->shouldReceive('update')->with([ 'build' => [ 'env|overwrite' => ['env'], @@ -147,7 +146,7 @@ class StartupModificationServiceTest extends TestCase 'pack' => 'xyz987', 'skip_scripts' => false, ], - ])->once()->andReturnSelf(); + ])->once()->andReturn(new Response); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); diff --git a/tests/Unit/Services/Servers/SuspensionServiceTest.php b/tests/Unit/Services/Servers/SuspensionServiceTest.php index e899ca747..116014277 100644 --- a/tests/Unit/Services/Servers/SuspensionServiceTest.php +++ b/tests/Unit/Services/Servers/SuspensionServiceTest.php @@ -13,6 +13,7 @@ use Exception; use Mockery as m; use Tests\TestCase; use Illuminate\Log\Writer; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use GuzzleHttp\Exception\RequestException; use Illuminate\Database\ConnectionInterface; @@ -104,9 +105,8 @@ class SuspensionServiceTest extends TestCase $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->server->id, ['suspended' => true])->once()->andReturnNull(); - $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($this->server->uuid)->once()->andReturnSelf() - ->shouldReceive('suspend')->withNoArgs()->once()->andReturnNull(); + $this->daemonServerRepository->shouldReceive('setServer')->with($this->server)->once()->andReturnSelf() + ->shouldReceive('suspend')->withNoArgs()->once()->andReturn(new Response); $this->database->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->assertTrue($this->service->toggle($this->server)); @@ -123,9 +123,8 @@ class SuspensionServiceTest extends TestCase $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->server->id, ['suspended' => false])->once()->andReturnNull(); - $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id)->once()->andReturnSelf() - ->shouldReceive('setAccessServer')->with($this->server->uuid)->once()->andReturnSelf() - ->shouldReceive('unsuspend')->withNoArgs()->once()->andReturnNull(); + $this->daemonServerRepository->shouldReceive('setServer')->with($this->server)->once()->andReturnSelf() + ->shouldReceive('unsuspend')->withNoArgs()->once()->andReturn(new Response); $this->database->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); $this->assertTrue($this->service->toggle($this->server, 'unsuspend')); @@ -162,7 +161,7 @@ class SuspensionServiceTest extends TestCase $this->repository->shouldReceive('withoutFreshModel')->withNoArgs()->once()->andReturnSelf() ->shouldReceive('update')->with($this->server->id, ['suspended' => true])->once()->andReturnNull(); - $this->daemonServerRepository->shouldReceive('setNode')->with($this->server->node_id) + $this->daemonServerRepository->shouldReceive('setServer')->with($this->server) ->once()->andThrow($this->exception); $this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnSelf() diff --git a/tests/Unit/Services/Subusers/SubuserUpdateServiceTest.php b/tests/Unit/Services/Subusers/SubuserUpdateServiceTest.php index 550411337..6ca75c0fe 100644 --- a/tests/Unit/Services/Subusers/SubuserUpdateServiceTest.php +++ b/tests/Unit/Services/Subusers/SubuserUpdateServiceTest.php @@ -12,6 +12,7 @@ namespace Tests\Unit\Services\Subusers; use Mockery as m; use Tests\TestCase; use Pterodactyl\Models\User; +use GuzzleHttp\Psr7\Response; use Pterodactyl\Models\Server; use Pterodactyl\Models\Subuser; use Tests\Traits\MocksRequestException; @@ -90,8 +91,8 @@ class SubuserUpdateServiceTest extends TestCase $this->permissionService->shouldReceive('handle')->with($subuser->id, ['some-permission'])->once()->andReturnNull(); $this->keyProviderService->shouldReceive('handle')->with($subuser->server, $subuser->user, false)->once()->andReturn('test123'); - $this->daemonRepository->shouldReceive('setNode')->with($subuser->server->node_id)->once()->andReturnSelf(); - $this->daemonRepository->shouldReceive('revokeAccessKey')->with('test123')->once()->andReturnNull(); + $this->daemonRepository->shouldReceive('setServer')->with($subuser->server)->once()->andReturnSelf(); + $this->daemonRepository->shouldReceive('revokeAccessKey')->with('test123')->once()->andReturn(new Response); $this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull(); @@ -116,7 +117,7 @@ class SubuserUpdateServiceTest extends TestCase $this->permissionService->shouldReceive('handle')->with($subuser->id, [])->once()->andReturnNull(); $this->keyProviderService->shouldReceive('handle')->with($subuser->server, $subuser->user, false)->once()->andReturn('test123'); - $this->daemonRepository->shouldReceive('setNode')->with($subuser->server->node_id)->once()->andThrow($this->getExceptionMock()); + $this->daemonRepository->shouldReceive('setServer')->with($subuser->server)->once()->andThrow($this->getExceptionMock()); $this->connection->shouldReceive('rollBack')->withNoArgs()->once()->andReturnNull(); try { From 21a78f465b31a77becce78c9a4564c6bbf44ffad Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Fri, 5 Jan 2018 18:44:20 -0600 Subject: [PATCH 05/20] Fix node return being too strict --- app/Contracts/Repository/Daemon/BaseRepositoryInterface.php | 4 ++-- app/Repositories/Daemon/BaseRepository.php | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/Contracts/Repository/Daemon/BaseRepositoryInterface.php b/app/Contracts/Repository/Daemon/BaseRepositoryInterface.php index 398469265..b34c7420e 100644 --- a/app/Contracts/Repository/Daemon/BaseRepositoryInterface.php +++ b/app/Contracts/Repository/Daemon/BaseRepositoryInterface.php @@ -19,9 +19,9 @@ interface BaseRepositoryInterface /** * Return the node model being used. * - * @return \Pterodactyl\Models\Node + * @return \Pterodactyl\Models\Node|null */ - public function getNode(): Node; + public function getNode(); /** * Set the Server model to use when requesting information from the Daemon. diff --git a/app/Repositories/Daemon/BaseRepository.php b/app/Repositories/Daemon/BaseRepository.php index 8b401526a..e15b17ce1 100644 --- a/app/Repositories/Daemon/BaseRepository.php +++ b/app/Repositories/Daemon/BaseRepository.php @@ -28,7 +28,7 @@ abstract class BaseRepository implements BaseRepositoryInterface private $token; /** - * @var \Pterodactyl\Models\Node + * @var \Pterodactyl\Models\Node|null */ private $node; @@ -65,9 +65,9 @@ abstract class BaseRepository implements BaseRepositoryInterface /** * Return the node model being used. * - * @return \Pterodactyl\Models\Node + * @return \Pterodactyl\Models\Node|null */ - public function getNode(): Node + public function getNode() { return $this->node; } From b3d7c6f1af704ee2fa441f08b4faed9398484237 Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Fri, 5 Jan 2018 18:49:00 -0600 Subject: [PATCH 06/20] Fix search weighting for servers --- app/Models/Server.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/app/Models/Server.php b/app/Models/Server.php index 6b5af5112..9f81584c8 100644 --- a/app/Models/Server.php +++ b/app/Models/Server.php @@ -119,13 +119,13 @@ class Server extends Model implements CleansAttributes, ValidableContract * @var array */ protected $searchableColumns = [ - 'name' => 10, - 'uuidShort' => 9, - 'uuid' => 8, - 'pack.name' => 7, - 'user.email' => 6, - 'user.username' => 6, - 'node.name' => 2, + 'name' => 50, + 'uuidShort' => 10, + 'uuid' => 10, + 'pack.name' => 5, + 'user.email' => 20, + 'user.username' => 20, + 'node.name' => 10, ]; /** From 59f8ae4b50340b2f23c8c0602b653be13c779c2a Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Sat, 6 Jan 2018 12:49:32 -0600 Subject: [PATCH 07/20] Too much grep --- app/Repositories/Eloquent/EloquentRepository.php | 2 +- app/Repositories/Eloquent/PackRepository.php | 2 +- app/Repositories/Eloquent/ServerRepository.php | 2 +- app/Repositories/Eloquent/UserRepository.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/Repositories/Eloquent/EloquentRepository.php b/app/Repositories/Eloquent/EloquentRepository.php index 417b547ce..e285ba318 100644 --- a/app/Repositories/Eloquent/EloquentRepository.php +++ b/app/Repositories/Eloquent/EloquentRepository.php @@ -228,7 +228,7 @@ abstract class EloquentRepository extends Repository implements RepositoryInterf { $instance = $this->getBuilder(); if (is_subclass_of(get_called_class(), SearchableInterface::class) && $this->hasSearchTerm()) { - $instance = $instance->setSearchTerm($this->getSearchTerm()); + $instance = $instance->search($this->getSearchTerm()); } return $instance->get($this->getColumns()); diff --git a/app/Repositories/Eloquent/PackRepository.php b/app/Repositories/Eloquent/PackRepository.php index a199e5500..922e6415a 100644 --- a/app/Repositories/Eloquent/PackRepository.php +++ b/app/Repositories/Eloquent/PackRepository.php @@ -47,7 +47,7 @@ class PackRepository extends EloquentRepository implements PackRepositoryInterfa public function paginateWithEggAndServerCount(): LengthAwarePaginator { return $this->getBuilder()->with('egg')->withCount('servers') - ->setSearchTerm($this->getSearchTerm()) + ->search($this->getSearchTerm()) ->paginate(50, $this->getColumns()); } } diff --git a/app/Repositories/Eloquent/ServerRepository.php b/app/Repositories/Eloquent/ServerRepository.php index 02ecef2f1..4bf058a72 100644 --- a/app/Repositories/Eloquent/ServerRepository.php +++ b/app/Repositories/Eloquent/ServerRepository.php @@ -34,7 +34,7 @@ class ServerRepository extends EloquentRepository implements ServerRepositoryInt */ public function getAllServers(int $paginate): LengthAwarePaginator { - $instance = $this->getBuilder()->with('node', 'user', 'allocation')->setSearchTerm($this->getSearchTerm()); + $instance = $this->getBuilder()->with('node', 'user', 'allocation')->search($this->getSearchTerm()); return $instance->paginate($paginate, $this->getColumns()); } diff --git a/app/Repositories/Eloquent/UserRepository.php b/app/Repositories/Eloquent/UserRepository.php index 3a0a07942..008916de2 100644 --- a/app/Repositories/Eloquent/UserRepository.php +++ b/app/Repositories/Eloquent/UserRepository.php @@ -46,7 +46,7 @@ class UserRepository extends EloquentRepository implements UserRepositoryInterfa 'id', 'email', 'username', 'name_first', 'name_last', ]); - $instance = $this->getBuilder()->setSearchTerm($query)->get($this->getColumns()); + $instance = $this->getBuilder()->search($query)->get($this->getColumns()); return $instance->transform(function ($item) { $item->md5 = md5(strtolower($item->email)); From a75b15cd8d3aeebe58425c4088e7cc1e71124a59 Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Sat, 6 Jan 2018 12:53:17 -0600 Subject: [PATCH 08/20] closes #852 --- app/Http/Requests/Admin/Node/AllocationFormRequest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Requests/Admin/Node/AllocationFormRequest.php b/app/Http/Requests/Admin/Node/AllocationFormRequest.php index 3cece4efc..777d3033f 100644 --- a/app/Http/Requests/Admin/Node/AllocationFormRequest.php +++ b/app/Http/Requests/Admin/Node/AllocationFormRequest.php @@ -20,7 +20,7 @@ class AllocationFormRequest extends AdminFormRequest { return [ 'allocation_ip' => 'required|string', - 'allocation_alias' => 'sometimes|string|max:255', + 'allocation_alias' => 'sometimes|nullable|string|max:255', 'allocation_ports' => 'required|array', ]; } From adcab5969a68408fddeb9523a2a55e0620ead07c Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Sat, 6 Jan 2018 12:58:30 -0600 Subject: [PATCH 09/20] Fix server description nullablility --- app/Http/Controllers/Admin/ServersController.php | 1 + app/Http/Requests/Admin/ServerFormRequest.php | 5 ++++- app/Services/Servers/ServerCreationService.php | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/Admin/ServersController.php b/app/Http/Controllers/Admin/ServersController.php index e2bfa8fd4..c3e33b964 100644 --- a/app/Http/Controllers/Admin/ServersController.php +++ b/app/Http/Controllers/Admin/ServersController.php @@ -254,6 +254,7 @@ class ServersController extends Controller * @throws \Pterodactyl\Exceptions\DisplayException * @throws \Pterodactyl\Exceptions\Model\DataValidationException * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException + * @throws \Illuminate\Validation\ValidationException */ public function store(ServerFormRequest $request) { diff --git a/app/Http/Requests/Admin/ServerFormRequest.php b/app/Http/Requests/Admin/ServerFormRequest.php index f448a953c..33b9c8ffd 100644 --- a/app/Http/Requests/Admin/ServerFormRequest.php +++ b/app/Http/Requests/Admin/ServerFormRequest.php @@ -21,7 +21,10 @@ class ServerFormRequest extends AdminFormRequest */ public function rules() { - return Server::getCreateRules(); + $rules = Server::getCreateRules(); + $rules['description'][] = 'nullable'; + + return $rules; } /** diff --git a/app/Services/Servers/ServerCreationService.php b/app/Services/Servers/ServerCreationService.php index 82c49000c..4395717ec 100644 --- a/app/Services/Servers/ServerCreationService.php +++ b/app/Services/Servers/ServerCreationService.php @@ -118,7 +118,7 @@ class ServerCreationService 'uuidShort' => str_random(8), 'node_id' => array_get($data, 'node_id'), 'name' => array_get($data, 'name'), - 'description' => array_get($data, 'description', ''), + 'description' => array_get($data, 'description') ?? '', 'skip_scripts' => isset($data['skip_scripts']), 'suspended' => false, 'owner_id' => array_get($data, 'owner_id'), From 4b5ee920bd986e642a4fc6bd2de276a8eb169c09 Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Sat, 6 Jan 2018 13:08:20 -0600 Subject: [PATCH 10/20] Fix logic mistake with findOrFail --- app/Repositories/Eloquent/EggRepository.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Repositories/Eloquent/EggRepository.php b/app/Repositories/Eloquent/EggRepository.php index bfb6738d9..10d27f284 100644 --- a/app/Repositories/Eloquent/EggRepository.php +++ b/app/Repositories/Eloquent/EggRepository.php @@ -32,7 +32,7 @@ class EggRepository extends EloquentRepository implements EggRepositoryInterface public function getWithVariables(int $id): Egg { try { - return $this->getBuilder()->with('variables')->firstOrFail($id, $this->getColumns()); + return $this->getBuilder()->with('variables')->findOrFail($id, $this->getColumns()); } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } @@ -79,7 +79,7 @@ class EggRepository extends EloquentRepository implements EggRepositoryInterface public function getWithExportAttributes(int $id): Egg { try { - return $this->getBuilder()->with('scriptFrom', 'configFrom', 'variables')->find($id, $this->getColumns()); + return $this->getBuilder()->with('scriptFrom', 'configFrom', 'variables')->findOrFail($id, $this->getColumns()); } catch (ModelNotFoundException $exception) { throw new RecordNotFoundException; } From a3bad520cdf6718c31bcb15b09a98cc571724344 Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Sat, 6 Jan 2018 13:19:17 -0600 Subject: [PATCH 11/20] closes #807 --- .../pterodactyl/admin/servers/index.blade.php | 15 +++++++++++++++ .../admin/servers/view/index.blade.php | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/resources/themes/pterodactyl/admin/servers/index.blade.php b/resources/themes/pterodactyl/admin/servers/index.blade.php index ca21e5823..f9a82497a 100644 --- a/resources/themes/pterodactyl/admin/servers/index.blade.php +++ b/resources/themes/pterodactyl/admin/servers/index.blade.php @@ -45,6 +45,7 @@ Node Connection + @foreach ($servers as $server) @@ -64,6 +65,10 @@ Active @endif + + + + @endforeach @@ -78,3 +83,13 @@ @endsection + +@section('footer-scripts') + @parent + +@endsection diff --git a/resources/themes/pterodactyl/admin/servers/view/index.blade.php b/resources/themes/pterodactyl/admin/servers/view/index.blade.php index 6e9855337..58deaa924 100644 --- a/resources/themes/pterodactyl/admin/servers/view/index.blade.php +++ b/resources/themes/pterodactyl/admin/servers/view/index.blade.php @@ -10,7 +10,7 @@ @endsection @section('content-header') -

{{ $server->name }}{{ $server->uuid }}

+

{{ $server->name }}{{ str_limit($server->description) }}