1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Resourceful; |
4
|
|
|
|
5
|
|
|
use Silex\Application; |
6
|
|
|
use Symfony\Component\HttpFoundation\Request; |
7
|
|
|
|
8
|
|
|
class SchemaHandler |
9
|
|
|
{ |
|
|
|
|
10
|
|
|
protected $schemaId; |
11
|
|
|
protected $template; |
12
|
|
|
protected $replacements; |
13
|
|
|
|
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @return string schemaUrl |
17
|
|
|
*/ |
18
|
14 |
|
static function getSchemaUrl($schemaId, Application $app) |
|
|
|
|
19
|
|
|
{ |
20
|
14 |
|
static $urlCache =array(); |
21
|
|
|
|
22
|
14 |
|
assert (!empty($schemaId)); |
23
|
|
|
|
24
|
14 |
|
if( !isset($urlCache[$schemaId])){ |
25
|
4 |
|
$urlCache[$schemaId] = $app["url_generator"]->generate('schema', array("id" => $schemaId)); |
26
|
|
|
} |
27
|
|
|
|
28
|
14 |
|
return $urlCache[$schemaId]; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* create a schema from template if it does not exist |
34
|
|
|
* |
35
|
|
|
* @return string schemaUrl |
36
|
|
|
*/ |
37
|
3 |
|
protected static function _register(Application $app, $schemaId, $template, array $replacements) |
38
|
|
|
{ |
39
|
3 |
|
assert( isset($app['schema.cache'])); |
40
|
3 |
|
assert( isset($app['data.store'])); |
41
|
3 |
|
assert( isset($app['twig'])); |
42
|
|
|
|
43
|
3 |
|
$schemaUrl = static::getSchemaUrl($schemaId, $app); |
44
|
3 |
|
$store = isset($app['schema.store'])?$app['schema.store']:$app['data.store']; |
45
|
|
|
|
46
|
|
|
if ( |
47
|
3 |
|
$app['createDefault'] |
48
|
3 |
|
&& !$store->contains($schemaUrl) |
49
|
3 |
|
&& ($schema=json_decode($app["twig"]->render("schema_{$template}.json.twig", $replacements))) |
50
|
|
|
) { |
51
|
1 |
|
$store->save($schemaUrl, $schema); |
52
|
|
|
} |
53
|
|
|
|
54
|
3 |
|
$app["schema.cache"]->add($schemaUrl, $store->fetch($schemaUrl)); |
55
|
|
|
|
56
|
3 |
|
return $schemaUrl; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
|
60
|
2 |
|
static function register(Application $app, $schemaId=null, $template=null, array $replacements = array()) |
|
|
|
|
61
|
|
|
{ |
62
|
2 |
|
$handler = new static($schemaId, $template, $replacements); |
63
|
2 |
|
return static::_register($app, $handler->schemaId, $handler->template, $handler->replacements); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
|
67
|
6 |
|
public function __construct($schemaId, $template=null, array $replacements = array()) |
68
|
|
|
{ |
69
|
6 |
|
assert (!empty($schemaId)); |
70
|
|
|
|
71
|
6 |
|
$this->schemaId=$schemaId; |
72
|
6 |
|
$this->template = $template?:$this->schemaId; |
73
|
6 |
|
$this->replacements = array_merge(array("schemaId" => $this->schemaId, "schemaTitle" => ucfirst($this->schemaId)),$replacements); |
74
|
6 |
|
} |
75
|
|
|
|
76
|
|
|
|
77
|
1 |
|
public function __invoke(Request $request, Application $app) |
78
|
|
|
{ |
79
|
1 |
|
static::_register($app, $this->schemaId, $this->template, $this->replacements); |
80
|
1 |
|
} |
81
|
|
|
} |
82
|
|
|
|