Skip to content

Commit 500bfa2

Browse files
authored
Merge pull request #122 from FriendsOfCake/plugin-class
Move plugin bootstrapping and routes setting within Plugin class
2 parents f1d8565 + b9eb3b6 commit 500bfa2

4 files changed

Lines changed: 50 additions & 34 deletions

File tree

config/bootstrap.php

Lines changed: 0 additions & 31 deletions
This file was deleted.

config/routes.php

Lines changed: 0 additions & 3 deletions
This file was deleted.

phpunit.xml.dist

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@
2424
<filter>
2525
<whitelist>
2626
<directory suffix=".php">src/</directory>
27+
<exclude>
28+
<file>src/Plugin.php</file>
29+
</exclude>
2730
</whitelist>
2831
</filter>
2932

src/Plugin.php

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@
44
namespace CsvView;
55

66
use Cake\Core\BasePlugin;
7+
use Cake\Core\PluginApplicationInterface;
8+
use Cake\Event\EventInterface;
9+
use Cake\Event\EventManager;
10+
use Cake\Http\ServerRequest;
11+
use Cake\Routing\RouteBuilder;
12+
use Cake\Routing\Router;
713

814
class Plugin extends BasePlugin
915
{
@@ -13,4 +19,45 @@ class Plugin extends BasePlugin
1319
* @var string
1420
*/
1521
protected $name = 'CsvView';
22+
23+
/**
24+
* @inheritDoc
25+
*/
26+
public function bootstrap(PluginApplicationInterface $app): void
27+
{
28+
/**
29+
* Add CsvView to View class map through RequestHandler, if available, on Controller initialisation
30+
*
31+
* @link https://book.cakephp.org/4/en/controllers/components/request-handling.html#using-custom-viewclasses
32+
*/
33+
EventManager::instance()->on('Controller.initialize', function (EventInterface $event) {
34+
$controller = $event->getSubject();
35+
if ($controller->components()->has('RequestHandler')) {
36+
$controller->RequestHandler->setConfig('viewClassMap.csv', 'CsvView.Csv');
37+
}
38+
});
39+
40+
/**
41+
* Add a request detector named "csv" to check whether the request was for a CSV,
42+
* either through accept header or file extension
43+
*
44+
* @link https://book.cakephp.org/4/en/controllers/request-response.html#checking-request-conditions
45+
*/
46+
ServerRequest::addDetector(
47+
'csv',
48+
[
49+
'accept' => ['text/csv'],
50+
'param' => '_ext',
51+
'value' => 'csv',
52+
]
53+
);
54+
}
55+
56+
/**
57+
* @inheritDoc
58+
*/
59+
public function routes(RouteBuilder $routes): void
60+
{
61+
Router::extensions('csv');
62+
}
1663
}

0 commit comments

Comments
 (0)