Completed
Push — master ( 9ea506...789ce9 )
by Robbie
13s
created

CurlLinkChecker::getCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\ExternalLinks\Tasks;
4
5
use Psr\SimpleCache\CacheInterface;
6
use SilverStripe\Core\Injector\Injector;
7
8
/**
9
 * Check links using curl
10
 */
11
class CurlLinkChecker implements LinkChecker
12
{
13
14
    /**
15
     * Return cache
16
     *
17
     * @return Zend_Cache_Frontend
0 ignored issues
show
Bug introduced by
The type SilverStripe\ExternalLin...sks\Zend_Cache_Frontend was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
     */
19
    protected function getCache()
20
    {
21
        return Injector::inst()->get(CacheInterface::class . '.CurlLinkChecker');
22
    }
23
24
    /**
25
     * Determine the http status code for a given link
26
     *
27
     * @param string $href URL to check
28
     * @return int HTTP status code, or null if not checkable (not a link)
29
     */
30
    public function checkLink($href)
31
    {
32
        // Skip non-external links
33
        if (!preg_match('/^https?[^:]*:\/\//', $href)) {
34
            return null;
35
        }
36
37
        // Check if we have a cached result
38
        $cacheKey = md5($href);
39
        $result = $this->getCache()->get($cacheKey);
40
        if ($result !== false) {
41
            return $result;
42
        }
43
44
        // No cached result so just request
45
        $handle = curl_init($href);
46
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
47
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
48
        curl_setopt($handle, CURLOPT_TIMEOUT, 10);
49
        curl_exec($handle);
50
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
51
        curl_close($handle);
52
53
        // Cache result
54
        $this->getCache()->set($httpCode, $cacheKey);
55
        return $httpCode;
56
    }
57
}
58