| 1 |
<?php |
| 2 |
|
| 3 |
declare( strict_types=1 ); |
| 4 |
|
| 5 |
namespace Tests\Integration\Module\Views; |
| 6 |
|
| 7 |
use Packetery\Module\Framework\WpAdapter; |
| 8 |
use Packetery\Module\Views\UrlBuilder; |
| 9 |
use Tests\Integration\AbstractIntegrationTestCase; |
| 10 |
|
| 11 |
class UrlBuilderTest extends AbstractIntegrationTestCase { |
| 12 |
private function createUrlBuilder(): UrlBuilder { |
| 13 |
/** @var WpAdapter $wpAdapter */ |
| 14 |
$wpAdapter = $this->container->getByType( WpAdapter::class ); |
| 15 |
|
| 16 |
return new UrlBuilder( $wpAdapter ); |
| 17 |
} |
| 18 |
|
| 19 |
public function testBuildAssetUrlReturnsNullForMissingAsset(): void { |
| 20 |
$urlBuilder = $this->createUrlBuilder(); |
| 21 |
|
| 22 |
self::assertNull( $urlBuilder->buildAssetUrl( 'temp/does-not-exist-' . uniqid( '', true ) . '.txt' ) ); |
| 23 |
} |
| 24 |
|
| 25 |
public function testBuildAssetUrlReturnsVersionedUrlForExistingFile(): void { |
| 26 |
$urlBuilder = $this->createUrlBuilder(); |
| 27 |
|
| 28 |
$directoryPath = PACKETERY_PLUGIN_DIR . '/temp/tests'; |
| 29 |
$filePath = $directoryPath . '/urlbuilder-' . uniqid( '', true ) . '.txt'; |
| 30 |
$relativeAsset = 'temp/tests/' . basename( $filePath ); |
| 31 |
|
| 32 |
if ( ! is_dir( $directoryPath ) ) { |
| 33 |
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir |
| 34 |
mkdir( $directoryPath, 0777, true ); |
| 35 |
} |
| 36 |
|
| 37 |
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents |
| 38 |
file_put_contents( $filePath, 'test' ); |
| 39 |
clearstatcache( true, $filePath ); |
| 40 |
|
| 41 |
$url = $urlBuilder->buildAssetUrl( $relativeAsset ); |
| 42 |
|
| 43 |
self::assertNotNull( $url ); |
| 44 |
self::assertStringEndsWith( $relativeAsset, (string) preg_replace( '/\?.*/', '', (string) $url ) ); |
| 45 |
|
| 46 |
$modificationTime = filemtime( $filePath ); |
| 47 |
$version = md5( (string) $modificationTime ); |
| 48 |
|
| 49 |
$query = (string) wp_parse_url( (string) $url, PHP_URL_QUERY ); |
| 50 |
parse_str( $query, $params ); |
| 51 |
self::assertArrayHasKey( 'v', $params ); |
| 52 |
self::assertSame( $version, $params['v'] ); |
| 53 |
|
| 54 |
wp_delete_file( $filePath ); |
| 55 |
} |
| 56 |
} |
| 57 |
|