Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
OptinController
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
100.00% covered (success)
100.00%
1 / 1
 optin
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3namespace App\Http\Controllers\Api\V2;
4
5use App\Enums\ApiError;
6use App\Exceptions\Api\V2\ApiErrorException;
7use App\Exceptions\Api\V2\CrmException;
8use App\Http\Controllers\Controller;
9use App\Http\Requests\Api\V2\SingleOptinRequest;
10use App\Models\CustomerInfo;
11use App\Models\Service;
12use Illuminate\Http\JsonResponse;
13use App\Models\SingleOptin;
14
15class OptinController extends Controller
16{
17    /**
18     * Creates a new Single optin or destroys it if exists
19     *
20     * @param \App\Http\Requests\Api\V2\SingleOptinRequest $request
21     * @param \App\Models\Service                          $service
22     * @return \Illuminate\Http\JsonResponse
23     * @throws \App\Exceptions\Api\V2\ApiErrorException With ApiError::singleOptinCustomerExists
24     * if this email already has a full account.
25     * @throws \App\Exceptions\Api\V2\CrmException If the single optin could not be added or removed.
26     */
27    public function optin(SingleOptinRequest $request, Service $service): JsonResponse
28    {
29        if (CustomerInfo::getFromEmail($service->brand, $request->email)->exists()) {
30            throw new ApiErrorException(ApiError::singleOptinCustomerExists());
31        }
32
33        /** @var \App\Models\SingleOptin */
34        $singleOptin = SingleOptin::where('email', $request->email)
35        ->whereHas('brand', function ($q) use ($service) {
36            $q->whereId($service->brand->id);
37        })->firstOrNew();
38
39        if ($request->opt_in) {
40            $singleOptin->fill($request->validated());
41            $singleOptin->brand()->associate($service->brand);
42            $success = $singleOptin->save();
43        } else {
44            $success = $singleOptin->delete() !== false;
45        }
46
47        if (!$success) {
48            // @codeCoverageIgnoreStart
49            throw new CrmException('Api failed to update single optin.');
50            // @codeCoverageIgnoreEnd
51        }
52
53        return response()->json();
54    }
55}