Completed
Push — master ( cc01fd...c570ee )
by Oscar
04:59
created

Entity::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Folk\Controllers;
4
5
use Psr\Http\Message\ServerRequestInterface as Request;
6
use Psr\Http\Message\ResponseInterface as Response;
7
use Folk\Admin;
8
use Middlewares\Utils\Factory;
9
use FormManager\Builder as F;
10
11
abstract class Entity
12
{
13
    protected $app;
14
    protected $formats = [
15
        'text/html' => 'html',
16
        'application/json' => 'json',
17
    ];
18
19
    public function __construct(Admin $app)
20
    {
21
        $this->app = $app;
22
    }
23
24
    public function __invoke(Request $request)
25
    {
26
        $format = $request->getHeaderLine('Accept');
27
        $format = $this->formats[$format] ?? 'html';
28
        $entityName = $request->getAttribute('entity');
29
30
        if ($this->app->hasEntity($entityName) && method_exists($this, $format)) {
31
            return $this->$format($request, $entityName);
32
        }
33
34
        return Factory::createResponse(404);
35
    }
36
37
    /**
38
     * Helper to build the entity form.
39
     * 
40
     * @param string     $entityName
41
     * @param mixed|null $id
42
     * 
43
     * return \Folk\Formats\Form
44
     */
45
    protected function createForm(string $entityName, $id = null)
46
    {
47
        $entity = $this->app->getEntity($entityName);
48
49
        $form = F::form()
50
            ->method('post')
51
            ->enctype('multipart/form-data')
52
            ->add([
53
                'entity' => F::hidden()->val($entityName)->class('field-data-entity'),
54
                'data' => $entity->getScheme($this->app->get('builder')),
55
            ]);
56
57
        if ($id !== null) {
58
            $form['id'] = F::hidden()->val($id)->class('field-data-id');
59
        }
60
61
        return $form;
62
    }
63
}
64