Skip to content

Commit

Permalink
Revert Mix dependence on Request, Add unit tests
Browse files Browse the repository at this point in the history
Remove redundant listener tags from phpunit.xml.dist
Apply better solution to remove asset timestamping from the cake3 branch
Add unit tests to test css() and script() AssetMixHelper methods
  • Loading branch information
toggenation authored and ishanvyas22 committed May 25, 2023
1 parent 0720f50 commit 254f81e
Show file tree
Hide file tree
Showing 11 changed files with 128 additions and 29 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,9 @@ bin/cake asset_mix generate inertia-react
```bash
bin/cake asset_mix generate react --dir=resources
```
## Serving CakePHP out of a Subdirectory
Please see [docs/ServingFromSubdirectory](docs/ServingFromSudirectory.md)
## Version map
Expand Down
19 changes: 10 additions & 9 deletions config/routes.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
<?php

use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;

/** @var RouteBuilder $routes */
$routes->plugin(
'AssetMix',
['path' => '/asset-mix'],
function (RouteBuilder $routes) {
$routes->fallbacks(DashedRoute::class);
});
/** @var \Cake\Routing\RouteBuilder $routes */
$routes->plugin(
'AssetMix',
['path' => '/asset-mix'],
function (RouteBuilder $routes) {
$routes->fallbacks(DashedRoute::class);
}
);
26 changes: 26 additions & 0 deletions docs/ServingFromSudirectory.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Using AssetMix Plugin when Serving CakePHP from a Subdirectory

To use the AssetMixHelper methods `$this->AssetMix->css('main)` and `$this->AssetMix->script('app')` when CakePHP is being served out of a subdirectory. For example you access your CakePHP application from https://example.com/subdir and NOT https://example.com/

Configure `App.base` with `/subdir`:

```php
// config/app.php
'App' => [
'namespace' => 'App',
'encoding' => env('APP_ENCODING', 'UTF-8'),
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_AU'),
'defaultTimezone' => 'Australia/Melbourne',
// comment or remove the default
// 'base' => false,
// hard coded
'base' => '/subdir',
// or pull from the environment to make it portable
// 'base' => env('SUBDIR', false),
'language' => 'en',
'dir' => 'src',
'webroot' => 'webroot',
'wwwRoot' => WWW_ROOT,
//...
]
```
11 changes: 3 additions & 8 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,9 @@
</testsuite>
</testsuites>

<!-- Setup a listener for fixtures -->
<listeners>
<listener class="\Cake\TestSuite\Fixture\FixtureInjector">
<arguments>
<object class="\Cake\TestSuite\Fixture\FixtureManager"/>
</arguments>
</listener>
</listeners>
<extensions>
<extension class="\Cake\TestSuite\Fixture\PHPUnitExtension" />
</extensions>

<filter>
<whitelist>
Expand Down
23 changes: 18 additions & 5 deletions src/Mix.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace AssetMix;

use Cake\Core\Configure;
use Exception;

/**
Expand Down Expand Up @@ -35,11 +36,22 @@ public function __invoke($path, $manifestDirectory = ''): string
$path = $matches[2];
}

if (! starts_with($path, '/')) {
// strip subdir if exists
$subdir = Configure::read('App.base');

if ($subdir) {
$path = preg_replace(sprintf('+^%s+', $subdir), '', $path);
}

// strip asset timestamp query string
// /js/app.js?1674622148 becomes /js/app.js
$path = preg_replace('/\?.*/', '', $path);

if (!starts_with($path, '/')) {
$path = "/{$path}";
}

if ($manifestDirectory && ! starts_with($manifestDirectory, '/')) {
if ($manifestDirectory && !starts_with($manifestDirectory, '/')) {
$manifestDirectory = "/{$manifestDirectory}";
}

Expand All @@ -59,8 +71,8 @@ public function __invoke($path, $manifestDirectory = ''): string
}

