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 App\Models\SingleOptin;
13
14class OptinController extends Controller
15{
16    /**
17     * Creates a new Single optin or destroys it if exists
18     *
19     * @param SingleOptinRequest $request
20     * @param Service            $service
21     * @return JsonResponse
22     * @throws ApiErrorException With ApiError::singleOptinCustomerExists if this email already has a full account.
23     * @throws CrmException If the single optin could not be added or removed.
24     */
25    public function optin(SingleOptinRequest $request, Service $service)
26    {
27        if (CustomerInfo::getFromEmail($service->brand, $request->email)->exists()) {
28            throw new ApiErrorException(ApiError::singleOptinCustomerExists());
29        }
30
31        /** @var \App\Models\SingleOptin */
32        $singleOptin = SingleOptin::where('email', $request->email)
33        ->whereHas('brand', function ($q) use ($service) {
34            $q->whereId($service->brand->id);
35        })->firstOrNew();
36
37        if ($request->opt_in) {
38            $singleOptin->fill($request->validated());
39            $singleOptin->brand()->associate($service->brand);
40            $success = $singleOptin->save();
41        } else {
42            $success = $singleOptin->delete() !== false;
43        }
44
45        if (!$success) {
46            // @codeCoverageIgnoreStart
47            throw new CrmException('Api failed to update single optin.');
48            // @codeCoverageIgnoreEnd
49        }
50
51        return response()->json();
52    }
53}