Skip to content

Commit

Permalink
tests for ImageAsset
Browse files Browse the repository at this point in the history
  • Loading branch information
passchn committed Sep 21, 2023
1 parent 14d4e3b commit 95065d5
Show file tree
Hide file tree
Showing 7 changed files with 132 additions and 24 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@
/vendor/
/.idea/
/node_modules
webroot/modified
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"@phpstan",
"@psalm"
],
"test": "phpunit",
"stan-setup": "cp composer.json composer.backup && composer require --dev phpstan/phpstan:~1.9.0 psalm/phar:~5.4.0 && mv composer.backup composer.json",
"lowest-setup": "composer update --prefer-lowest --prefer-stable --prefer-dist --no-interaction && cp composer.json composer.backup && composer require --dev dereuromark/composer-prefer-lowest && mv composer.backup composer.json"
},
Expand Down
26 changes: 26 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?xml version="1.0"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" bootstrap="tests/bootstrap.php" colors="true" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<php>
<!-- E_ALL => 32767 -->
<!-- E_ALL & ~E_USER_DEPRECATED => 16383 -->
<ini name="error_reporting" value="16383"/>
</php>
<testsuites>
<testsuite name="assets">
<directory>tests/</directory>
</testsuite>
</testsuites>
<listeners>
<listener class="Cake\TestSuite\Fixture\FixtureInjector">
<arguments>
<object class="Cake\TestSuite\Fixture\FixtureManager"/>
</arguments>
</listener>
</listeners>
<!-- Prevent coverage reports from looking in tests, vendors, config folders -->
<coverage>
<include>
<directory suffix=".php">src/</directory>
</include>
</coverage>
</phpunit>
10 changes: 9 additions & 1 deletion src/Model/Entity/Asset.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,15 @@ public function exists(): bool
*/
protected function _getAbsolutePath(): string
{
return ROOT . DS . $this->directory . DS . $this->filename;
$relativeOrAbsolute = DS . ltrim($this->directory . DS . $this->filename, DS);
if (is_readable($relativeOrAbsolute)) {
return $relativeOrAbsolute;
}
$path = ROOT . $relativeOrAbsolute;
if (is_readable($path)) {
return $path;
}
throw new \Exception('Could not find image file.');
}

