Passed
Push — issue-14 ( 6b772e )
by Koldo
04:23
created

FileStructure::getMiddleware()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 25
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 22
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 25
ccs 0
cts 3
cp 0
crap 2
rs 9.568
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antidot\Installer\Template\Web;
6
7
use Antidot\Installer\Template\CommonFileStructure;
8
9
class FileStructure extends CommonFileStructure
10
{
11
    private const FILES = [
12
        'getGitignore' => '.gitignore',
13
        'getConfig' => 'config/config.php',
14
        'getCliConfig' => 'config/cli-config.php',
15
        'getConsole' => 'bin/console',
16
        'getFrameworkConfig' => 'config/services/framework.prod.php',
17
        'getDevelopmentConfig' => 'config/services/framework.dev.php.dist',
18
        'getContainer' => 'config/container.php',
19
        'getCliContainer' => 'config/cli-container.php',
20
        'getRoutes' => 'router/routes.php',
21
        'getMiddleware' => 'router/middleware.php',
22
        'getIndex' => 'public/index.php',
23
        'getHome' => 'src/Handler/Home.php',
24
        'getReadme' => 'README.md',
25
    ];
26
27
    private const DIRECTORIES = [
28
        'public',
29
        'bin',
30
        'config/services',
31
        'var/cache',
32
        'var/log',
33
        'test',
34
        'src/Handler',
35
        'router',
36
    ];
37
38
    public function create(string $installationPath): void
39
    {
40
        $this->verifyInstallationPath($installationPath);
41
        $this->createDirectories($installationPath, self::DIRECTORIES);
42
        $this->createFiles($installationPath, self::FILES);
43
        $this->removeCommunityFiles($installationPath);
44
    }
45
46
    public static function getGitignore(): string
47
    {
48
        $gitignoreContents = <<<EOT
49
/composer.lock
50
51
/config/services/*.dev.php
52
/config/services/*.local.php
53
54
/vendor
55
/var/cache/*
56
!/var/cache/.gitkeep
57
/var/log/*
58
!/var/log/.gitkeep
59
60
EOT;
61
62
        return $gitignoreContents;
63
    }
64
65
    public static function getConfig(): string
66
    {
67
        $configContent = <<<'PHP'
68
<?php
69
70
declare(strict_types=1);
71
72
use Antidot\DevTools\Container\Config\ConfigProvider as DevToolsConfigProvider;
73
use Laminas\ConfigAggregator\ConfigAggregator;
74
use Laminas\ConfigAggregator\ArrayProvider;
75
use Laminas\ConfigAggregator\PhpFileProvider;
76
77
// To enable or disable caching, set the `ConfigAggregator::ENABLE_CACHE` boolean in
78
// `config/autoload/local.php`.
79
$cacheConfig = [
80
    'config_cache_path' => 'var/cache/config-cache.php',
81
];
82
83
$aggregator = new ConfigAggregator([
84
    class_exists(DevToolsConfigProvider::class) ? DevToolsConfigProvider::class : fn() => [],
85
    // Load application config in a pre-defined order in such a way that local settings
86
    // overwrite global settings. (Loaded as first to last):
87
    //   - `services/*.php`
88
    //   - `services/*.local.php`
89
    //   - `services/*.dev.php`
90
    new PhpFileProvider(realpath(__DIR__).'/services/{{,*.}prod,{,*.}local,{,*.}dev}.php'),
91
    new ArrayProvider($cacheConfig),
92
], $cacheConfig['config_cache_path']);
93
94
return $aggregator->getMergedConfig();
95
96
PHP;
97
98
        return $configContent;
99
    }
100
101
    public static function getCliConfig(): string
102
    {
103
        $configContent = <<<'PHP'
104
<?php
105
106
declare(strict_types=1);
107
108
use Laminas\ConfigAggregator\ArrayProvider;
109
use Laminas\ConfigAggregator\ConfigAggregator;
110
111
$config = require __DIR__ . '/config.php';
112
$cliConfig['services'] = $config['console']['services'] ?? [];
113
$cliConfig['factories'] = $config['console']['factories'] ?? [];
114
$cacheConfig = [
115
    'cli_config_cache_path' => 'var/cache/cli-config-cache.php',
116
];
117
118
return (new ConfigAggregator([
119
    new ArrayProvider($config),
120
    new ArrayProvider($cliConfig),
121
    new ArrayProvider($cacheConfig),
122
], $cacheConfig['cli_config_cache_path']))->getMergedConfig();
123
124
PHP;
125
126
        return $configContent;
127
    }
128
129
    public static function getConsole(): string
130
    {
131
        $consoleContent = <<<'BASH'
132
#!/usr/bin/env php
133
<?php
134
135
declare(strict_types=1);
136
137
use Antidot\Cli\Application\Console;
138
139
set_time_limit(0);
140
141
call_user_func(static function (): void {
142
    require __DIR__.'/../vendor/autoload.php';
143
    $container = require __DIR__.'/../config/cli-container.php';
144
    $console = $container->get(Console::class);
145
146
    $console->run();
147
});
148
149
BASH;
150
151
        return $consoleContent;
152
    }
153
154
    public static function getFrameworkConfig(): string
155
    {
156
        $frameworkConfigContents = <<<'PHP'
157
<?php
158
159
declare(strict_types=1);
160
161
use App\Handler\Home;
162
use Monolog\Logger;
163
164
return [
165
    'debug' => false,
166
    'config_cache_enabled' => true,
167
    'monolog' => [
168
        'handlers' => [
169
            'default' => [
170
                'type' => 'stream',
171
                'options' => [
172
                    'stream' => sprintf('var/log/%s.log', (new DateTimeImmutable())->format('Y-m-d')),
173
                    'level' => Logger::ERROR,
174
                ],
175
            ],
176
        ],  
177
    ],
178
    'services' => [
179
        Home::class => Home::class,
180
    ],
181
];
182
183
PHP;
184
185
        return $frameworkConfigContents;
186
    }
187
188
    public static function getDevelopmentConfig(): string
189
    {
190
        $frameworkConfigContents = <<<'PHP'
191
<?php
192
193
declare(strict_types=1);
194
195
use Monolog\Logger;
196
197
return [
198
    'debug' => true,
199
    'config_cache_enabled' => false,
200
    'monolog' => [
201
        'handlers' => [
202
            'default' => [
203
                'options' => [
204
                    'level' => Logger::DEBUG,
205
                ],
206
            ],
207
        ],  
208
    ],
209
];
210
211
PHP;
212
213
        return $frameworkConfigContents;
214
    }
215
216
    public static function getCliContainer(): string
217
    {
218
        $containerContent = <<<'PHP'
219
<?php
220
221
// Load configuration
222
use Antidot\Container\Builder;
223
224
$config = require __DIR__ . '/../config/cli-config.php';
225
226
return Builder::build($config, true);
227
228
PHP;
229
230
        return $containerContent;
231
    }
232
233
    public static function getIndex(): string
234
    {
235
        $indexContent = <<<'PHP'
236
<?php
237
238
declare(strict_types=1);
239
240
// Delegate static file requests back to the PHP built-in webserver
241
use Antidot\Application\Http\Application;
242
243
if (PHP_SAPI === 'cli-server' && $_SERVER['SCRIPT_FILENAME'] !== __FILE__) {
244
    return false;
245
}
246
\chdir(\dirname(__DIR__));
247
require 'vendor/autoload.php';
248
/**
249
 * Self-called anonymous function that creates its own scope and keep the global namespace clean.
250
 */
251
\call_user_func(static function (): void {
252
    error_reporting(E_ALL & ~E_USER_DEPRECATED & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);
253
254
    /** @var \Psr\Container\ContainerInterface $container */
255
    $container = require 'config/container.php';
256
    /** @var Application $app */
257
    $app = $container->get(Application::class);
258
    // Execute programmatic/declarative middleware pipeline and routing
259
    // configuration statements
260
    (require 'router/middleware.php')($app, $container);
261
    (require 'router/routes.php')($app, $container);
262
    $app->run();
263
});
264
265
PHP;
266
267
        return $indexContent;
268
    }
269
270
    public static function getRoutes(): string
271
    {
272
        $routesContent = <<<'PHP'
273
<?php
274
275
declare(strict_types=1);
276
277
use Antidot\Application\Http\Application;
278
use App\Handler\Home;
279
use Psr\Container\ContainerInterface;
280
281
/**
282
 * Setup routes with a single request method and routed Middleware:
283
 *
284
 * $app->get('/', [App\Middleware\HomePageMiddleware::class, App\Handler\HomePageHandler::class], 'home');
285
 * $app->post('/album', [
286
 *      App\Middleware\HomePageMiddleware::class, 
287
 *      App\Handler\AlbumCreateHandler::class
288
 * ], 'album.create');
289
 * $app->put('/album/:id', [App\Handler\AlbumUpdateHandler::class], 'album.put');
290
 * $app->patch('/album/:id', [App\Handler\AlbumUpdateHandler::class,] 'album.patch');
291
 * $app->delete('/album/:id', [App\Handler\AlbumDeleteHandler::class], 'album.delete');
292
 */
293
return static function (Application $app, ContainerInterface $container) : void {
294
    $app->get('/', [Home::class], 'home');
295
};
296
297
PHP;
298
299
        return $routesContent;
300
    }
301
302
    public static function getMiddleware(): string
303
    {
304
        $middlewareContent = <<<'PHP'
305
<?php
306
307
declare(strict_types=1);
308
309
use Antidot\Application\Http\Application;
310
use Antidot\Application\Http\Middleware\ErrorMiddleware;
311
use Antidot\Application\Http\Middleware\RouteDispatcherMiddleware;
312
use Antidot\Application\Http\Middleware\RouteNotFoundMiddleware;
313
use Antidot\Logger\Application\Http\Middleware\ExceptionLoggerMiddleware;
314
use Antidot\Logger\Application\Http\Middleware\RequestLoggerMiddleware;
315
316
return static function (Application $app) : void {
317
    $app->pipe(ErrorMiddleware::class);
318
    $app->pipe(ExceptionLoggerMiddleware::class);
319
    $app->pipe(RequestLoggerMiddleware::class);
320
    $app->pipe(RouteDispatcherMiddleware::class);
321
    $app->pipe(RouteNotFoundMiddleware::class);
322
};
323
324
PHP;
325
326
        return $middlewareContent;
327
    }
328
329
    public static function getHome(): string
330
    {
331
        $handlerContent = <<<'PHP'
332
<?php
333
334
declare(strict_types=1);
335
336
namespace App\Handler;
337
338
use Psr\Http\Message\ResponseInterface;
339
use Psr\Http\Message\ServerRequestInterface;
340
use Psr\Http\Server\RequestHandlerInterface;
341
use Laminas\Diactoros\Response\JsonResponse;
342
343
class Home implements RequestHandlerInterface
344
{
345
    public function handle(ServerRequestInterface $request): ResponseInterface
346
    {
347
        return new JsonResponse([
348
            'docs' => 'https://antidotfw.io',
349
            'Message' => 'Welcome to Antidot Framework Starter'
350
        ]);
351
    }
352
}
353
354
PHP;
355
356
        return $handlerContent;
357
    }
358
359
    public static function getReadme(): string
360
    {
361
        $readmeContents = <<<'EOT'
362
# Antidot Framework Web HTTP App
363
364
Full featured PSR-15 middleware application.
365
366
## Routing
367
368
You can add your routes with its custom middlewares in `router/routes.php` file, take a look at the example:
369
370
```php 
371
<?php
372
373
declare(strict_types=1);
374
375
use Antidot\Application\Http\Application;
376
use App\Application\Http\Home;
377
use Psr\Container\ContainerInterface;
378
379
return static function (Application $app, ContainerInterface $container) : void {
380
    $app->get('/', [Home::class], 'home');
381
    ...
382
};
383
384
```
385
386
You can modify global middleware in `router/middleware.php` file, take a look at the example:
387
388
```php 
389
<?php
390
391
declare(strict_types=1);
392
393
use Antidot\Application\Http\Application;
394
use Antidot\Application\Http\Middleware\ErrorMiddleware;
395
use Antidot\Application\Http\Middleware\RouteDispatcherMiddleware;
396
use Antidot\Application\Http\Middleware\RouteNotFoundMiddleware;
397
use Antidot\Logger\Application\Http\Middleware\ExceptionLoggerMiddleware;
398
use Antidot\Logger\Application\Http\Middleware\RequestLoggerMiddleware;
399
400
return static function (Application $app) : void {
401
    $app->pipe(ErrorMiddleware::class);
402
    $app->pipe(ExceptionLoggerMiddleware::class);
403
    $app->pipe(RequestLoggerMiddleware::class);
404
    $app->pipe(RouteDispatcherMiddleware::class);
405
    $app->pipe(RouteNotFoundMiddleware::class);
406
};
407
408
```
409
410
## File structure
411
412
```
413
config/
414
    services/
415
        framework.prod.php    
416
        framework.dev.php.dist    
417
    config.php
418
    container.php
419
    cli-config.php
420
    cli-container.php
421
public/
422
    index.php
423
router/
424
    middleware.php
425
    routes.php
426
src/
427
    Handler/
428
        Home.php
429
test/
430
var/
431
    cache/
432
.gitignore
433
composer.json
434
phpcs.xml.dist
435
phpunit.xml.dist
436
README.md        
437
```
438
439
EOT;
440
441
        return $readmeContents;
442
    }
443
}
444