Completed
Push — master ( ee94a5...d975bd )
by Nicolaas
04:02
created

CartResponse::set_force_reload()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * @description: returns the cart as JSON
5
 *
6
 * @authors: Nicolaas [at] Sunny Side Up .co.nz
7
 * @package: ecommerce
8
 * @sub-package: control
9
 * @inspiration: Silverstripe Ltd, Jeremy
10
 **/
11
class CartResponse extends EcommerceResponse
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...
12
{
13
    /**
14
     * Should the page be reloaded rather than using AJAX?
15
     *
16
     * @var bool
17
     */
18
    private static $force_reload = false;
19
20
    /**
21
     * Should the page be reloaded rather than using AJAX?
22
     *
23
     * @var bool
24
     */
25
    protected $includeHeaders = true;
26
27
    /**
28
     * Sets the $force_reload to true;.
29
     */
30
    public static function set_force_reload()
31
    {
32
        self::$force_reload = true;
33
    }
34
35
    /**
36
     * turn the json headers on or off...
37
     * useful if you want to use the json data
38
     * but not the associated header.
39
     *
40
     * @param bool
41
     */
42
    public function setIncludeHeaders($b)
43
    {
44
        $this->includeHeaders = $b;
45
    }
46
47
    /**
48
     * Builds json object to be returned via ajax.
49
     *
50
     * @param array  $message        (Type, Message)
0 ignored issues
show
Documentation introduced by
There is no parameter named $message. Did you maybe mean $messages?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
51
     * @param array  $additionalData
0 ignored issues
show
Documentation introduced by
Should the type for parameter $additionalData not be null|array?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
52
     * @param string $status
53
     *
54
     * @return HEADER + JSON
0 ignored issues
show
Documentation introduced by
Should the return type not be string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
55
     **/
56
    public function ReturnCartData(array $messages = array(), array $additionalData = null, $status = 'success')
0 ignored issues
show
Coding Style introduced by
ReturnCartData uses the super-global variable $_REQUEST 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...
57
    {
58
        //add header
59
        if ($this->includeHeaders) {
60
            $this->addHeader('Content-Type', 'application/json');
61
        }
62
63
        SSViewer::set_source_file_comments(false);
0 ignored issues
show
Deprecated Code introduced by
The method SSViewer::set_source_file_comments() has been deprecated with message: 4.0 Use the "SSViewer.source_file_comments" config setting instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
64
        //merge messages
65
        $messagesImploded = '';
66
        if (is_array($messages) && count($messages)) {
67
            foreach ($messages as $messageArray) {
68
                $messagesImploded .= '<span class="'.$messageArray['Type'].'">'.$messageArray['Message'].'</span>';
69
            }
70
        }
71
72
        //bad status
73
        if ($status != 'success') {
74
            $this->setStatusCode(400, $messagesImploded);
75
        }
76
77
        //init Order - IMPORTANT
78
        $currentOrder = ShoppingCart::current_order();
79
80
        //THIS LINE TAKES UP MOST OF THE TIME OF THE RESPONSE!!!
81
        $currentOrder->calculateOrderAttributes($force = false);
82
83
        $ajaxObject = $currentOrder->AJAXDefinitions();
84
        // populate Javascript
85
        $js = array();
86
87
        //must be first
88
        if (isset($_REQUEST['loadingindex'])) {
89
            $js[] = array(
90
                't' => 'loadingindex',
91
                'v' => $_REQUEST['loadingindex'],
92
            );
93
        }
94
95
        //order items
96
97
        $inCartArray = array();
98
        $items = $currentOrder->Items();
99
        if ($items->count()) {
100
            foreach ($items as $item) {
101
                $js = $item->updateForAjax($js);
102
                $buyable = $item->Buyable(true);
103
                if ($buyable) {
104
                    //products in cart
105
                    $inCartArray[] = $buyable->AJAXDefinitions()->UniqueIdentifier();
106
                    //HACK TO INCLUDE PRODUCT IN PRODUCT VARIATION
107
                    if (is_a($buyable, 'ProductVariation')) {
108
                        $inCartArray[] = $buyable->Product()->AJAXDefinitions()->UniqueIdentifier();
109
                    }
110
                }
111
            }
112
        }
113
114
        //in cart items
115
        $js[] = array(
116
            't' => 'replaceclass',
117
            's' => $inCartArray,
118
            'p' => $currentOrder->AJAXDefinitions()->ProductListItemClassName(),
119
            'v' => $currentOrder->AJAXDefinitions()->ProductListItemInCartClassName(),
120
            'without' => $currentOrder->AJAXDefinitions()->ProductListItemNotInCartClassName(),
121
        );
122
123
        //order modifiers
124
        $modifiers = $currentOrder->Modifiers();
125
        if ($modifiers->count()) {
126
            foreach ($modifiers as $modifier) {
127
                $js = $modifier->updateForAjax($js);
128
            }
129
        }
130
131
        //order
132
        $js = $currentOrder->updateForAjax($js);
133
134
        //messages
135
        if (is_array($messages)) {
136
            $js[] = array(
137
                't' => 'id',
138
                's' => $ajaxObject->TableMessageID(),
139
                'p' => 'innerHTML',
140
                'v' => $messagesImploded,
141
                'isOrderMessage' => true,
142
            );
143
            $js[] = array(
144
                't' => 'id',
145
                's' => $ajaxObject->TableMessageID(),
146
                'p' => 'hide',
147
                'v' => 0,
148
            );
149
        } else {
150
            $js[] = array(
151
                't' => 'id',
152
                's' => $ajaxObject->TableMessageID(),
153
                'p' => 'hide',
154
                'v' => 1,
155
            );
156
        }
157
158
        //TO DO: set it up in such a way that it specifically requests one of these
159
        $templates = EcommerceConfig::get('CartResponse', 'cart_responses_required');
160
        foreach ($templates as $idMethod => $template) {
0 ignored issues
show
Bug introduced by
The expression $templates of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
161
            $selector = $ajaxObject->$idMethod();
162
            $classOrID = 'id';
163
            if (strpos($selector, 'ID') === false || strpos($selector, '_class') !== false) {
164
                $classOrID = 'class';
165
            }
166
            $js[] = array(
167
                't' => $classOrID,
168
                's' => $selector,
169
                'p' => 'innerHTML',
170
                //note the space is a hack to return something!
171
                'v' => ' '.$currentOrder->renderWith($template),
172
            );
173
        }
174
        //now can check if it needs to be reloaded
175
        if (self::$force_reload) {
176
            $js = array(
177
                'reload' => 1,
178
            );
179
        } else {
180
            $js[] = array(
181
                'reload' => 0,
182
            );
183
        }
184
185
        //merge and return
186
        if (is_array($additionalData) && count($additionalData)) {
187
            $js = array_merge($js, $additionalData);
188
        }
189
        //TODO: remove doubles?
190
        //turn HTMLText (et al.) objects into text
191
        foreach ($js as $key => $node) {
192
            if (isset($node['v'])) {
193
                if ($node['v'] instanceof DBField) {
194
                    $js[$key]['v'] = $node['v']->forTemplate();
195
                }
196
            }
197
        }
198
        $json = json_encode($js);
199
        $json = str_replace('\t', ' ', $json);
200
        $json = str_replace('\r', ' ', $json);
201
        $json = str_replace('\n', ' ', $json);
202
        $json = preg_replace('/\s\s+/', ' ', $json);
203
        if (Director::isDev()) {
204
            $json = str_replace('{', "\r\n{", $json);
205
        }
206
207
        return $json;
208
    }
209
}
210