Passed
Push — master ( f470d1...2a4a9b )
by Jason
02:06
created

DataTestController::xml()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Dynamic\Foxy\Orders\Controller;
4
5
use Dynamic\Foxy\Extension\Purchasable;
6
use Dynamic\Foxy\Extension\Shippable;
7
use Dynamic\Foxy\Orders\Controller\FoxyController;
8
use Dynamic\Foxy\Model\FoxyHelper;
9
use Dynamic\Foxy\Orders\Model\Order;
10
use GuzzleHttp\Client;
11
use SilverStripe\CMS\Model\SiteTree;
12
use SilverStripe\Control\Controller;
13
use SilverStripe\Control\Director;
14
use SilverStripe\Core\Injector\Injector;
15
use SilverStripe\Dev\DebugView;
16
use SilverStripe\ORM\ArrayList;
17
use SilverStripe\Security\Member;
18
use SilverStripe\Security\PasswordEncryptor;
19
20
/**
21
 * Class DataTestController
22
 * @package Dynamic\FoxyStripe\Controller
23
 */
24
class DataTestController extends Controller
25
{
26
    private static $allowed_actions = [
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
27
        'index',
28
        'xml',
29
    ];
30
31
    /**
32
     * @var array
33
     */
34
    private static $data = [
0 ignored issues
show
introduced by
The private property $data is not used, and could be removed.
Loading history...
35
        "TransactionDate" => "now",
36
        "OrderID" => "auto",
37
        "Email" => "auto",
38
        "Password" => "password",
39
        "OrderDetails" => [],
40
    ];
41
42
    /**
43
     * @throws \SilverStripe\ORM\ValidationException
44
     */
45
    public function index()
46
    {
47
        $rules = Director::config()->get('rules');
48
        $rule = array_search(FoxyController::class, $rules);
49
        $myURL = Director::absoluteBaseURL() . explode('//', $rule)[0];
0 ignored issues
show
Bug introduced by
It seems like $rule can also be of type false; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

49
        $myURL = Director::absoluteBaseURL() . explode('//', /** @scrutinizer ignore-type */ $rule)[0];
Loading history...
50
51
        $helper = new FoxyHelper();
52
        $myKey = $helper->config()->get('secret');
53
54
        $XMLOutput_encrypted = \rc4crypt::encrypt($myKey, $this->xml());
55
        $XMLOutput_encrypted = urlencode($XMLOutput_encrypted);
56
57
        $client = new Client();
58
        $response = $client->request('POST', $myURL, [
59
            'form_params' => ['FoxyData' => $XMLOutput_encrypted]
60
        ]);
61
62
        $configString = print_r(static::config()->get('data'), true);
63
        /** @var DebugView $view */
64
        $view = Injector::inst()->create(DebugView::class);
65
        echo $view->renderHeader();
66
        echo '<div class="info">';
67
        echo "<h2>Config:</h2><pre>$configString</pre>";
68
        if ($this->getRequest()->getVar('data')) {
69
            echo "<h2>Data:</h2><pre>{$xml->HTML()}</pre>";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $xml seems to be never defined.
Loading history...
70
        }
71
        echo "<h2>Response:</h2><pre>" . $response->getBody() . "</pre>";
72
        echo '<p></p>';
73
        echo '</div>';
74
        echo $view->renderFooter();
75
    }
76
77
    /**
78
     *
79
     */
80
    private function updateConfig()
81
    {
82
        $data = static::config()->get('data');
83
        $transactionDate = $data['TransactionDate'];
84
        static::config()->merge('data', [
85
            'TransactionDate' => strtotime($transactionDate),
86
        ]);
87
88
        $orderID = $data['OrderID'];
89
        if ($orderID === 'auto' || $orderID < 1) {
90
            $lastOrderID = 0;
91
            if ($lastOrder = Order::get()->sort('OrderID')->last()) {
92
                $lastOrderID = $lastOrder->OrderID;
93
            };
94
            static::config()->merge('data', [
95
                'OrderID' => $lastOrderID + 1,
96
            ]);
97
        }
98
99
        $email = $data['Email'];
100
        if ($email === 'auto') {
101
            static::config()->merge('data', [
102
                'Email' => $this->generateEmail(),
103
            ]);
104
        }
105
106
        $orderDetails = $data['OrderDetails'];
107
        if (count($orderDetails) === 0) {
108
            static::config()->merge('data', [
109
                'OrderDetails' => [
110
                    $this->generateOrderDetail()
111
                ],
112
            ]);
113
        }
114
115
        if (!array_key_exists('Salt', $data)) {
116
            static::config()->merge('data', [
117
                'Salt' => 'faGgWXUTdZ7i42lpA6cljzKeGBeUwShBSNHECwsJmt',
118
            ]);
119
        }
120
121
        if (!array_key_exists('HashType', $data)) {
122
            static::config()->merge('data', [
123
                'HashType' => 'sha1_v2.4',
124
            ]);
125
        }
126
127
        $data = static::config()->get('data');
128
        if (!array_key_exists('HashedPassword', $data)) {
129
            $encryptor = PasswordEncryptor::create_for_algorithm($data['HashType']);
130
            static::config()->merge('data', [
131
                'HashedPassword' => $encryptor->encrypt($data['Password'], $data['Salt']),
132
            ]);
133
        }
134
    }
135
136
    /**
137
     * @return string
138
     */
139
    private function generateEmail()
140
    {
141
        $emails = Member::get()->filter([
142
            'Email:EndsWith' => '@example.com',
143
        ])->column('Email');
144
145
        if ($emails && count($emails)) {
146
            $email = $emails[count($emails) - 1];
147
            return preg_replace_callback(
148
                "|(\d+)|",
149
                function ($mathces) {
150
                    return ++$mathces[1];
151
                },
152
                $email
153
            );
154
        }
155
        return '[email protected]';
156
    }
157
158
    /**
159
     * @return array
160
     */
161
    private function generateOrderDetail()
162
    {
163
        return [
164
            'Title' => 'foo',
165
            'Price' => 20.00,
166
            'Quantity' => 1,
167
            'Weight' => 0.1,
168
            'DeliveryType' => 'shipped',
169
            'CategoryDescription' => 'Default cateogry',
170
            'CategoryCode' => 'DEFAULT',
171
            'Options' => ArrayList::create([
172
                [
173
                    'Name' => 'color',
174
                    'OptionValue' => 'blue',
175
                    'PriceMod' => '',
176
                    'WeightMod' => '',
177
                ],
178
                [
179
                    'Name' => 'product_id',
180
                    'OptionValue' => $this->getTestProduct(),
181
                    'PriceMod' => '',
182
                    'WeightMod' => '',
183
                ]
184
            ])
185
        ];
186
    }
187
188
    /**
189
     * @return bool
190
     */
191
    public function getTestProduct()
192
    {
193
        $pages = SiteTree::get();
194
        foreach ($pages as $page) {
195
            if ($page->hasExtension(Purchasable::class) || $page->hasExtension(Shippable::class)) {
196
                return $page->ID;
197
            }
198
        }
199
        return false;
200
    }
201
202
    /**
203
     * @return mixed|string
204
     */
205
    public function xml()
206
    {
207
        $this->updateConfig();
208
        $config = static::config()->get('data');
209
        $config['OrderDetails'] = ArrayList::create($config['OrderDetails']);
210
        $xml = $this->renderWith('TestData', $config);
211
        return $xml->RAW();
212
    }
213
}
214