FoxyDataGeneratorController   A
last analyzed

Complexity

Total Complexity 21

Size/Duplication

Total Lines 210
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 99
c 1
b 0
f 0
dl 0
loc 210
rs 10
wmc 21

7 Methods

Rating   Name   Duplication   Size   Complexity  
A xml() 0 11 1
A encryptedXML() 0 5 1
A generateOrderDetail() 0 22 1
A getTestProduct() 0 10 4
B updateConfig() 0 48 9
A generateEmail() 0 19 3
A index() 0 30 2
1
<?php
2
3
namespace Dynamic\Foxy\Parser\Controller;
4
5
use Dynamic\Foxy\Extension\Purchasable;
6
use Dynamic\Foxy\Extension\Shippable;
7
use Dynamic\Foxy\Model\FoxyHelper;
8
use GuzzleHttp\Client;
0 ignored issues
show
Bug introduced by
The type GuzzleHttp\Client was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use SilverStripe\CMS\Model\SiteTree;
10
use SilverStripe\Control\Controller;
11
use SilverStripe\Control\Director;
12
use SilverStripe\Core\Config\Config;
13
use SilverStripe\Core\Injector\Injector;
14
use SilverStripe\Dev\DebugView;
15
use SilverStripe\ORM\ArrayList;
16
use SilverStripe\Security\Member;
17
use SilverStripe\Security\PasswordEncryptor;
18
19
/**
20
 * Class FoxyDataGeneratorController
21
 * @package Dynamic\Foxy\Parser\Controller
22
 */
