Passed
Push — master ( f04d85...f0f514 )
by Artem
01:45
created

Account::createPromoCredit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
// ---------------------------------------------------------------------
4
//
5
//  Copyright (C) 2018-2024 Artem Rodygin
6
//
7
//  You should have received a copy of the MIT License along with
8
//  this file. If not, see <https://opensource.org/licenses/MIT>.
9
//
10
// ---------------------------------------------------------------------
11
12
namespace Linode\Account;
13
14
use Linode\Account\Repository\EventRepository;
15
use Linode\Account\Repository\InvoiceRepository;
16
use Linode\Account\Repository\NotificationRepository;
17
use Linode\Account\Repository\OAuthClientRepository;
18
use Linode\Account\Repository\PaymentMethodRepository;
19
use Linode\Account\Repository\PaymentRepository;
20
use Linode\Account\Repository\ServiceTransferRepository;
21
use Linode\Account\Repository\UserRepository;
22
use Linode\Entity;
23
use Linode\Exception\LinodeException;
24
use Linode\LinodeClient;
25
use Linode\Longview\LongviewSubscription;
26
use Linode\Managed\StatsDataAvailable;
27
28
/**
29
 * Account object.
30
 *
31
 * @property string                             $first_name         The first name of the person associated with this Account.
32
 *                                                                  Must not include any of the following characters: `<` `>` `(` `)` `"` `=`
33
 * @property string                             $last_name          The last name of the person associated with this Account.
34
 *                                                                  Must not include any of the following characters: `<` `>` `(` `)` `"` `=`
35
 * @property string                             $email              The email address of the person associated with this Account.
36
 * @property float                              $balance            This Account's balance, in US dollars.
37
 * @property float                              $balance_uninvoiced This Account's current estimated invoice in US dollars. This is not your final
38
 *                                                                  invoice balance. Transfer charges are not included in the estimate.
39
 * @property string                             $company            The company name associated with this Account.
40
 *                                                                  Must not include any of the following characters: `<` `>` `(` `)` `"` `=`
41
 * @property string                             $address_1          First line of this Account's billing address.
42
 * @property string                             $address_2          Second line of this Account's billing address.
43
 * @property string                             $city               The city for this Account's billing address.
44
 * @property string                             $state              If billing address is in the United States (US) or Canada (CA), only the
45
 *                                                                  two-letter ISO 3166 State or Province code are accepted. If entering a US military
46
 *                                                                  address, state abbreviations (AA, AE, AP) should be entered. If the address is
47
 *                                                                  outside the US or CA, this is the Province associated with the Account's billing
48
 *                                                                  address.
49
 * @property string                             $zip                The zip code of this Account's billing address. The following restrictions apply:
50
 *                                                                  - May only consist of letters, numbers, spaces, and hyphens.
51
 *                                                                  - Must not contain more than 9 letter or number characters.
52
 * @property string                             $country            The two-letter ISO 3166 country code of this Account's billing address.
53
 * @property string                             $phone              The phone number associated with this Account.
54
 * @property string                             $tax_id             The tax identification number associated with this Account, for tax calculations
55
 *                                                                  in some countries. If you do not live in a country that collects tax, this should
56
 *                                                                  be an empty string (`""`).
57
 * @property CreditCardData                     $credit_card        Credit Card information associated with this Account.
58
 * @property string                             $active_since       The datetime of when the account was activated.
59
 * @property string[]                           $capabilities       A list of capabilities your account supports.
60
 * @property Promotion[]                        $active_promotions  A list of active promotions on your account.
61
 * @property string                             $billing_source     The source of service charges for this Account, as determined by its relationship
62
 *                                                                  with Akamai.
63
 *                                                                  Accounts that are associated with Akamai-specific customers return a value of
64
 *                                                                  `akamai`.
65
 *                                                                  All other Accounts return a value of `linode`.
66
 * @property string                             $euuid              An external unique identifier for this account.
67
 * @property EventRepositoryInterface           $events             List of Event objects representing actions taken on your Account. The Events
68
 *                                                                  returned depends on your grants.
69
 * @property InvoiceRepositoryInterface         $invoices           List of Invoices against your Account.
70
 * @property NotificationRepositoryInterface    $notifications      List of Notification objects representing important, often time-sensitive items
71
 *                                                                  related to your Account.
72
 * @property OAuthClientRepositoryInterface     $oauth_clients      List of OAuth Clients registered to your Account. OAuth Clients allow users to log
73
 *                                                                  into applications you write or host using their Linode Account, and may allow them
74
 *                                                                  to grant some level of access to their Linodes or other entities to your
75
 *                                                                  application.
76
 * @property PaymentRepositoryInterface         $payments           List of Payments made on this Account.
77
 * @property PaymentMethodRepositoryInterface   $paymentMethods     List of Payment Methods for this Account.
78
 * @property ServiceTransferRepositoryInterface $serviceTransfers   List of Service Transfer objects containing the details of all transfers that have
79
 *                                                                  been created and accepted by this account.
80
 * @property UserRepositoryInterface            $users              List of Users on your Account. Users may access all or part of your Account based
81
 *                                                                  on their restricted status and grants. An unrestricted User may access everything
82
 *                                                                  on the account, whereas restricted User may only access entities or perform
83
 *                                                                  actions they've been given specific grants to.
84
 *
85
 * @codeCoverageIgnore This class was autogenerated.
86
 */
