1 <?php namespace Tests\Uploads;
3 use BookStack\Entities\Models\Page;
4 use Illuminate\Http\UploadedFile;
9 * Get the path to a file in the test-data-directory.
11 protected function getTestImageFilePath(?string $fileName = null): string
13 if (is_null($fileName)) {
14 $fileName = 'test-image.png';
17 return base_path('tests/test-data/' . $fileName);
21 * Creates a new temporary image file using the given name,
22 * with the content decoded from the given bas64 file name.
23 * Is generally used for testing sketchy files that could trip AV.
25 protected function newTestImageFromBase64(string $base64FileName, $imageFileName): UploadedFile
27 $imagePath = implode(DIRECTORY_SEPARATOR, [sys_get_temp_dir(), $imageFileName]);
28 $base64FilePath = $this->getTestImageFilePath($base64FileName);
29 $data = file_get_contents($base64FilePath);
30 $decoded = base64_decode($data);
31 file_put_contents($imagePath, $decoded);
32 return new UploadedFile($imagePath, $imageFileName, 'image/png', null, true);
36 * Get a test image that can be uploaded
38 protected function getTestImage(string $fileName, ?string $testDataFileName = null): UploadedFile
40 return new UploadedFile($this->getTestImageFilePath($testDataFileName), $fileName, 'image/png', null, true);
44 * Get the raw file data for the test image.
45 * @return false|string
47 protected function getTestImageContent()
49 return file_get_contents($this->getTestImageFilePath());
53 * Get the path for a test image.
55 protected function getTestImagePath(string $type, string $fileName): string
57 return '/uploads/images/' . $type . '/' . Date('Y-m') . '/' . $fileName;
61 * Uploads an image with the given name.
63 * @param int $uploadedTo
64 * @param string $contentType
65 * @return \Illuminate\Foundation\Testing\TestResponse
67 protected function uploadImage($name, $uploadedTo = 0, $contentType = 'image/png', ?string $testDataFileName = null)
69 $file = $this->getTestImage($name, $testDataFileName);
70 return $this->withHeader('Content-Type', $contentType)
71 ->call('POST', '/images/gallery', ['uploaded_to' => $uploadedTo], [], ['file' => $file], []);
75 * Upload a new gallery image.
76 * Returns the image name.
77 * Can provide a page to relate the image to.
78 * @param Page|null $page
81 protected function uploadGalleryImage(Page $page = null, ?string $testDataFileName = null)
84 $page = Page::query()->first();
87 $imageName = $testDataFileName ?? 'first-image.png';
88 $relPath = $this->getTestImagePath('gallery', $imageName);
89 $this->deleteImage($relPath);
91 $upload = $this->uploadImage($imageName, $page->id, 'image/png', $testDataFileName);
92 $upload->assertStatus(200);
97 'response' => json_decode($upload->getContent()),
102 * Delete an uploaded image.
104 protected function deleteImage(string $relPath)
106 $path = public_path($relPath);
107 if (file_exists($path)) {