SchemaHandler::getSchemaUrl()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 2
crap 2
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
	public 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
	public 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 8
    public function __construct($schemaId, $template=null, array $replacements = array())
68
    {
69 8
    	assert (!empty($schemaId));
70
		
71 8
		$this->schemaId=$schemaId;
72 8
        $this->template = $template?:$this->schemaId;
73 8
        $this->replacements = array_merge(array("schemaId" => $this->schemaId, "schemaTitle" => ucfirst($this->schemaId)),$replacements);
74 8
    }
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