87
class Account extends Entity
88
{
89
    // Available fields.
90
    public const FIELD_FIRST_NAME         = 'first_name';
91
    public const FIELD_LAST_NAME          = 'last_name';
92
    public const FIELD_EMAIL              = 'email';
93
    public const FIELD_BALANCE            = 'balance';
94
    public const FIELD_BALANCE_UNINVOICED = 'balance_uninvoiced';
95
    public const FIELD_COMPANY            = 'company';
96
    public const FIELD_ADDRESS_1          = 'address_1';
97
    public const FIELD_ADDRESS_2          = 'address_2';
98
    public const FIELD_CITY               = 'city';
99
    public const FIELD_STATE              = 'state';
100
    public const FIELD_ZIP                = 'zip';
101
    public const FIELD_COUNTRY            = 'country';
102
    public const FIELD_PHONE              = 'phone';
103
    public const FIELD_TAX_ID             = 'tax_id';
104
    public const FIELD_CREDIT_CARD        = 'credit_card';
105
    public const FIELD_ACTIVE_SINCE       = 'active_since';
106
    public const FIELD_CAPABILITIES       = 'capabilities';
107
    public const FIELD_ACTIVE_PROMOTIONS  = 'active_promotions';
108
    public const FIELD_BILLING_SOURCE     = 'billing_source';
109
    public const FIELD_EUUID              = 'euuid';
110
111
    // `FIELD_BILLING_SOURCE` values.
112
    public const BILLING_SOURCE_AKAMAI = 'akamai';
113
    public const BILLING_SOURCE_LINODE = 'linode';
114
115
    /**
116
     * Returns the contact and billing information related to your Account.
117
     *
118
     * @throws LinodeException
119
     */
120
    public function __construct(LinodeClient $client)
121
    {
122
        parent::__construct($client);
123
124
        $response = $this->client->get('/account');
125
        $contents = $response->getBody()->getContents();
126
        $json     = json_decode($contents, true);
127
128
        $this->data = $json;
129
    }
130
131
    /**
132
     * @codeCoverageIgnore This method was autogenerated.
133
     */
134
    public function __get(string $name): mixed
135
    {
136
        return match ($name) {
137
            self::FIELD_CREDIT_CARD       => new CreditCardData($this->client, $this->data[$name]),
138
            self::FIELD_ACTIVE_PROMOTIONS => array_map(fn ($data) => new Promotion($this->client, $data), $this->data[$name]),
139
            'events'                      => new EventRepository($this->client),
140
            'invoices'                    => new InvoiceRepository($this->client),
141
            'notifications'               => new NotificationRepository($this->client),
142
            'oauth_clients'               => new OAuthClientRepository($this->client),
143
            'payments'                    => new PaymentRepository($this->client),
144
            'paymentMethods'              => new PaymentMethodRepository($this->client),
145
            'serviceTransfers'            => new ServiceTransferRepository($this->client),
146
            'users'                       => new UserRepository($this->client),
147
            default                       => parent::__get($name),
148
        };
149
    }
150
151
    /**
152
     * Updates contact and billing information related to your Account.
153
     *
154
     * @param array $parameters Update contact and billing information.
155
     *
156
     * Account properties that are excluded from a request remain unchanged.
157
     *
158
     * When updating an Account's `country` to "US", an error is returned if the
159
     * Account's `zip` is not a valid US zip code.
160
     *
161
     * @throws LinodeException
162
     */
163
    public function updateAccount(array $parameters = []): self
164
    {
165
        $response   = $this->client->put('/account', $parameters);
166
        $contents   = $response->getBody()->getContents();
167
        $this->data = json_decode($contents, true);
168
169
        return $this;
170
    }
171
172
    /**
173
     * Cancels an active Linode account. This action will cause Linode to attempt to
174
     * charge the credit card on file for the remaining balance. An error will occur if
175
     * Linode fails to charge the credit card on file. Restricted users will not be able
176
     * to cancel an account.
177
     *
178
     * @param string $comments Any reason for cancelling the account, and any other comments you might have about
179
     *                         your Linode service.
180
     *
181
     * @return string A link to Linode's exit survey.
182
     *
183
     * @throws LinodeException
184
     */
185
    public function cancelAccount(string $comments): string
186
    {
187
        $parameters = [
188
            'comments' => $comments,
189
        ];
190
191
        $response = $this->client->post('/account/cancel', $parameters);
192
        $contents = $response->getBody()->getContents();
193
        $json     = json_decode($contents, true);
194
195
        return $json['survey_link'];
196
    }
197
198
    /**
199
     * **DEPRECATED**. Please use Payment Method Add (POST /account/payment-methods).
200
     *
201
     * Adds a credit card Payment Method to your account and sets it as the default
202
     * method.
203
     *
204
     * @param string $card_number  Your credit card number. No spaces or dashes allowed.
205
     * @param string $expiry_month A value from 1-12 representing the expiration month of your credit card.
206
     * @param string $expiry_year  A four-digit integer representing the expiration year of your credit card.
207
     * @param string $cvv          The Card Verification Value on the back of the card.
208
     *
209
     * @throws LinodeException
210
     */
211
    public function createCreditCard(string $card_number, string $expiry_month, string $expiry_year, string $cvv): void
212
    {
213
        $parameters = [
214
            'card_number'  => $card_number,
215
            'expiry_month' => $expiry_month,
216
            'expiry_year'  => $expiry_year,
217
            'cvv'          => $cvv,
218
        ];
219
220
        $this->client->post('/account/credit-card', $parameters);
221
    }
222
223
    /**
224
     * Returns a collection of successful logins for all users on the account during the
225
     * last 90 days. This command can only be accessed by the unrestricted users of an
226
     * account.
227
     *
228
     * @return Login[] A collection of successful logins for all users on the account during the last 90
229
     *                 days.
230
     *
231
     * @throws LinodeException
232
     */
233
    public function getAccountLogins(): array
234
    {
235
        $response = $this->client->get('/account/logins');
236
        $contents = $response->getBody()->getContents();
237
        $json     = json_decode($contents, true);
238
239
        return array_map(fn ($data) => new Login($this->client, $data), $json['data']);
240
    }
241
242
    /**
243
     * Returns a Login object that displays information about a successful login. The
244
     * logins that can be viewed can be for any user on the account, and are not limited
245
     * to only the logins of the user that is accessing this API endpoint. This command
246
     * can only be accessed by the unrestricted users of the account.
247
     *
248
     * @param int $loginId The ID of the login object to access.
249
     *
250
     * @throws LinodeException
251
     */
252
    public function getAccountLogin(int $loginId): Login
253
    {
254
        $response = $this->client->get("/account/logins/{$loginId}");
255
        $contents = $response->getBody()->getContents();
256
        $json     = json_decode($contents, true);
257
258
        return new Login($this->client, $json);
259
    }
260
261
    /**
262
     * Returns a collection of Maintenance objects for any entity a user has permissions
263
     * to view. Canceled Maintenance objects are not returned.
264
     *
265
     * Currently, Linodes are the only entities available for viewing.
266
     *
267
     * @throws LinodeException
268
     */
269
    public function getMaintenance(): array
270
    {
271
        $response = $this->client->get('/account/maintenance');
272
        $contents = $response->getBody()->getContents();
273
274
        return json_decode($contents, true);
275
    }
276
277
    /**
278
     * Returns a Transfer object showing your network utilization, in GB, for the current
279
     * month.
280
     *
281
     * @throws LinodeException
282
     */
283
    public function getTransfer(): Transfer
284
    {
285
        $response = $this->client->get('/account/transfer');
286
        $contents = $response->getBody()->getContents();
287
        $json     = json_decode($contents, true);
288
289
        return new Transfer($this->client, $json);
290
    }
291
292
    /**
293
     * Returns information related to your Account settings: Managed service
294
     * subscription, Longview subscription, and network helper.
295
     *
296
     * @throws LinodeException
297
     */
298
    public function getAccountSettings(): AccountSettings
299
    {
300
        $response = $this->client->get('/account/settings');
301
        $contents = $response->getBody()->getContents();
302
        $json     = json_decode($contents, true);
303
304
        return new AccountSettings($this->client, $json);
305
    }
306
307
    /**
308
     * Updates your Account settings.
309
     *
310
     * To update your Longview subscription plan, send a request to Update Longview Plan.
311
     *
312
     * @param array $parameters Update Account settings information.
313
     *
314
     * @throws LinodeException
315
     */
316
    public function updateAccountSettings(array $parameters = []): AccountSettings
317
    {
318
        $response = $this->client->put('/account/settings', $parameters);
319
        $contents = $response->getBody()->getContents();
320
        $json     = json_decode($contents, true);
321
322
        return new AccountSettings($this->client, $json);
323
    }
324
325
    /**
326
     * Enables Linode Managed for the entire account and sends a welcome email to the
327
     * account's associated email address. Linode Managed can monitor any service or
328
     * software stack reachable over TCP or HTTP. See our Linode Managed guide to learn
329
     * more.
330
     *
331
     * @throws LinodeException
332
     */
333
    public function enableAccountManaged(): void
334
    {
335
        $this->client->post('/account/settings/managed-enable');
336
    }
337
338
    /**
339
     * Send a one-time verification code via SMS message to the submitted phone number.
340
     * Providing your phone number helps ensure you can securely access your Account in
341
     * case other ways to connect are lost. Your phone number is only used to verify your
342
     * identity by sending an SMS message. Standard carrier messaging fees may apply.
343
     *
344
     * * By accessing this command you are opting in to receive SMS messages. You can opt
345
     * out of SMS messages by using the **Phone Number Delete** (DELETE
346
     * /profile/phone-number) command after your phone number is verified.
347
     *
348
     * * Verification codes are valid for 10 minutes after they are sent.
349
     *
350
     * * Subsequent requests made prior to code expiration result in sending the same
351
     * code.
352
     *
353
     * Once a verification code is received, verify your phone number with the **Phone
354
     * Number Verify** (POST /profile/phone-number/verify) command.
355
     *
356
     * @param string $iso_code     The two-letter ISO 3166 country code associated with the phone number.
357
     * @param string $phone_number A valid phone number.
358
     *
359
     * @throws LinodeException
360
     */
361
    public function postProfilePhoneNumber(string $iso_code, string $phone_number): void
362
    {
363
        $parameters = [
364
            'iso_code'     => $iso_code,
365
            'phone_number' => $phone_number,
366
        ];
367
368
        $this->client->post('/profile/phone-number', $parameters);
369
    }
370
371
    /**
372
     * Verify a phone number by confirming the one-time code received via SMS message
373
     * after accessing the **Phone Verification Code Send** (POST /profile/phone-number)
374
     * command.
375
     *
376
     * * Verification codes are valid for 10 minutes after they are sent.
377
     *
378
     * * Only the same User that made the verification code request can use that code
379
     * with this command.
380
     *
381
     * Once completed, the verified phone number is assigned to the User making the
382
     * request. To change the verified phone number for a User, first use the **Phone
383
     * Number Delete** (DELETE /profile/phone-number) command, then begin the
384
     * verification process again with the **Phone Verification Code Send** (POST
385
     * /profile/phone-number) command.
386
     *
387
     * @param string $otp_code The one-time code received via SMS message after accessing the **Phone
388
     *                         Verification Code Send** (POST /profile/phone-number) command.
389
     *
390
     * @throws LinodeException
391
     */
392
    public function postProfilePhoneNumberVerify(string $otp_code): void
393
    {
394
        $parameters = [
395
            'otp_code' => $otp_code,
396
        ];
397
398
        $this->client->post('/profile/phone-number/verify', $parameters);
399
    }
400
401
    /**
402
     * Delete the verified phone number for the User making this request.
403
     *
404
     * Use this command to opt out of SMS messages for the requesting User after a phone
405
     * number has been verified with the **Phone Number Verify** (POST
406
     * /profile/phone-number/verify) command.
407
     *
408
     * @throws LinodeException
409
     */
410
    public function deleteProfilePhoneNumber(): void
411
    {
412
        $this->client->delete('/profile/phone-number');
413
    }
414
415
    /**
416
     * Returns a collection of security questions and their responses, if any, for your
417
     * User Profile.
418
     *
419
     * @return SecurityQuestion[] List of security questions.
420
     *
421
     * @throws LinodeException
422
     */
423
    public function getSecurityQuestions(): array
424
    {
425
        $response = $this->client->get('/profile/security-questions');
426
        $contents = $response->getBody()->getContents();
427
        $json     = json_decode($contents, true);
428
429
        return array_map(fn ($data) => new SecurityQuestion($this->client, $data), $json['security_questions']);
430
    }
431
432
    /**
433
     * Adds security question responses for your User.
434
     *
435
     * Requires exactly three unique questions.
436
     *
437
     * Previous responses are overwritten if answered or reset to `null` if unanswered.
438
     *
439
     * **Note**: Security questions must be answered for your User prior to accessing the
440
     * **Two Factor Secret Create** (POST /profile/tfa-enable) command.
441
     *
442
     * @param array $parameters Answer Security Questions
443
     *
444
     * @return SecurityQuestion[] List of security questions.
445
     *
446
     * @throws LinodeException
447
     */
448
    public function postSecurityQuestions(array $parameters = []): array
449
    {
450
        $response = $this->client->post('/profile/security-questions', $parameters);
451
        $contents = $response->getBody()->getContents();
452
        $json     = json_decode($contents, true);
453
454
        return array_map(fn ($data) => new SecurityQuestion($this->client, $data), $json['security_questions']);
455
    }
456
457
    /**
458
     * Get the details of your current Longview plan. This returns a
459
     * `LongviewSubscription` object for your current Longview Pro plan, or an empty set
460
     * `{}` if your current plan is Longview Free.
461
     *
462
     * You must have at least one of the following `global` User Grants in order to
463
     * access this endpoint:
464
     *
465
     *   - `"account_access": read_write`
466
     *   - `"account_access": read_only`
467
     *   - `"longview_subscription": true`
468
     *   - `"add_longview": true`
469
     *
470
     * To update your subscription plan, send a request to Update Longview Plan.
471
     *
472
     * @throws LinodeException
473
     */
474
    public function getLongviewPlan(): LongviewSubscription
475
    {
476
        $response = $this->client->get('/longview/plan');
477
        $contents = $response->getBody()->getContents();
478
        $json     = json_decode($contents, true);
479
480
        return new LongviewSubscription($this->client, $json);
481
    }
482
483
    /**
484
     * Update your Longview plan to that of the given subcription ID. This returns a
485
     * `LongviewSubscription` object for the updated Longview Pro plan, or an empty set
486
     * `{}` if the updated plan is Longview Free.
487
     *
488
     * You must have `"longview_subscription": true` configured as a `global` User Grant
489
     * in order to access this endpoint.
490
     *
491
     * You can send a request to the List Longview Subscriptions endpoint to receive the
492
     * details, including `id`'s, of each plan.
493
     *
494
     * @param array $parameters Update your Longview subscription plan.
495
     *
496
     * @throws LinodeException
497
     */
498
    public function updateLongviewPlan(array $parameters = []): LongviewSubscription
499
    {
500
        $response = $this->client->put('/longview/plan', $parameters);
501
        $contents = $response->getBody()->getContents();
502
        $json     = json_decode($contents, true);
503
504
        return new LongviewSubscription($this->client, $json);
505
    }
506
507
    /**
508
     * Adds an expiring Promo Credit to your account.
509
     *
510
     * The following restrictions apply:
511
     *
512
     * * Your account must be less than 90 days old.
513
     * * There must not be an existing Promo Credit already on your account.
514
     * * The requesting User must be unrestricted. Use the User Update
515
     *   (PUT /account/users/{username}) to change a User's restricted status.
516
     * * The `promo_code` must be valid and unexpired.
517
     *
518
     * @param array $parameters Enter a Promo Code to add its associated credit to your Account.
519
     *
520
     * @throws LinodeException
521
     */
522
    public function createPromoCredit(array $parameters = []): Promotion
523
    {
524
        $response = $this->client->post('/account/promo-codes', $parameters);
525
        $contents = $response->getBody()->getContents();
526
        $json     = json_decode($contents, true);
527
528
        return new Promotion($this->client, $json);
529
    }
530
531
    /**
532
     * Returns a list of Managed Stats on your Account in the form of x and y data
533
     * points.
534
     * You can use these data points to plot your own graph visualizations. These stats
535
     * reflect the last 24 hours of combined usage across all managed Linodes on your
536
     * account
537
     * giving you a high-level snapshot of data for the following:
538
     *
539
     * * cpu
540
     * * disk
541
     * * swap
542
     * * network in
543
     * * network out
544
     *
545
     * This command can only be accessed by the unrestricted users of an account.
546
     *
547
     * @return StatsDataAvailable A list of Managed Stats from the last 24 hours.
548
     *
549
     * @throws LinodeException
550
     */
551
    public function getManagedStats(): StatsDataAvailable
552
    {
553
        $response = $this->client->get('/managed/stats');
554
        $contents = $response->getBody()->getContents();
555
        $json     = json_decode($contents, true);
556
557
        return new StatsDataAvailable($this->client, $json);
558
    }
559
}
560