DataAccess   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 0
dl 0
loc 47
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A retrieveUrl() 0 4 1
A retrieveHeader() 0 18 3
A saveCache() 0 3 1
A readCache() 0 3 1
A setContext() 0 11 1
1
<?php
2
3
namespace Mpclarkson\IconScraper;
4
5
/**
6
 * DataAccess is a wrapper used to read/write data locally or remotely
7
 * Aside from SOLID principles, this wrapper is also useful to mock remote resources in unit tests
8
 * Note: remote access warning are silenced because we don't care if a website is unreachable
9
 **/
10
class DataAccess {
11
12
    public function retrieveUrl($url) {
13
        $this->setContext();
14
        return @file_get_contents($url);
15
    }
16
	
17
    public function retrieveHeader($url) {
18
        $this->setContext();
19
20
        // get_headers already follows redirects and stacks headers up in array
21
        $headers = @get_headers($url, TRUE);
22
        $headers = array_change_key_case($headers);
23
24
        // if there were multiple redirects flatten down the location header
25
        if (isset($headers['location']) && is_array($headers['location'])) {
26
            $headers['location'] = array_filter($headers['location'], function ($header) {
27
                return strpos($header, '://') !== false; // leave only absolute urls
28
            });
29
30
            $headers['location'] = end($headers['location']);
31
        }
32
33
        return $headers;
34
    }
35
    
36
	
37
    public function saveCache($file, $data) {
38
        file_put_contents($file, $data);
39
    }
40
    
41
    public function readCache($file) {
42
        return file_get_contents($file);
43
    }
44
    
45
    private function setContext() {
46
        stream_context_set_default(
47
            array(
48
                'http' => array(
49
                    'method' => 'GET',
50
                    'timeout' => 10,
51
                    'header' => "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:20.0; Favicon; +https://github.com/mpclarkson/icons-craper) Gecko/20100101 Firefox/32.0\r\n",
52
                )
53
            )
54
        );
55
    }
56
}