/**
Expand Down
52 changes: 29 additions & 23 deletions src/Utilities/ImageAsset.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,21 @@

namespace Assets\Utilities;

use App\View\AppView;
use Assets\Error\FileNotFoundException;
use Assets\Error\FilterNotFoundException;
use Assets\Error\UnkownErrorException;
use Assets\Model\Entity\Asset;
use Cake\Core\Configure;
use Cake\I18n\FrozenTime;
use Cake\View\Helper\HtmlHelper;
use Cake\View\View;
use Intervention\Image\Image;
use Intervention\Image\ImageManager;
use InvalidArgumentException;
use Nette\Utils\FileSystem;
use Nette\Utils\Json;
use Nette\Utils\Strings;
use SplFileInfo;

/**
* To be called through Assets::getImage() with MimeType image/*
Expand Down Expand Up @@ -79,34 +81,38 @@ public function __construct(Asset $asset, int $quality = 90)
* @param array $options - optional:
* - title (string): for alt-parameter in html-output
* - quality (int): for jpg compression
* @throws \Exception
* @throws \InvalidArgumentException when no file was found
* @return \Assets\Utilities\ImageAsset
*/
public static function createFromPath(string $path, array $options = [])
{
$absolute_path = null;
$img_dir = WWW_ROOT . Configure::read('App.imageBaseUrl');
$absolute_path = false;
if (file_exists($path)) {
$absolute_path = $path;
} elseif (file_exists($img_dir . $path)) {
$absolute_path = $img_dir . $path;
} else {
$img_dir = WWW_ROOT . ltrim((string)Configure::read('App.imageBaseUrl'), DS);
if (file_exists($img_dir . $path)) {
$absolute_path = $img_dir . $path;
}
}

if (!$absolute_path) {
throw new \Exception("Could not find image with path {$path}.");
if ($absolute_path === false || !is_readable($absolute_path)) {
throw new InvalidArgumentException("Could not find image with path {$path}.");
}

$splFileInfo = new \SplFileInfo($absolute_path);

$asset = new Asset();
$asset->id = md5($path);
$asset->filename = $splFileInfo->getFilename();
$asset->directory = ltrim(str_replace(ROOT, '', $splFileInfo->getPath()), DS);
$asset->mimetype = mime_content_type($absolute_path) ?: 'unknown';
$asset->title = $options['title'] ?? null;
$asset->description = null;
$asset->modified = FrozenTime::createFromTimestamp($splFileInfo->getMTime());
$asset->created = $asset->modified;
$splFileInfo = new SplFileInfo($absolute_path);
$fileMTime = FrozenTime::createFromTimestamp($splFileInfo->getMTime());

$asset = new Asset([
'id' => md5($path),
'filename' => $splFileInfo->getFilename(),
'directory' => ltrim(str_replace(ROOT, '', $splFileInfo->getPath()), DS),
'mimetype' => mime_content_type($absolute_path) ?: 'unknown',
'title' => $options['title'] ?? null,
'description' => null,
'modified' => $fileMTime,
'created' => $fileMTime,
]);

$quality = $options['quality'] ?? 90;

Expand Down Expand Up @@ -251,7 +257,7 @@ public function getPath(): string
public function getHTML(array $params = []): string
{
$path = $this->getPath();
$html = new HtmlHelper(new AppView());
$html = new HtmlHelper(new View());

if (!$this->image) {
$manager = $this->getImageManager();
Expand Down Expand Up @@ -313,7 +319,7 @@ private function getFilename(): string
* @throws \Nette\Utils\JsonException
* @throws \Assets\Error\FileNotFoundException
*/
private function getRelativePath(?\SplFileInfo $file = null): string
private function getRelativePath(?SplFileInfo $file = null): string
{
if ($file) {
return $this->outputDirectory . $file->getFilename();
Expand Down Expand Up @@ -377,12 +383,12 @@ private function getAssetIdentifier(): string
* @return \SplFileInfo|null
* @throws \Nette\Utils\JsonException
*/
private function getFile(): ?\SplFileInfo
private function getFile(): ?SplFileInfo
{
$path = WWW_ROOT . ltrim($this->outputDirectory, DS) . $this->getFilename() . '.' . $this->format;

if (file_exists($path)) {
return new \SplFileInfo($path);
return new SplFileInfo($path);
}

return null;
Expand Down
66 changes: 66 additions & 0 deletions tests/Utilities/ImageAssetTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);

namespace Assets\Test\Utilities;

use Assets\Utilities\ImageAsset;
use Cake\TestSuite\TestCase;

class ImageAssetTest extends TestCase
{
protected const DATA_IMAGES = __DIR__ . DS;

protected function setUp(): void
{
parent::setUp();
if (!defined('PLUGIN_ROOT')) {
include __DIR__ . DS . '..' . DS . 'bootstrap.php';
}
}

public function testCreateFromPathWithInvalidPath(): void
{
static::expectException(\InvalidArgumentException::class);
$image = ImageAsset::createFromPath('invalid-path');
}

public function testCreateFromPathWithValidPath(): void
{
$path = static::DATA_IMAGES . 'cake.jpg';
$image = ImageAsset::createFromPath($path);
static::assertInstanceOf(ImageAsset::class, $image);

$renderedPath = WWW_ROOT . $image->toWebp()->scaleWidth(120)->getPath();
static::assertFileExists($renderedPath);
$splFileInfo = new \SplFileInfo($renderedPath);
static::assertEquals('image/webp', mime_content_type($renderedPath));
static::assertEquals(6178, $splFileInfo->getSize());

$renderedPathOfLargeJpg = WWW_ROOT . $image->toJpg()->scaleWidth(240)->getPath();
static::assertFileExists($renderedPathOfLargeJpg);
$splFileInfoJpg = new \SplFileInfo($renderedPathOfLargeJpg);
static::assertEquals('image/jpeg', mime_content_type($renderedPathOfLargeJpg));
static::assertEquals(22336, $splFileInfoJpg->getSize());
}

public function testHtmlCreation(): void
{
$path = static::DATA_IMAGES . 'cake.jpg';
$image = ImageAsset::createFromPath($path);
static::assertInstanceOf(ImageAsset::class, $image);

$html = $image
->scaleWidth(230)
->setCSS('some-css')
->setLazyLoading(false)
->getHTML([
'data-test' => 123,
]);

static::assertNotEmpty($html);
static::assertStringContainsString('width="230"', $html);
static::assertStringContainsString('class="some-css"', $html);
static::assertStringContainsString('data-test="123"', $html);
static::assertStringContainsString('loading="eager"', $html);
}
}
Binary file added tests/Utilities/cake.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 95065d5

Please sign in to comment.