Completed
Push — master ( 588057...32e2a0 )
by Oscar
07:36
created

Index   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 14 3
A thumb() 0 16 2
B thumbs() 0 29 6
1
<?php
2
3
namespace Folk\Controllers;
4
5
use Psr\Http\Message\ServerRequestInterface as Request;
6
use Psr\Http\Message\ResponseInterface as Response;
7
use Folk\Admin;
8
use Imagecow\Image;
9
10
class Index
11
{
12
    public function __invoke(Request $request, Response $response, Admin $app)
13
    {
14
        $query = $request->getQueryParams();
15
16
        if (isset($query['thumb'])) {
17
            return $this->thumb($request, $response, $app);
18
        }
19
20
        if (isset($query['thumbs'])) {
21
            return $this->thumbs($request, $response, $app);
22
        }
23
24
        return $app['templates']->render('pages/index');
25
    }
26
27
    private function thumb(Request $request, Response $response, Admin $app)
28
    {
29
        $query = $request->getQueryParams();
30
        $thumb = $app->getPath($query['thumb']);
31
32
        if (!is_file($thumb)) {
33
            return $response->withStatus(404);
34
        }
35
36
        $image = Image::fromFile($thumb);
37
        $image->resize(0, 200);
38
39
        $response->getBody()->write($image->getString());
40
41
        return $response->withHeader('Content-Type', $image->getMimeType());
42
    }
43
44
    private function thumbs(Request $request, Response $response, Admin $app)
45
    {
46
        $query = $request->getQueryParams();
47
        $thumbs = $app->getPath($query['thumbs']);
48
        $limit = empty($query['limit']) ? 100 : (int) $query['limit'];
49
        $offset = empty($query['offset']) ? 0 : (int) $query['offset'];
50
51
        $files = [];
52
53
        if (is_dir($thumbs)) {
54
            $dir = opendir($thumbs);
55
56
            while (($file = readdir($dir)) !== false) {
57
                $file = '/'.$file;
58
59
                if (is_file($thumbs.$file)) {
60
                    $files[] = $file;
61
                }
62
            }
63
64
            closedir($dir);
65
        }
66
67
        $files = array_reverse($files);
68
        $files = array_splice($files, $offset, $limit);
69
70
        $response->getBody()->write(json_encode($files));
71
        return $response->withHeader('Content-Type', 'application/json');
72
    }
73
}
74