Passed
Push — 1.0 ( da4729...c4ae60 )
by Morven
02:38 queued 10s
created

DisplayController::LogoBase64()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 2
nop 2
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverCommerce\OrdersAdmin\Control;
4
5
use SilverStripe\Control\Controller;
6
use SilverStripe\Control\Director;
7
use SilverStripe\Assets\Image;
8
use SilverStripe\Security\Member;
9
use SilverStripe\SiteConfig\SiteConfig;
10
use SilverStripe\Security\Security;
11
use SilverCommerce\OrdersAdmin\Model\Invoice;
12
use SilverCommerce\OrdersAdmin\Model\Estimate;
13
use SilverStripe\View\Requirements;
14
use SilverStripe\Control\HTTPRequest;
15
use SilverStripe\Control\HTTPStreamResponse;
16
use SilverStripe\Core\Manifest\ModuleResourceLoader;
17
use Dompdf\Dompdf;
18
use Dompdf\Options;
19
20
/**
21
 * Controller responsible for displaying either an rendered order or a
22
 * rendered quote that can be emailed or printed.
23
 *
24
 * @package Orders
25
 */
26
class DisplayController extends Controller
27
{
28
    /**
29
     * ClassName of Order object
30
     *
31
     * @var string
32
     * @config
33
     */
34
    private static $url_segment = "ordersadmin/display";
35
    
36
    
37
    private static $allowed_actions = [
38
        "invoice",
39
        "invoicepdf",
40
        "estimate",
41
        "estimatepdf"
42
    ];
43
44
    /**
45
     * directory for pdf css file (in requirements format)
46
     *
47
     * @var string
48
     * @config
49
     */
50
    private static $pdf_css = 'silvercommerce/orders-admin: client/dist/css/pdf.css';
51
52
    /**
53
     * Ther object associated with this controller
54
     *
55
     * @var Estimate
56
     */
57
    protected $object;
58
59
    protected function init()
60
    {
61
        parent::init();
62
63
        $member = Security::getCurrentUser();
64
        $object = Estimate::get()
65
            ->byID($this->getrequest()->param("ID"));
66
67
        if ($object && (
68
            ($member && $object->canView($member)) ||
69
            ($object->AccessKey && $object->AccessKey == $this->request->param("OtherID"))
70
        )) {
71
            $this->object = $object;
72
        } else {
73
            return Security::permissionFailure();
74
        }
75
    }
76
77
    /**
78
     * Generate a Dompdf object from the provided html
79
     *
80
     * @param string $html
81
     * @return Dompdf
82
     */
83
    protected function gernerate_pdf($html)
84
    {
85
        $options = new Options([
86
            "compressed" => true,
87
            'defaultFont' => 'sans-serif',
88
            'isHtml5ParserEnabled' => true,
89
            'isRemoteEnabled' => true
90
        ]);
91
        $dompdf = new Dompdf($options);
92
        $dompdf->loadHtml($html);
93
        $dompdf->setPaper('A4', 'portrait');
94
95
        return $dompdf;
96
    }
97
98
    /**
99
     * Undocumented function
100
     *
101
     * @return \SilverStripe\Assets\Image
102
     */
103
    public function Logo()
104
    {
105
        $config = SiteConfig::current_site_config();
106
        $image = $config->EstimateInvoiceLogo();
107
108
        $this->extend("updateLogo", $image);
109
        
110
        return $image;
111
    }
112
113
    /**
114
     * get the current logo as a base 64 encoded string
115
     *
116
     * @return string
117
     */
118
    public function LogoBase64(int $width = 0, int $height = 0)
119
    {
120
        $logo = $this->Logo();
121
122
        if ($width > 0 && $height > 0) {
123
            $logo = $logo->Fit($width, $height);
124
        }
125
        $string = base64_encode($logo->getString());
126
127
        $this->extend("updateLogoBase64", $string);
128
        
129
        return $string;
130
    }
131
    
132
    /**
133
     * Get a relative link to anorder or invoice
134
     *
135
     * NOTE: this controller will always require an ID of an order and
136
     * access key to be passed (as well as an action).
137
     *
138
     * @param $action Action we would like to view.
139
     * @param $id ID or the order we want to view.
140
     * @param $key Access key of the order (for security).
141
     * @return string
142
     */
143
    public function Link($action = "invoice")
144
    {
145
        return Controller::join_links(
146
            $this->config()->url_segment,
147
            $action
148
        );
149
    }
150
    
151
    /**
152
     * Get an absolute link to an order or invoice
153
     *
154
     * NOTE: this controller will always require an ID of an order and
155
     * access key to be passed (as well as an action).
156
     *
157
     * @param $action Action we would like to view.
158
     * @param $id ID or the order we want to view.
159
     * @param $key Access key of the order (for security).
160
     * @return string
161
     */
162
    public function AbsoluteLink($action = "invoice")
163
    {
164
        return Controller::join_links(
165
            Director::absoluteBaseURL(),
166
            $this->Link($action)
167
        );
168
    }
169
170
    public function invoice(HTTPRequest $request)
171
    {
172
        $config = SiteConfig::current_site_config();
173
        
174
        $this->customise([
175
            "Type" => "Invoice",
176
            "HeaderContent" => $config->dbObject("InvoiceHeaderContent"),
177
            "FooterContent" => $config->dbObject("InvoiceFooterContent"),
178
            "Title" => _t("Orders.InvoiceTitle", "Invoice"),
179
            "MetaTitle" => _t("Orders.InvoiceTitle", "Invoice"),
180
            "Object" => $this->object
181
        ]);
182
183
        $this->extend("updateInvoice");
184
        
185
        return $this->render();
186
    }
187
188
    /**
189
     * Generate a PDF based on the invoice html output.
190
     *
191
     * @todo At the moment this exits all execution after generating
192
     * and streaming PDF. Ideally this should tap into
193
     * @link http://api.silverstripe.org/4/SilverStripe/Control/HTTPStreamResponse.html
194
     *
195
     * @param HTTPRequest $request
196
     * @return void
197
     */
198
    public function invoicepdf(HTTPRequest $request)
199
    {
200
        /**
201
         * Load custom CSS for PDF explicitly (as pass)
202
         */
203
        $loader = ModuleResourceLoader::singleton();
204
        $style = file_get_contents($loader->resolvePath($this->config()->pdf_css));
205
        Requirements::clear();
206
        Requirements::customCSS(<<<CSS
207
        $style
208
CSS
209
        );
210
        $result = $this->invoice($request);
211
        $html = $result->getValue();
212
        $pdf = $this->gernerate_pdf($html);
213
214
        $this->extend("updateInvoicePDF", $pdf);
215
216
        $pdf->render();
217
        $pdf->stream("{$this->object->FullRef}.pdf");
218
        exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
219
    }
220
    
221
    public function estimate(HTTPRequest $request)
222
    {
223
        $config = SiteConfig::current_site_config();
224
        $this->customise([
225
            "Type" => "Estimate",
226
            "HeaderContent" => $config->dbObject("EstimateHeaderContent"),
227
            "FooterContent" => $config->dbObject("EstimateFooterContent"),
228
            "Title" => _t("Orders.EstimateTitle", "Estimate"),
229
            "MetaTitle" => _t("Orders.EstimateTitle", "Estimate"),
230
            "Object" => $this->object
231
        ]);
232
233
        $this->extend("updateEstimate");
234
        
235
        return $this->render();
236
    }
237
238
    public function estimatepdf(HTTPRequest $request)
239
    {
240
        /**
241
         * Load custom CSS for PDF explicitly (as pass)
242
         */
243
        $loader = ModuleResourceLoader::singleton();
244
        $style = file_get_contents($loader->resolvePath('silvercommerce/orders-admin: client/dist/css/pdf.css'));
245
        Requirements::clear();
246
        Requirements::customCSS(<<<CSS
247
        $style
248
CSS
249
        );
250
        $result = $this->estimate($request);
251
        $html = $result->getValue();
252
253
        $pdf = $this->gernerate_pdf($html);
254
255
        $this->extend("updateEstimatePDF", $pdf);
256
257
        $pdf->render();
258
        $pdf->stream("{$this->object->FullRef}.pdf");
259
        exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
260
    }
261
}
262