Completed
Push — master ( f8f77e...d2a4ab )
by Jason
05:01
created

FoxyCart::getAPIRequest()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 8.8593

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
ccs 2
cts 15
cp 0.1333
rs 8.9713
cc 3
eloc 14
nc 3
nop 1
crap 8.8593
1
<?php
2
3
namespace Dynamic\FoxyStripe\Model;
4
5
use Psr\Log\LoggerInterface;
6
use SilverStripe\Core\Injector\Injector;
7
use SilverStripe\SiteConfig\SiteConfig;
8
9
/**
10
 *
11
 */
12
class FoxyCart
13
{
14
    /**
15
     * @var string
16
     */
17
    private static $keyPrefix = 'dYnm1c';
18
19
    /**
20
     * @param int $length
21
     * @param int $count
22
     *
23
     * @return string
24
     */
25 3
    public static function setStoreKey($length = 54, $count = 0)
26
    {
27 3
        $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.strtotime('now');
28 3
        $strLength = strlen($charset);
29 3
        $str = '';
30 3
        while ($count < $length) {
31 3
            $str .= $charset[mt_rand(0, $strLength - 1)];
32 3
            ++$count;
33
        }
34
35 3
        return self::getKeyPrefix().substr(base64_encode($str), 0, $length);
36
    }
37
38
    /**
39
     * @return mixed|null
40
     */
41 49
    public static function getStoreKey()
42
    {
43 49
        $config = SiteConfig::current_site_config();
44 49
        if ($config->StoreKey) {
45
            return $config->StoreKey;
46
        }
47
48 49
        return;
49
    }
50
51
    /**
52
     * @return null|string
53
     */
54 1
    public static function store_name_warning()
55
    {
56 1
        $warning = null;
57 1
        if (self::getFoxyCartStoreName() === null) {
58 1
            $warning = 'Must define FoxyCart Store Name in your site settings in the cms';
59
        }
60
61 1
        return $warning;
62
    }
63
64
    /**
65
     * @return mixed|null
66
     */
67 1
    public static function getFoxyCartStoreName()
68
    {
69 1
        $config = SiteConfig::current_site_config();
70 1
        if ($config->StoreName) {
71
            return $config->StoreName;
72
        }
73
74 1
        return;
75
    }
76
77
    /**
78
     * @return string
79
     */
80
    public static function FormActionURL()
81
    {
82
        return sprintf('https://%s.foxycart.com/cart', self::getFoxyCartStoreName());
83
    }
84
85
    /**
86
     * FoxyCart API v1.1 functions.
87
     */
88
89
    /**
90
     * @param array $foxyData
91
     *
92
     * @return string
93
     *
94
     * @throws \Psr\Container\NotFoundExceptionInterface
95
     */
96 49
    private static function getAPIRequest($foxyData = array())
97
    {
98 49
        if (self::getStoreKey()) {
99
            $foxy_domain = self::getFoxyCartStoreName().'.foxycart.com';
100
            $foxyData['api_token'] = self::getStoreKey();
101
102
            $ch = curl_init();
103
            curl_setopt($ch, CURLOPT_URL, 'https://'.$foxy_domain.'/api');
104
            curl_setopt($ch, CURLOPT_POSTFIELDS, $foxyData);
105
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
106
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
107
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
108
            // If you get SSL errors, you can uncomment the following, or ask your host to add the appropriate CA bundle
109
            // 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...
110
            $response = trim(curl_exec($ch));
111
112
            // The following if block will print any CURL errors you might have
113
            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...
114
                //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...
115
                Injector::inst()->get(LoggerInterface::class)->error('Could not connect to FoxyCart API');
116
            }
117
            curl_close($ch);
118
119
            return $response;
120
        }
121
    }
122
123
    /**
124
     * @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...
125
     *
126
     * @return string
127
     *
128
     * @throws \Psr\Container\NotFoundExceptionInterface
129
     */
130
    public static function getCustomer($Member = null)
131
    {
132
133
        // throw error if no $Member Object
134
        if (!isset($Member)) {
135
            trigger_error('No Member set', E_USER_ERROR);
136
        }
137
138
        // grab customer record from API
139
140
        $foxyData = array();
141
        $foxyData['api_action'] = 'customer_get';
142
        if ($Member->Customer_ID) {
143
            $foxyData['customer_id'] = $Member->Customer_ID;
144
        }
145
        $foxyData['customer_email'] = $Member->Email;
146
147
        return self::getAPIRequest($foxyData);
148
    }
149
150
    /**
151
     * @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...
152
     *
153
     * @return string
154
     *
155
     * @throws \Psr\Container\NotFoundExceptionInterface
156
     */
157 49
    public static function putCustomer($Member = null)
158
    {
159
        // throw error if no $Member Object
160 49
        if (!isset($Member)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
161
//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...
162
        }
163
        // send updated customer record from API
164 49
        $foxyData = array();
165 49
        $foxyData['api_action'] = 'customer_save';
166
        // customer_id will be 0 if created in SilverStripe.
167 49
        if ($Member->Customer_ID) {
168
            $foxyData['customer_id'] = $Member->Customer_ID;
169
        }
170 49
        $foxyData['customer_email'] = $Member->Email;
171 49
        $foxyData['customer_password_hash'] = $Member->Password;
172 49
        $foxyData['customer_password_salt'] = $Member->Salt;
173 49
        $foxyData['customer_first_name'] = $Member->FirstName;
174 49
        $foxyData['customer_last_name'] = $Member->Surname;
175
176 49
        return self::getAPIRequest($foxyData);
177
    }
178
179
    /**
180
     * @return string
181
     */
182 3
    public static function getKeyPrefix()
183
    {
184 3
        return self::$keyPrefix;
185
    }
186
}
187