Passed
Push — master ( e5f64f...dec0ac )
by Jason
01:47
created

DataTestController::generateOrderDetail()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 17
nc 1
nop 0
dl 0
loc 22
rs 9.7
c 0
b 0
f 0
1
<?php
2
3
namespace Dynamic\Foxy\Controller;
4
5
use Dynamic\Foxy\Controller\FoxyController;
6
use Dynamic\Foxy\Model\FoxyHelper;
7
use Dynamic\Foxy\Model\Order;
8
use GuzzleHttp\Client;
9
use SilverStripe\Control\Controller;
10
use SilverStripe\Control\Director;
11
use SilverStripe\Core\Injector\Injector;
12
use SilverStripe\Dev\DebugView;
13
use SilverStripe\ORM\ArrayList;
14
use SilverStripe\Security\Member;
15
use SilverStripe\Security\PasswordEncryptor;
16
17
/**
18
 * Class DataTestController
19
 * @package Dynamic\FoxyStripe\Controller
20
 */
21
class DataTestController extends Controller
22
{
23
    private static $allowed_actions = [
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
24
        'index',
25
        'xml',
26
    ];
27
28
    /**
29
     * @var array
30
     */
31
    private static $data = [
0 ignored issues
show
introduced by
The private property $data is not used, and could be removed.
Loading history...
32
        "TransactionDate" => "now",
33
        "OrderID" => "auto",
34
        "Email" => "auto",
35
        "Password" => "password",
36
        "OrderDetails" => [],
37
    ];
38
39
    /**
40
     * @throws \SilverStripe\ORM\ValidationException
41
     */
42
    public function index()
43
    {
44
        $rules = Director::config()->get('rules');
45
        $rule = array_search(FoxyController::class, $rules);
46
        $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

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