Completed
Push — master ( 8b6b4d...3108c8 )
by AJ
01:52
created

SubdomainMiddleware::getSubdomains()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 17
rs 9.2
cc 4
eloc 8
nc 3
nop 0
1
<?php
2
/**
3
 * CakePHP Plugin : CakePHP Subdomain Routing
4
 * Copyright (c) Multidimension.al (http://multidimension.al)
5
 * Github : https://github.com/multidimension-al/cakephp-subdomains
6
 *
7
 * Licensed under The MIT License
8
 * For full copyright and license information, please see the LICENSE file
9
 * Redistributions of files must retain the above copyright notice.
10
 *
11
 * @copyright     (c) Multidimension.al (http://multidimension.al)
12
 * @link          https://github.com/multidimension-al/cakephp-subdomains Github
13
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
14
 */
15
16
namespace Multidimensional\Subdomains\Middleware;
17
18
use Cake\Core\Configure;
19
20
class SubdomainMiddleware {
21
        
22
    /**
23
     * @param \Psr\Http\Message\ServerRequestInterface $request The request.
24
     * @param \Psr\Http\Message\ResponseInterface $response The response.
25
     * @param callable $next The next middleware to call.
26
     * @return \Psr\Http\Message\ResponseInterface A response.
27
     */
28
    public function __invoke($request, $response, $next) {
29
        
30
        $subdomains = $this->getSubdomains();
31
        
32
        $uri = $request->getUri();
33
        $host = $uri->getHost();
34
        
35
        if (preg_match('/(.*?)\.([^\/]*\..{2,5})/i', $host, $parts)) {
36
            
37
            if (in_array($parts[1], $subdomains)) {
38
            
39
                $params = (array) $request->getAttribute('params', []);
40
                
41
                if (empty($params['prefix'])) {
42
                    $params['prefix'] = $parts[1];            
43
                }
44
                
45
                $request = $request->withAttribute('params', $params);
46
            
47
            }
48
        
49
        }
50
        
51
        return $next($request, $response);
52
        
53
    }    
54
    
55
    public function getSubdomains() {
56
        
57
        $validConfiguration = Configure::check('Multidimensional/Subdomains.subdomains');
58
        
59
        if (!$validConfiguration) {
60
            return [];
61
        }
62
        
63
        $subdomains = Configure::read('Multidimensional/Subdomains.subdomains');
64
        
65
        if (!is_array($subdomains) || count($subdomains) == 0) {
66
            return [];
67
        }
68
        
69
        return $subdomains;
70
        
71
    }
72
    
73
}