Completed
Pull Request — master (#373)
by Nic
07:48
created

FoxyCart::getStoreKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 8
ccs 0
cts 5
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Dynamic\FoxyStripe\Model;
4
5
use Psr\Log\LoggerInterface;
6
use SilverStripe\Core\Injector\Injector;
7
use SilverStripe\Dev\Debug;
8
use SilverStripe\SiteConfig\SiteConfig;
9
use SilverStripe\Security\Member;
10
11
/**
12
 *
13
 */
14
class FoxyCart
15
{
16
    /**
17
     * @var string
18
     */
19
    private static $keyPrefix = 'dYnm1c';
20
21
    /**
22
     * @param int $length
23
     * @param int $count
24
     *
25
     * @return string
26
     */
27 3
    public static function setStoreKey($length = 54, $count = 0)
28
    {
29 3
        $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.strtotime('now');
30 3
        $strLength = strlen($charset);
31 3
        $str = '';
32 3
        while ($count < $length) {
33 3
            $str .= $charset[mt_rand(0, $strLength - 1)];
34 3
            ++$count;
35
        }
36
37 3
        return self::getKeyPrefix().substr(base64_encode($str), 0, $length);
38
    }
39
40
    /**
41
     * @return mixed|null
42
     * @throws \SilverStripe\ORM\ValidationException
43
     */
44
    public static function getStoreKey()
45
    {
46
        $config = FoxyStripeSetting::current_foxystripe_setting();
47
        if ($config->StoreKey) {
48
            return $config->StoreKey;
49
        }
50
51
        return false;
52
    }
53
54
    /**
55
     * @return null|string
56
     * @throws \SilverStripe\ORM\ValidationException
57
     */
58 1
    public static function store_name_warning()
59
    {
60 1
        $warning = null;
61 1
        if (self::getFoxyCartStoreName() === null) {
62
            $warning = 'Must define FoxyCart Store Name or Store Remote Domain in your site settings in the cms';
63
        }
64
65 1
        return $warning;
66
    }
67
68
    /**
69
     * @return mixed|null
70
     * @throws \SilverStripe\ORM\ValidationException
71
     */
72 1
    public static function getFoxyCartStoreName()
73
    {
74 1
        $config = FoxyStripeSetting::current_foxystripe_setting();
75 1
        if ($config->CustomSSL) {
0 ignored issues
show
Bug Best Practice introduced by
The property CustomSSL does not exist on Dynamic\FoxyStripe\Model\FoxyStripeSetting. Since you implemented __get, consider adding a @property annotation.
Loading history...
76
            if ($config->RemoteDomain) {
0 ignored issues
show
Bug Best Practice introduced by
The property RemoteDomain does not exist on Dynamic\FoxyStripe\Model\FoxyStripeSetting. Since you implemented __get, consider adding a @property annotation.
Loading history...
77
                return $config->RemoteDomain;
78
            }
79
        } else {
80 1
            if ($config->StoreName) {
81
                return $config->StoreName;
82
            }
83
        }
84
85 1
        return false;
86
    }
87
88
    /**
89
     * @return string
90
     * @throws \SilverStripe\ORM\ValidationException
91
     */
92
    public static function FormActionURL()
93
    {
94
        $config = FoxyStripeSetting::current_foxystripe_setting();
95
        if ($config->CustomSSL) {
0 ignored issues
show
Bug Best Practice introduced by
The property CustomSSL does not exist on Dynamic\FoxyStripe\Model\FoxyStripeSetting. Since you implemented __get, consider adding a @property annotation.
Loading history...
96
            return sprintf('https://%s/cart', self::getFoxyCartStoreName());
97
        } else {
98
            return sprintf('https://%s.foxycart.com/cart', self::getFoxyCartStoreName());
99
        }
100
    }
101
102
    /**
103
     * FoxyCart API v1.1 functions.
104
     */
105
106
    /**
107
     * @param array $foxyData
108
     * @return string
109
     * @throws \SilverStripe\ORM\ValidationException
110
     */
111
    private static function getAPIRequest($foxyData = array())
112
    {
113
        if (self::getStoreKey() && self::getFoxyCartStoreName()) {
114
            $config = FoxyStripeSetting::current_foxystripe_setting();
115
            if ($config->CustomSSL) {
0 ignored issues
show
Bug Best Practice introduced by
The property CustomSSL does not exist on Dynamic\FoxyStripe\Model\FoxyStripeSetting. Since you implemented __get, consider adding a @property annotation.
Loading history...
116
                $foxy_domain = self::getFoxyCartStoreName();
117
            } else {
118
                $foxy_domain = self::getFoxyCartStoreName().'.foxycart.com';
119
            }
120
121
            $foxyData['api_token'] = self::getStoreKey();
122
123
            $ch = curl_init();
124
            curl_setopt($ch, CURLOPT_URL, 'https://'.$foxy_domain.'/api');
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_setopt() does only seem to accept resource, 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

124
            curl_setopt(/** @scrutinizer ignore-type */ $ch, CURLOPT_URL, 'https://'.$foxy_domain.'/api');
Loading history...
125
            curl_setopt($ch, CURLOPT_POSTFIELDS, $foxyData);
126
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
127
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
128
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
129
            // If you get SSL errors, you can uncomment the following, or ask your host to add the appropriate CA bundle
130
            // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
131
            $response = trim(curl_exec($ch));
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, 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

131
            $response = trim(curl_exec(/** @scrutinizer ignore-type */ $ch));
Loading history...
132
133
            // The following if block will print any CURL errors you might have
134
            if ($response == false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $response of type string to the boolean false. If you are specifically checking for an empty string, consider using the more explicit === '' instead.
Loading history...
135
                //trigger_error("Could not connect to FoxyCart API", E_USER_ERROR);
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
136
                Injector::inst()->get(LoggerInterface::class)->error('Could not connect to FoxyCart API');
137
            }
138
            curl_close($ch);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, 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

138
            curl_close(/** @scrutinizer ignore-type */ $ch);
Loading history...
139
140
            return $response;
141
        }
142
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
143
    }
144
145
    /**
146
     * @param null $Member
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $Member is correct as it would always require null to be passed?
Loading history...
147
     * @return string
148
     * @throws \SilverStripe\ORM\ValidationException
149
     */
150
    public static function getCustomer(Member $Member = null)
151
    {
152
153
        // throw error if no $Member Object
154
        if (!isset($Member)) {
155
            trigger_error('No Member set', E_USER_ERROR);
156
        }
157
158
        // grab customer record from API
159
160
        $foxyData = array();
161
        $foxyData['api_action'] = 'customer_get';
162
        if ($Member->Customer_ID) {
163
            $foxyData['customer_id'] = $Member->Customer_ID;
164
        }
165
        $foxyData['customer_email'] = $Member->Email;
166
167
        return self::getAPIRequest($foxyData);
168
    }
169
170
    /**
171
     * @param null $Member
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $Member is correct as it would always require null to be passed?
Loading history...
172
     * @return string
173
     * @throws \SilverStripe\ORM\ValidationException
174
     */
175
    public static function putCustomer(Member $Member = null)
176
    {
177
        // throw error if no $Member Object
178
        if ($Member === null) {
179
//trigger_error('No Member set', E_USER_ERROR);
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
180
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
181
        }
182
        // send updated customer record from API
183
        $foxyData = array();
184
        $foxyData['api_action'] = 'customer_save';
185
        // customer_id will be 0 if created in SilverStripe.
186
        if ($Member->Customer_ID) {
187
            $foxyData['customer_id'] = $Member->Customer_ID;
188
        }
189
        $foxyData['customer_email'] = $Member->Email;
190
        $foxyData['customer_password_hash'] = $Member->Password;
191
        $foxyData['customer_password_salt'] = $Member->Salt;
192
        $foxyData['customer_first_name'] = $Member->FirstName;
193
        $foxyData['customer_last_name'] = $Member->Surname;
194
195
        return self::getAPIRequest($foxyData);
196
    }
197
198
    /**
199
     * @return string
200
     */
201 3
    public static function getKeyPrefix()
202
    {
203 3
        return self::$keyPrefix;
204
    }
205
}
206