Passed
Push — master ( 79c5c4...dc6772 )
by Harm
07:54
created

DocsController::getRedirectUrlToSpec()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 7
cts 8
cp 0.875
rs 9.7666
c 0
b 0
f 0
cc 3
nc 2
nop 1
crap 3.0175
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
        $contents = @file_get_contents(__DIR__ . '/../Resources/public/index.html');
47
        if ($contents === false) {
48
            throw new \RuntimeException('Unable to load [Resources/public/index.html]. Did [ScriptHandler::linkAssets] run correctly?');
49
        }
50
51
        return new Response($contents);
52
    }
53
54
    /**
55
     * @param string $fileName
56
     *
57
     * @return RedirectResponse
58
     */
59 1
    public function redirectAction($fileName)
60
    {
61
        // redirect to swagger file if that's what we're looking for
62 1
        if (in_array($fileName, $this->swaggerFiles, true)) {
63 1
            return $this->redirect($this->getRedirectUrlToSpec($fileName));
64
        }
65
66
        // redirect to the assets dir so that relative links work
67
        return $this->redirect('/bundles/hbswaggerui/' . $fileName);
68
    }
69
70
    /**
71
     * @param string $fileName
72
     *
73
     * @return JsonResponse|Response
74
     */
75 4
    public function swaggerFileAction($fileName)
76
    {
77
        try {
78 4
            $filePath = $this->getFilePath($fileName);
79 2
        } catch (\Exception $e) {
80 2
            return new JsonResponse($e->getMessage(), Response::HTTP_NOT_FOUND);
81
        }
82
83 2
        $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
84 2
        if ($extension === 'yml' || $extension === 'yaml') {
85 1
            $fileContents = Yaml::parse(file_get_contents($filePath));
86
87 1
            return new JsonResponse($fileContents);
88
        }
89
90 1
        $fileContents = file_get_contents($filePath);
91
92 1
        return new Response(
93 1
            $fileContents,
94 1
            Response::HTTP_OK,
95 1
            ['Content-Type' => 'application/json']
96
        );
97
    }
98
99
    /**
100
     * @param string $fileName
101
     *
102
     * @return string
103
     */
104 4
    private function getFilePath($fileName = '')
105
    {
106 4
        if ($fileName !== '' && !in_array($fileName, $this->swaggerFiles)) {
107 1
            throw new \RuntimeException(
108 1
                sprintf('File [%s] not defined under [hb_swagger_ui.files] in config.yml.', $fileName)
109
            );
110
        }
111
112 3
        if ($this->directory === '') {
113
            throw new \RuntimeException(
114
                'Directory [hb_swagger_ui.directory] not defined or empty in config.yml.'
115
            );
116
        }
117
118 3
        $filePath = realpath($this->directory . DIRECTORY_SEPARATOR . $fileName);
119 3
        if (!is_file($filePath)) {
120 1
            throw new FileNotFoundException(sprintf('File [%s] not found.', $fileName));
121
        }
122
123 2
        return $filePath;
124
    }
125
126
    /**
127
     * @param string $fileName
128
     *
129
     * @return string
130
     */
131 2
    private function getRedirectUrlToSpec($fileName)
132
    {
133 2
        if (strpos($fileName, '/') === 0 || preg_match('#http[s]?://#', $fileName)) {
134
            // if absolute path or URL use it raw
135
            $specUrl = $fileName;
136
        } else {
137 2
            $specUrl = $this->generateUrl(
138 2
                'hb_swagger_ui_swagger_file',
139 2
                ['fileName' => $fileName],
140 2
                UrlGeneratorInterface::ABSOLUTE_PATH
141
            );
142
        }
143
144 2
        return $this->generateUrl('hb_swagger_ui_default', ['url' => $specUrl]);
145
    }
146
}
147