Completed
Pull Request — master (#52)
by John
02:48
created

DocumentRepository   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 10
c 4
b 1
f 0
lcom 1
cbo 5
dl 0
loc 76
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A get() 0 14 4
B load() 0 20 5
1
<?php
2
/*
3
 * This file is part of the KleijnWeb\SwaggerBundle package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace KleijnWeb\SwaggerBundle\Document;
10
11
use Doctrine\Common\Cache\Cache;
12
use KleijnWeb\SwaggerBundle\Document\Exception\ResourceNotReadableException;
13
14
/**
15
 * @author John Kleijn <[email protected]>
16
 */
17
class DocumentRepository
18
{
19
    /**
20
     * @var string
21
     */
22
    private $basePath;
23
24
    /**
25
     * @var array
26
     */
27
    private $documents = [];
28
29
    /**
30
     * @var Cache
31
     */
32
    private $cache;
33
34
    /**
35
     * Initializes a new Repository.
36
     *
37
     * @param string $basePath
38
     * @param Cache  $cache
39
     */
40
    public function __construct($basePath = null, Cache $cache = null)
41
    {
42
        $this->basePath = $basePath;
43
        $this->cache = $cache;
44
    }
45
46
    /**
47
     * @param string $documentPath
48
     *
49
     * @return SwaggerDocument
50
     */
51
    public function get($documentPath)
52
    {
53
        if ($this->basePath) {
54
            $documentPath = "$this->basePath/$documentPath";
55
        }
56
        if (!$documentPath) {
57
            throw new \InvalidArgumentException("No document path provided");
58
        }
59
        if (!isset($this->documents[$documentPath])) {
60
            $this->documents[$documentPath] = $this->load($documentPath);
61
        }
62
63
        return $this->documents[$documentPath];
64
    }
65
66
    /**
67
     * @param string $documentPath
68
     *
69
     * @return SwaggerDocument
70
     * @throws ResourceNotReadableException
71
     */
72
    private function load($documentPath)
73
    {
74
        if ($this->cache && $document = $this->cache->fetch($documentPath)) {
75
            return $document;
76
        }
77
78
        if (!is_readable($documentPath)) {
79
            throw new ResourceNotReadableException("Document '$documentPath' is not readable");
80
        }
81
82
        $parser = new  YamlParser();
83
        $resolver = new RefResolver($parser->parse((string)file_get_contents($documentPath)), $documentPath);
84
        $document = new SwaggerDocument($documentPath, $resolver->resolve());
85
86
        if ($this->cache) {
87
            $this->cache->save($documentPath, $document);
88
        }
89
90
        return $document;
91
    }
92
}
93