SchemaHandler   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 0
dl 0
loc 74
ccs 30
cts 30
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getSchemaUrl() 0 12 2
B _register() 0 21 5
A register() 0 5 1
A __construct() 0 8 2
A __invoke() 0 4 1
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