Completed
Branch master (a84ec0)
by Shaharia
02:45 queued 01:18
created

Accounts   F

Complexity

Total Complexity 89

Size/Duplication

Total Lines 348
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 89
eloc 153
dl 0
loc 348
rs 2
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
C getDetails() 0 38 12
C searchAccounts() 0 55 13
D create() 0 145 60
A availableFunctions() 0 9 3

How to fix   Complexity   

Complex Class

Complex classes like Accounts often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Accounts, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PreviewTechs\cPanelWHM\WHM;
4
5
use Http\Client\Exception;
6
use PreviewTechs\cPanelWHM\Entity\Account;
7
use PreviewTechs\cPanelWHM\Exceptions\ClientExceptions;
8
use PreviewTechs\cPanelWHM\WHMClient;
9
10
/**
11
 * Class Accounts
12
 *
13
 * @package PreviewTechs\cPanelWHM\WHM
14
 */
15
class Accounts
16
{
17
    /**
18
     *
19
     * @var WHMClient
20
     */
21
    protected $client;
22
23
    /**
24
     * Accounts constructor.
25
     *
26
     * @param WHMClient $client
27
     */
28
    public function __construct(WHMClient $client)
29
    {
30
        $this->client = $client;
31
    }
32
33
    /**
34
     * Search accounts from your WHM server.
35
     *
36
     * WHM API function: Accounts -> listaccts
37
     *
38
     * $accounts = new Accounts($c);
39
     * $keyword = "search_keyword";
40
     * $searchType = "username";   //valid search types are "domain", "owner", "user", "ip", "package"
41
     * $options = [
42
     *       'searchmethod' => "exact",   //"exact" or "regex",
43
     *       "page" => 1,
44
     *       "limit" => 10,   //per page,
45
     *       "want" => "username"    //A comma-separated list of fields you want to fetch
46
     *   ];
47
     *
48
     * try {
49
     *       $accounts->searchAccounts($keyword, $searchType, $options);
50
     *   } catch (\Http\Client\Exception $e) {
51
     *       echo $e->getMessage();
52
     *   } catch (\PreviewTechs\cPanelWHM\Exceptions\ClientExceptions $e) {
53
     *       echo $e->getMessage();
54
     *   }
55
     *
56
     * @link https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+listaccts
57
     *
58
     * @param null $keyword
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $keyword is correct as it would always require null to be passed?
Loading history...
59
     * @param null $searchType
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $searchType is correct as it would always require null to be passed?
Loading history...
60
     * @param array $options
61
     *
62
     * @return array
63
     * @throws ClientExceptions
64
     * @throws Exception
65
     */
66
    public function searchAccounts($keyword = null, $searchType = null, array $options = [])
67
    {
68
        $limit = 10;
69
        $page = 1;
70
71
        $params = [
72
            'api.version' => 1,
73
            'api.chunk.enable' => 1,
74
            'api.chunk.size' => $limit,
75
            'api.chunk.start' => $page * $limit
76
        ];
77
78
        if (!empty($options['limit'])) {
79
            $params['api.chunk.size'] = intval($options['limit']);
80
        }
81
82
        if (!empty($options['page'])) {
83
            $params['api.chunk.start'] = intval($options['page']) * $params['api.chunk.size'];
84
        }
85
86
        if (!empty($searchType) && !in_array($searchType, ["domain", "owner", "user", "ip", "package"])) {
87
            throw new \InvalidArgumentException("`searchType` must be one of these - domain, owner, user, ip, package");
88
        }
89
90
        if (!empty($options['searchmethod']) && !in_array($options['searchmethod'], ["exact", "regex"])) {
91
            throw new \InvalidArgumentException("options[searchmethod] must be either `regex` or `exact`");
92
        }
93
94
        if (!empty($options['want'])) {
95
            $params['want'] = $options['want'];
96
        }
97
98
        if (!empty($searchType)) {
99
            $params['searchtype'] = $searchType;
100
        }
101
102
        if (!empty($keyword)) {
103
            $params['search'] = $keyword;
104
            empty($searchType) ? $params['searchtype'] = "user" : null;
105
        }
106
107
        $results = $this->client->sendRequest("/json-api/listaccts", "GET", $params);
108
        if (empty($results['data']['acct'])) {
109
            return [];
110
        }
111
112
        $accounts = [];
113
        foreach ($results['data']['acct'] as $account) {
114
            $accounts[] = Account::buildFromArray($account);
115
        }
116
117
        return [
118
            'accounts' => $accounts,
119
            'count' => $params['api.chunk.size'],
120
            'page' => $page
121
        ];
122
    }
123
124
    /**
125
     * Get an account details
126
     *
127
     * WHM API function: Accounts -> accountsummary
128
     *
129
     * @link https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+accountsummary
130
     *
131
     * @param null $user
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $user is correct as it would always require null to be passed?
Loading history...
132
     * @param null $domain
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $domain is correct as it would always require null to be passed?
Loading history...
133
     *
134
     * @return null|Account
135
     * @throws ClientExceptions
136
     * @throws Exception
137
     */
138
    public function getDetails($user = null, $domain = null)
139
    {
140
        if (empty($user) && empty($domain)) {
141
            throw ClientExceptions::invalidArgument("You must provide either a username or a domain or both");
142
        }
143
144
        if (!empty($user) && !empty($domain)) {
145
            throw ClientExceptions::invalidArgument(
146
                "You must provide only one argument either user OR domain (not both)"
147
            );
148
        }
149
150
        $params = [];
151
152
        if (!empty($user)) {
153
            $params['user'] = $user;
154
        }
155
156
        if (!empty($domain)) {
157
            $params['domain'] = $domain;
158
        }
159
160
        $result = $this->client->sendRequest("/json-api/accountsummary", "GET", $params);
161
        if (empty($result)) {
162
            return null;
163
        }
164
165
        if ($result['status'] === 0) {
166
            throw ClientExceptions::recordNotFound(
167
                !empty($result['statusmsg']) ? $result['statusmsg'] : "Record not found"
168
            );
169
        }
170
171
        if (!empty($result['acct']) && is_array($result['acct'])) {
172
            return Account::buildFromArray($result['acct'][0]);
173
        }
174
175
        return null;
176
    }
177
178
    /**
179
     * This function lists available WHM API 1 functions.
180
     *
181
     * This function only lists the functions that are available to the current user.
182
     * For example, if the authenticated user is a reseller without root -level privileges,
183
     * the function will not list WHM API 1 functions that require root privileges.
184
     *
185
     * WHM API function: Accounts -> applist
186
     *
187
     * @link https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+applist
188
     *
189
     * @return array
190
     * @throws ClientExceptions
191
     * @throws Exception
192
     */
193
    public function availableFunctions()
194
    {
195
        $result = $this->client->sendRequest("/json-api/applist", 'GET', []);
196
197
        if (!empty($result['app']) && sizeof($result['app']) > 0) {
198
            return $result['app'];
199
        }
200
201
        return [];
202
    }
203
204
    /**
205
     * Create a new account. This function creates a cPanel account.
206
     * The function also sets up the new account's domain information.
207
     *
208
     * WHM API function: Accounts -> createacct
209
     *
210
     * @link    https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+createacct
211
     *
212
     * @param Account $account
213
     * @param array $options
214
     * @return array
215
     * @throws ClientExceptions
216
     * @throws Exception
217
     */
218
    public function create(Account $account, array $options = [])
219
    {
220
        if (empty($account->getUser())) {
221
            throw ClientExceptions::invalidArgument("You must provide an username to create new account");
222
        }
223
224
        if (empty($account->getDomain())) {
225
            throw ClientExceptions::invalidArgument("You must provide a domain to create new account");
226
        }
227
228
        $params = [];
229
        $params['username'] = $account->getUser();
230
        $params['domain'] = $account->getDomain();
231
        !empty($account->getPlanName()) ? $params['plan'] = $account->getPlanName() : null;
232
        !empty($options['pkgname']) ? $params['pkgname'] = $options['pkgname'] : null;
233
        if (!empty($options['savepkg'])) {
234
            if (!in_array(intval($options['savepkg']), [0, 1])) {
235
                throw new ClientExceptions("`savepkg` must be either 0 or 1");
236
            }
237
238
            $params['savepkg'] = $options['savepkg'];
239
        }
240
241
        !empty($options['featurelist']) ? $params['featurelist'] = $options['featurelist'] : null;
242
        if (!empty($account->getDiskLimit())) {
243
            if ($account->getDiskLimit() === -1) {
244
                $params['quota'] = 0;
245
            } else {
246
                $params['quota'] = intval($account->getDiskLimit());
247
            }
248
        }
249
250
        !empty($account->getPassword()) ? $params['password'] = $account->getPassword() : null;
251
        !empty($account->getIpAddress()) ? $params['ip'] = $account->getIpAddress() : null;
252
        !empty($account->isCgiEnable()) ? $params['cgi'] = (int)$account->isCgiEnable() : null;
253
        !empty($account->isSpamAssassinEnable()) ?
254
            $params['spamassassin'] = (int)$account->isSpamAssassinEnable()
255
            : null;
256
        !empty($account->isFrontPageEnable()) ? $params['frontpage'] = (int)$account->isFrontPageEnable() : null;
257
        !empty($account->getShell()) ? $params['hasshell'] = 1 : null;
258
        !empty($account->getEmail()) ? $params['contactemail'] = 1 : null;
259
        !empty($account->getEmail()) ? $params['contactemail'] = 1 : null;
260
        !empty($account->getTheme()) ? $params['cpmod'] = 1 : null;
261
262
        if ($account->getMaxFTP() === -1) {
263
            $params['maxftp'] = "unlimited";
264
        } elseif ($account->getMaxFTP() > 0) {
265
            $params['maxftp'] = intval($account->getMaxFTP());
266
        }
267
268
        if ($account->getMaxSQL() === -1) {
269
            $params['maxsql'] = "unlimited";
270
        } elseif ($account->getMaxSQL() > 0) {
271
            $params['maxsql'] = intval($account->getMaxSQL());
272
        }
273
274
        if ($account->getMaxPOP() === -1) {
275
            $params['maxpop'] = "unlimited";
276
        } elseif ($account->getMaxPOP() > 0) {
277
            $params['maxpop'] = intval($account->getMaxPOP());
278
        }
279
280
        if ($account->getMaxMailingList() === -1) {
281
            $params['maxlst'] = "unlimited";
282
        } elseif ($account->getMaxMailingList() > 0) {
283
            $params['maxlst'] = intval($account->getMaxMailingList());
284
        }
285
286
        if ($account->getMaxSubDomain() === -1) {
287
            $params['maxsub'] = "unlimited";
288
        } elseif ($account->getMaxSubDomain() > 0) {
289
            $params['maxsub'] = intval($account->getMaxSubDomain());
290
        }
291
292
        if ($account->getMaxParkedDomains() === -1) {
293
            $params['maxpark'] = "unlimited";
294
        } elseif ($account->getMaxParkedDomains() > 0) {
295
            $params['maxpark'] = intval($account->getMaxParkedDomains());
296
        }
297
298
        if ($account->getMaxAddonDomains() === -1) {
299
            $params['maxaddon'] = "unlimited";
300
        } elseif ($account->getMaxAddonDomains() > 0) {
301
            $params['maxaddon'] = intval($account->getMaxAddonDomains());
302
        }
303
304
        if ($account->getBandwidthLimit() === -1) {
305
            $params['bwlimit'] = "unlimited";
306
        } elseif ($account->getBandwidthLimit() > 0) {
307
            $params['bwlimit'] = intval($account->getBandwidthLimit());
308
        }
309
310
        !empty($options['customip']) ? $params['customip'] = $options['customip'] : null;
311
312
        !empty($account->getLanguagePreference()) ? $params['language'] = $account->getLanguagePreference() : null;
313
314
        !empty($options['useregns']) ? $params['useregns'] = $options['useregns'] : null;
315
        !empty($options['reseller']) ? $params['reseller'] = (int)$options['reseller'] : null;
316
        !empty($options['forcedns']) ? $params['forcedns'] = (int)$options['forcedns'] : null;
317
318
        !empty($account->getMailboxFormat()) ? $params['mailbox_format'] = $account->getMailboxFormat() : null;
319
320
        if (!empty($options['mxcheck'])) {
321
            if (!in_array($options['mxcheck'], ['local', 'secondary', 'remote', 'auto'])) {
322
                throw new ClientExceptions("options[mxcheck] parameters must be one of local, secondary, remote, auto");
323
            }
324
325
            $params['mxcheck'] = $options['mxcheck'];
326
        }
327
328
        if ($account->getMaxEmailPerHour() === -1) {
329
            $params['max_email_per_hour'] = "unlimited";
330
        } elseif ($account->getMaxEmailPerHour() > 0) {
331
            $params['max_email_per_hour'] = intval($account->getMaxEmailPerHour());
332
        }
333
334
        if ($account->getMaxEmailAccountQuota() === -1) {
335
            $params['max_emailacct_quota'] = "unlimited";
336
        } elseif ($account->getMaxEmailAccountQuota() > 0) {
337
            $params['max_email_per_hour'] = intval($account->getMaxEmailAccountQuota());
338
        }
339
340
        if ($account->getMaxDeferFailMailPercentage() === -1) {
341
            $params['max_defer_fail_percentage'] = "unlimited";
342
        } elseif ($account->getMaxDeferFailMailPercentage() > 0) {
343
            $params['max_defer_fail_percentage'] = intval($account->getMaxDeferFailMailPercentage());
344
        }
345
346
        !empty($account->getUid()) ? $params['uid'] = $account->getUid() : null;
347
        !empty($account->getPartition()) ? $params['homedir'] = $account->getPartition() : null;
348
        !empty($options['dkim']) ? $params['dkim'] = intval($options['dkim']) : null;
349
        !empty($options['spf']) ? $params['spf'] = intval($options['spf']) : null;
350
        !empty($account->getOwner()) ? $params['owner'] = $account->getOwner() : null;
351
352
        $result = $this->client->sendRequest("/json-api/createacct", "GET", $params);
353
354
        if (!empty($result) && !empty($result['result'][0]) && $result['result'][0]['status'] === 0) {
355
            throw new ClientExceptions($result['result'][0]['statusmsg']);
356
        }
357
358
        if (!empty($result) && !empty($result['result'][0]) && $result['result'][0]['status'] === 1) {
359
            return ['result' => $result['result'][0]['options'], 'raw_output' => $result['result'][0]['rawout']];
360
        }
361
362
        return [];
363
    }
364
}
365