$manifestPath = WWW_ROOT . $manifestDirectory . '/mix-manifest.json';
if (! isset(self::$manifests[$manifestPath])) {
if (! file_exists($manifestPath)) {
if (!isset(self::$manifests[$manifestPath])) {
if (!file_exists($manifestPath)) {
throw new Exception('The Mix manifest does not exist.');
}

Expand All @@ -74,7 +86,8 @@ public function __invoke($path, $manifestDirectory = ''): string
}

$manifest = self::$manifests[$manifestPath];
if (! isset($manifest[$path])) {

if (!isset($manifest[$path])) {
throw new Exception("Unable to locate AssetMix file: {$path}.");
}

Expand Down
3 changes: 2 additions & 1 deletion stubs/bootstrap/assets/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ try {
window.$ = window.jQuery = require('jquery');

require('bootstrap');
} catch (e) {}
} catch (e) {
}

/**
* Set CSRF token as a header based on the value of the "XSRF" token cookie.
Expand Down
2 changes: 1 addition & 1 deletion stubs/inertia-react/assets/js/Pages/Pages/Display.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ import React from 'react';
* when your application has been setup with inertiajs.
*/
export default function Display() {
return <div>Hello world!</div>;
return <div> Hello world! </div>;
}
3 changes: 2 additions & 1 deletion stubs/react/assets/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ try {
window.$ = window.jQuery = require('jquery');

require('bootstrap');
} catch (e) {}
} catch (e) {
}

/**
* Set CSRF token as a header based on the value of the "XSRF" token cookie.
Expand Down
2 changes: 1 addition & 1 deletion stubs/vue/assets/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ window.Vue = Vue;
Vue.component('app-greet', AppGreet);

const app = new Vue({
el: '#app'
el: '#app'
});
63 changes: 61 additions & 2 deletions tests/TestCase/View/Helper/AssetMixHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use AssetMix\View\Helper\AssetMixHelper;
use Cake\Core\Configure;
use Cake\Filesystem\Folder;
use Cake\Http\ServerRequest;
use Cake\Routing\Router;
use Cake\TestSuite\TestCase;
use Cake\View\View;

Expand Down Expand Up @@ -66,7 +68,7 @@ protected function _copy($withVersion = false)
$sourceFilename = 'mix-manifest-with-version.json';
}

if (! copy(COMPARE_PATH . $sourceFilename, WWW_ROOT . $destinationFilename)) {
if (!copy(COMPARE_PATH . $sourceFilename, WWW_ROOT . $destinationFilename)) {
throw new \Exception('Unable to copy mix-manifest.json file');
}
}
Expand Down Expand Up @@ -101,7 +103,7 @@ protected function _cleanUp()
$files = glob(WWW_ROOT . '*');

foreach ($files as $file) {
if (! is_file($file)) {
if (!is_file($file)) {
continue;
}

Expand Down Expand Up @@ -223,4 +225,61 @@ public function testScriptTagWithExternalBaseUrl()

$this->assertStringContainsString('https://example.com/js/app.js', $result);
}

/**
* Test `css()` function works when serving out of a /subdir
*
* @return void
*/
public function testRemoveBaseDirIfServingFromSubdirectory()
{
$subdir = '/subdir';

Configure::write('App.base', $subdir);

$request = new ServerRequest([
'base' => $subdir,
'webroot' => $subdir . '/',
]);

Router::reload();

Router::setRequest($request);

$this->_copyWithVersion();

$result = $this->AssetMix->css('main');

$this->assertStringContainsString($subdir . '/css/main.css', $result);
}

/**
* Test `script()` throws exception when serving from subdir and App.base missing
*
* @return void
*/
public function testSubdirWithoutAppBaseThrowsException()
{
$subdir = '/subdir';

Configure::write('App.base', false);

// url is /subdir/controller/action
$request = new ServerRequest([
'base' => $subdir,
'webroot' => $subdir . '/',
]);

Router::reload();

Router::setRequest($request);

$this->_copyWithVersion();

$this->expectException(\Exception::class);

$this->expectExceptionMessage("Unable to locate AssetMix file: {$subdir}/js/app.js.");

$result = $this->AssetMix->script('app');
}
}
2 changes: 1 addition & 1 deletion tests/test_app/config/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@

Router::reload();

Router::scope('/', function (RouteBuilder $routes) {
$routes->scope('/', function (RouteBuilder $routes) {
$routes->fallbacks(DashedRoute::class);
});

0 comments on commit 254f81e

Please sign in to comment.