Passed
Push — master ( af4dac...7c9bf0 )
by Harm
01:54
created

DocsController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
crap 1
1
<?php
2
3
namespace HarmBandstra\SwaggerUiBundle\Controller;
4
5
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
6
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
7
use Symfony\Component\HttpFoundation\JsonResponse;
8
use Symfony\Component\HttpFoundation\RedirectResponse;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpFoundation\Response;
11
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
12
use Symfony\Component\Yaml\Yaml;
13
14
class DocsController extends AbstractController
15
{
16
    /** @var string */
17
    private $projectDir;
18
19
    /** @var array */
20
    private $swaggerFiles;
21
22
    /** @var string */
23
    private $directory;
24
25 6
    public function __construct($projectDir, $swaggerFiles, $directory)
26
    {
27 6
        $this->projectDir = $projectDir;
28 6
        $this->swaggerFiles = $swaggerFiles;
29 6
        $this->directory = $directory;
30 6
    }
31
32
    /**
33
     * @param Request $request
34
     *
35
     * @return Response
36
     */
37 1
    public function indexAction(Request $request)
38
    {
39 1
        if (!$request->get('url')) {
40
            // if there is no ?url=... parameter, redirect to the default one
41 1
            $defaultSpecFile = reset($this->swaggerFiles);
42
43 1
            return $this->redirect($this->getRedirectUrlToSpec($defaultSpecFile));
44
        }
45
46
        $indexFilePath = $this->projectDir . '/vendor/swagger-api/swagger-ui/dist/index.html';
47
48
        return new Response(file_get_contents($indexFilePath));
49
    }
50
51
    /**
52
     * @param string $fileName
53
     *
54
     * @return RedirectResponse
55
     */
56 1
    public function redirectAction($fileName)
57
    {
58
        // redirect to swagger file if that's what we're looking for
59 1
        if (in_array($fileName, $this->swaggerFiles, true)) {
60 1
            return $this->redirect($this->getRedirectUrlToSpec($fileName));
61
        }
62
63
        // redirect to the assets dir so that relative links work
64
        return $this->redirect('/bundles/hbswaggerui/' . $fileName);
65
    }
66
67
    /**
68
     * @param string $fileName
69
     *
70
     * @return JsonResponse|Response
71
     */
72 4
    public function swaggerFileAction($fileName)
73
    {
74
        try {
75 4
            $filePath = $this->getFilePath($fileName);
76 2
        } catch (\Exception $e) {
77 2
            return new JsonResponse($e->getMessage(), Response::HTTP_NOT_FOUND);
78
        }
79
80 2
        $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
81 2
        if ($extension === 'yml' || $extension === 'yaml') {
82 1
            $fileContents = Yaml::parse(file_get_contents($filePath));
83
84 1
            return new JsonResponse($fileContents);
85
        }
86
87 1
        $fileContents = file_get_contents($filePath);
88
89 1
        return new Response(
90 1
            $fileContents,
91 1
            Response::HTTP_OK,
92 1
            ['Content-Type' => 'application/json']
93
        );
94
    }
95
96
    /**
97
     * @param string $fileName
98
     *
99
     * @return string
100
     */
101 4
    private function getFilePath($fileName = '')
102
    {
103 4
        if ($fileName !== '' && !in_array($fileName, $this->swaggerFiles)) {
104 1
            throw new \RuntimeException(
105 1
                sprintf('File [%s] not defined under [hb_swagger_ui.files] in config.yml.', $fileName)
106
            );
107
        }
108
109 3
        if ($this->directory === '') {
110
            throw new \RuntimeException(
111
                'Directory [hb_swagger_ui.directory] not defined or empty in config.yml.'
112
            );
113
        }
114
115 3
        $filePath = realpath($this->directory . DIRECTORY_SEPARATOR . $fileName);
116 3
        if (!is_file($filePath)) {
117 1
            throw new FileNotFoundException(sprintf('File [%s] not found.', $fileName));
118
        }
119
120 2
        return $filePath;
121
    }
122
123
    /**
124
     * @param string $fileName
125
     *
126
     * @return string
127
     */
128 2
    private function getRedirectUrlToSpec($fileName)
129
    {
130 2
        if (strpos($fileName, '/') === 0 || preg_match('#http[s]?://#', $fileName)) {
131
            // if absolute path or URL use it raw
132
            $specUrl = $fileName;
133
        } else {
134 2
            $specUrl = $this->generateUrl(
135 2
                'hb_swagger_ui_swagger_file',
136 2
                ['fileName' => $fileName],
137 2
                UrlGeneratorInterface::ABSOLUTE_PATH
138
            );
139
        }
140
141 2
        return $this->generateUrl('hb_swagger_ui_default', ['url' => $specUrl]);
142
    }
143
}
144