23
class FoxyDataGeneratorController extends Controller
24
{
25
    /**
26
     * @var array
27
     */
28
    private static $allowed_actions = [
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
29
        'index',
30
        'xml',
31
        'encryptedXML',
32
    ];
33
34
    /**
35
     * @var array
36
     */
37
    private static $data = [
0 ignored issues
show
introduced by
The private property $data is not used, and could be removed.
Loading history...
38
        "TransactionDate" => "now",
39
        "OrderID" => "auto",
40
        "Email" => "auto",
41
        "Password" => "password",
42
        "OrderDetails" => [],
43
    ];
44
45
    /**
46
     * @throws \GuzzleHttp\Exception\GuzzleException
47
     * @throws \SilverStripe\ORM\ValidationException
48
     * @throws \SilverStripe\Security\PasswordEncryptor_NotFoundException
49
     */
50
    public function index()
51
    {
52
        $rules = Director::config()->get('rules');
53
        $rule = array_search(FoxyController::class, $rules);
54
        $myURL = Director::absoluteBaseURL() . explode('//', $rule)[0];
55
56
        $helper = new FoxyHelper();
57
        $myKey = $helper->config()->get('secret');
0 ignored issues
show
Unused Code introduced by
The assignment to $myKey is dead and can be removed.
Loading history...
58
59
        $XMLOutput_encrypted = $this->encryptedXML();
60
        $XMLOutput_encrypted = urlencode($XMLOutput_encrypted);
61
62
        $client = new Client();
63
        $response = $client->request('POST', $myURL, [
64
            'form_params' => ['FoxyData' => $XMLOutput_encrypted],
65
        ]);
66
67
        $configString = print_r(static::config()->get('data'), true);
68
        /** @var DebugView $view */
69
        $view = Injector::inst()->create(DebugView::class);
70
        echo $view->renderHeader();
71
        echo '<div class="info">';
72
        echo "<h2>Config:</h2><pre>$configString</pre>";
73
        if ($this->getRequest()->getVar('data')) {
74
            //echo "<h2>Data:</h2><pre>{$xml->HTML()}</pre>";
75
        }
76
        echo "<h2>Response:</h2><pre>" . $response->getBody() . "</pre>";
77
        echo '<p></p>';
78
        echo '</div>';
79
        echo $view->renderFooter();
80
    }
81
82
    /**
83
     * @throws \SilverStripe\Security\PasswordEncryptor_NotFoundException
84
     */
85
    private function updateConfig()
86
    {
87
        $data = Config::inst()->get(self::class, 'data');
88
        $transactionDate = $data['TransactionDate'];
89
        static::config()->merge('data', [
90
            'TransactionDate' => strtotime($transactionDate),
91
        ]);
92
93
        $orderID = $data['OrderID'];
94
        if ($orderID === 'auto' || $orderID < 1) {
95
            static::config()->merge('data', [
96
                'OrderID' => rand(0, 5000),
97
            ]);
98
        }
99
100
        $email = $data['Email'];
101
        if ($email === 'auto') {
102
            static::config()->merge('data', [
103
                'Email' => $this->generateEmail(),
104
            ]);
105
        }
106
107
        $orderDetails = $data['OrderDetails'];
108
        if ($orderDetails === null || count($orderDetails) === 0) {
109
            static::config()->merge('data', [
110
                'OrderDetails' => [
111
                    $this->generateOrderDetail(),
112
                ],
113
            ]);
114
        }
115
116
        if (!array_key_exists('Salt', $data)) {
117
            static::config()->merge('data', [
118
                'Salt' => 'faGgWXUTdZ7i42lpA6cljzKeGBeUwShBSNHECwsJmt',
119
            ]);
120
        }
121
122
        if (!array_key_exists('HashType', $data)) {
123
            static::config()->merge('data', [
124
                'HashType' => 'sha1_v2.4',
125
            ]);
126
        }
127
128
        $data = static::config()->get('data');
129
        if (!array_key_exists('HashedPassword', $data)) {
130
            $encryptor = PasswordEncryptor::create_for_algorithm($data['HashType']);
131
            static::config()->merge('data', [
132
                'HashedPassword' => $encryptor->encrypt($data['Password'], $data['Salt']),
133
            ]);
134
        }
135
    }
136
137
    /**
138
     * @return string
139
     */
140
    private function generateEmail()
141
    {
142
        $emails = Member::get()->filter([
143
            'Email:EndsWith' => '@example.com',
144
        ])->column('Email');
145
146
        if ($emails && count($emails)) {
147
            $email = $emails[count($emails) - 1];
148
149
            return preg_replace_callback(
150
                "|(\d+)|",
151
                function ($mathces) {
152
                    return ++$mathces[1];
153
                },
154
                $email
155
            );
156
        }
157
158
        return '[email protected]';
159
    }
160
161
    /**
162
     * @return array
163
     */
164
    private function generateOrderDetail()
165
    {
166
        return [
167
            'Title' => 'foo',
168
            'Price' => 20.00,
169
            'Quantity' => 1,
170
            'Weight' => 0.1,
171
            'DeliveryType' => 'shipped',
172
            'CategoryDescription' => 'Default cateogry',
173
            'CategoryCode' => 'DEFAULT',
174
            'Options' => ArrayList::create([
175
                [
176
                    'Name' => 'color',
177
                    'OptionValue' => 'blue',
178
                    'PriceMod' => '',
179
                    'WeightMod' => '',
180
                ],
181
                [
182
                    'Name' => 'product_id',
183
                    'OptionValue' => $this->getTestProduct(),
184
                    'PriceMod' => '',
185
                    'WeightMod' => '',
186
                ],
187
            ]),
188
        ];
189
    }
190
191
    /**
192
     * @return bool
193
     */
194
    public function getTestProduct()
195
    {
196
        $pages = SiteTree::get();
197
        foreach ($pages as $page) {
198
            if ($page->hasExtension(Purchasable::class) || $page->hasExtension(Shippable::class)) {
199
                return $page->ID;
200
            }
201
        }
202
203
        return false;
204
    }
205
206
    /**
207
     * @return mixed|string
208
     * @throws \SilverStripe\Security\PasswordEncryptor_NotFoundException
209
     */
210
    public function xml()
211
    {
212
        $this->updateConfig();
213
214
        $config = static::config()->get('data');
215
216
        $config['OrderDetails'] = ArrayList::create($config['OrderDetails']);
217
218
        $xml = $this->renderWith('TestData', $config);
219
220
        return $xml->RAW();
221
    }
222
223
    /**
224
     * @return string
225
     * @throws \SilverStripe\ORM\ValidationException
226
     * @throws \SilverStripe\Security\PasswordEncryptor_NotFoundException
227
     */
228
    public function encryptedXML()
229
    {
230
        $helper = new FoxyHelper();
231
232
        return \rc4crypt::encrypt($helper->config()->get('secret'), $this->xml());
233
    }
234
}
235