PDFCrowdConverter   A
last analyzed

Complexity

Total Complexity 19

Size/Duplication

Total Lines 105
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 3

Importance

Changes 0
Metric Value
wmc 19
lcom 2
cbo 3
dl 0
loc 105
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A singleton() 0 7 2
A __construct() 0 6 1
A ConvertPage() 0 4 1
C ConvertURL() 0 30 8
A removeCachedPDF() 0 8 3
A file2FolderFilename() 0 13 3
A outputPDF() 0 10 1
1
<?php
2
3
4
class PDFCrowdConverter extends Object
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
5
{
6
    private static $third_party_file = "pdfcrowd/thirdparty/pdfcrowd.php";
7
8
    private static $username = "";
9
10
    private static $api_key = "";
11
12
    private static $singleton = null;
13
14
    private static $save_pdfs_here = 'pdfs'; //e.g. assets/pdfs
15
16
    public $pdf = null;
17
18
    /**
19
     * Allows access to the cart from anywhere in code.
20
     *@return ShoppingCart Object
21
     */
22
    public static function singleton()
23
    {
24
        if (!self::$singleton) {
25
            self::$singleton = new PDFCrowdConverter();
26
        }
27
        return self::$singleton;
28
    }
29
30
    public function __construct()
31
    {
32
        require_once(Director::baseFolder() . '/' .self::$third_party_file);
33
        $this->pdf = new Pdfcrowd(self::$username, self::$api_key);
34
        parent::__construct();
35
    }
36
37
    public function ConvertPage($page)
38
    {
39
        return $this->ConvertURL(Director::AbsoluteURL($page->Link), $page->URLSegment.".pdf", true);
40
    }
41
42
    //CACHING DOES NOT WORK!
43
    public function ConvertURL($url, $filename, $useCacheIfAvailable = false)
0 ignored issues
show
Coding Style introduced by
ConvertURL uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
44
    {
45
        $folderFilename = '';
0 ignored issues
show
Unused Code introduced by
$folderFilename is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
46
        if (isset($_GET["flush"])) {
47
            $useCacheIfAvailable = false;
48
        }
49
        $folderFilename = $this->file2FolderFilename($filename);
50
        if ($folderFilename && $useCacheIfAvailable) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $folderFilename of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
51
            if (file_exists($folderFilename)) {
52
                $url = Director::absoluteBaseURL().$this->file2FolderFilename($filename, true);
53
                header("Location: $url");
54
                exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method ConvertURL() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
55
            }
56
        }
57
        try {
58
            $pdf = $this->pdf->convertURI($url);
59
        } catch (PdfcrowdException $e) {
0 ignored issues
show
Bug introduced by
The class PdfcrowdException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
60
            return "Pdfcrowd Error: " . $e->getMessage();
61
        }
62
        if ($folderFilename = $this->file2FolderFilename($filename)) {
63
            if (!$pdf) {
64
                $pdf = "error occured";
65
            }
66
            $this->removeCachedPDF($filename);
67
            $fh = fopen($folderFilename, 'w');
68
            fwrite($fh, $pdf);
69
            fclose($fh);
70
        }
71
        return $this->outputPDF($pdf, $filename);
72
    }
73
74
    public function removeCachedPDF($filename)
75
    {
76
        if ($folderFilename = $this->file2FolderFilename($filename)) {
77
            if (file_exists($folderFilename)) {
78
                unlink($folderFilename);
79
            }
80
        }
81
    }
82
83
    protected function file2FolderFilename($filename, $withoutBase = false)
84
    {
85
        if (self::$save_pdfs_here) {
86
            $folder = Director::baseFolder()."/".self::$save_pdfs_here."/";
87
            $folderObject = Folder::find_or_make($folder);
88
            if ($withoutBase) {
89
                $folderFilename = $folderObject->getRelativePath() . $filename;
90
            } else {
91
                $folderFilename = $folderObject->getFullPath() . $filename;
92
            }
93
            return $folderFilename;
94
        }
95
    }
96
97
98
    public static function outputPDF($pdfAsString, $filename)
99
    {
100
        // set HTTP response headers
101
        header("Content-Type: application/pdf");
102
        header("Cache-Control: no-cache");
103
        header("Accept-Ranges: none");
104
        header("Content-Disposition: attachment; filename=\"$filename\"");
105
        // send the generated PDF
106
        echo $pdfAsString;
107
    }
108
}
109