Completed
Push — master ( 87af87...4349fb )
by Jeroen De
237:55 queued 172:52
created

ValidateDonorHandler::newRequestModel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.4285
cc 1
eloc 13
nc 1
nop 1
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace WMDE\Fundraising\Frontend\App\RouteHandlers;
6
7
use Silex\Application;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\HttpFoundation\Response;
10
use WMDE\Fundraising\Frontend\DonationContext\Domain\Model\Donor;
11
use WMDE\Fundraising\Frontend\DonationContext\Domain\Model\DonorAddress;
12
use WMDE\Fundraising\Frontend\DonationContext\Domain\Model\DonorName;
13
use WMDE\Fundraising\Frontend\DonationContext\UseCases\ValidateDonor\ValidateDonorRequest;
14
use WMDE\Fundraising\Frontend\Factories\FunFunFactory;
15
use WMDE\FunValidators\ConstraintViolation;
16
17
/**
18
 * @license GNU GPL v2+
19
 * @author Jeroen De Dauw < [email protected] >
20
 */
21
class ValidateDonorHandler {
22
23
	private $ffFactory;
24
	private $app;
25
26
	public function __construct( FunFunFactory $ffFactory, Application $app ) {
27
		$this->ffFactory = $ffFactory;
28
		$this->app = $app;
29
	}
30
31
	public function handle( Request $request ): Response {
32
		$validationResult =
33
			$this->ffFactory->newValidateDonorUseCase()
34
				->validateDonor( $this->newRequestModel( $request ) );
35
36
		if ( $validationResult->isSuccessful() ) {
37
			return $this->newSuccessResponse();
38
		}
39
40
		return $this->newErrorResponse( ...$validationResult->getViolations() );
41
	}
42
43
	private function newRequestModel( Request $request ): ValidateDonorRequest {
44
		return ValidateDonorRequest::newInstance()
45
			->withCity( $request->get( 'city', '' ) )
46
			->withCompanyName( $request->get( 'companyName', '' ) )
47
			->withCountryCode( $request->get( 'country', '' ) )
48
			->withEmailAddress( $request->get( 'email', '' ) )
49
			->withFirstName( $request->get( 'firstName', '' ) )
50
			->withLastName( $request->get( 'lastName', '' ) )
51
			->withPostalCode( $request->get( 'postcode', '' ) )
52
			->withSalutation( $request->get( 'salutation', '' ) )
53
			->withStreetAddress( $request->get( 'street', '' ) )
54
			->withTitle( $request->get( 'title', '' ) )
55
			->withType( $request->get( 'addressType', '' ) );
56
	}
57
58
	private function newSuccessResponse(): Response {
59
		return $this->app->json( [ 'status' => 'OK' ] );
60
	}
61
62
	private function newErrorResponse( ConstraintViolation ...$violations ) {
63
		$errors = [];
64
65
		foreach( $violations as $violation ) {
66
			$errors[$violation->getSource()] = $this->ffFactory->getTranslator()->trans( $violation->getMessageIdentifier() );
67
		}
68
69
		return $this->app->json( [ 'status' => 'ERR', 'messages' => $errors ] );
70
	}
71
72
}