]> BookStack Code Mirror - bookstack/blob - tests/Api/TestsApi.php
c566fd8de337fc2401ad796f5eeab483a5ca5e7c
[bookstack] / tests / Api / TestsApi.php
1 <?php
2
3 namespace Tests\Api;
4
5 use BookStack\Auth\User;
6
7 trait TestsApi
8 {
9     protected string $apiTokenId = 'apitoken';
10     protected string $apiTokenSecret = 'password';
11
12     /**
13      * Set the given user as the current logged-in user via the API driver.
14      * This does not ensure API access. The user may still lack required role permissions.
15      */
16     protected function actingAsForApi(User $user): static
17     {
18         parent::actingAs($user, 'api');
19
20         return $this;
21     }
22
23     /**
24      * Set the API editor role as the current user via the API driver.
25      */
26     protected function actingAsApiEditor(): static
27     {
28         $this->actingAs($this->users->editor(), 'api');
29
30         return $this;
31     }
32
33     /**
34      * Set the API admin role as the current user via the API driver.
35      */
36     protected function actingAsApiAdmin(): static
37     {
38         $this->actingAs($this->users->admin(), 'api');
39
40         return $this;
41     }
42
43     /**
44      * Format the given items into a standardised error format.
45      */
46     protected function errorResponse(string $message, int $code): array
47     {
48         return ['error' => ['code' => $code, 'message' => $message]];
49     }
50
51     /**
52      * Get the structure that matches a permission error response.
53      */
54     protected function permissionErrorResponse(): array
55     {
56         return $this->errorResponse('You do not have permission to perform the requested action.', 403);
57     }
58
59     /**
60      * Format the given (field_name => ["messages"]) array
61      * into a standard validation response format.
62      */
63     protected function validationResponse(array $messages): array
64     {
65         $err = $this->errorResponse('The given data was invalid.', 422);
66         $err['error']['validation'] = $messages;
67
68         return $err;
69     }
70
71     /**
72      * Get an approved API auth header.
73      */
74     protected function apiAuthHeader(): array
75     {
76         return [
77             'Authorization' => "Token {$this->apiTokenId}:{$this->apiTokenSecret}",
78         ];
79     }
80 }