diff --git a/.gitignore b/.gitignore index a6b4c86..8617a7a 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,5 @@ .DS_Store .swp composer.lock -phpunit.xml build vendor diff --git a/README.md b/README.md index 7c691e7..bbafe6b 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Baseado no repositório [https://github.com/lucasmro/ClearSale](https://github.c ## Requisitos -PHP 5.5+ +PHP 7.1+ Extensões PHP diff --git a/composer.json b/composer.json index b9fad0e..fdf0aba 100644 --- a/composer.json +++ b/composer.json @@ -30,6 +30,11 @@ "RodrigoPedra\\": "src/" } }, + "autoload-dev": { + "psr-4": { + "RodrigoPedra\\Tests\\": "tests/" + } + }, "scripts": { "test": "phpunit" } diff --git a/examples/airline-ticket-order-example.php b/examples/airline-ticket-order-example.php index bc0329c..1e63d9a 100644 --- a/examples/airline-ticket-order-example.php +++ b/examples/airline-ticket-order-example.php @@ -1,55 +1,55 @@ '; // ambiente - $environment = new Sandbox( $entityCode, new ExampleLogger ); - $environment->setDebug( true ); + $environment = new Sandbox($entityCode, new ExampleLogger()); + $environment->setDebug(true); // serviços - $connector = new Connector( $environment ); - $integration = new Integration( $connector ); - $clearSale = new Analysis( $integration ); + $connector = new Connector($environment); + $integration = new Integration($connector); + $clearSale = new Analysis($integration); // Dados do Pedido - $fingerPrint = new FingerPrint( createSessionId() ); - $orderId = createOrderId(); - $date = new \DateTime(); - $email = 'cliente@clearsale.com.br'; - $totalItems = 10.0; - $totalOrder = 17.5; + $fingerPrint = new FingerPrint(createSessionId()); + $orderId = createOrderId(); + $date = new \DateTime(); + $email = 'cliente@clearsale.com.br'; + $totalItems = 10.0; + $totalOrder = 17.5; $quantityInstallments = 1; - $ip = '127.0.0.1'; - $origin = 'WEB'; - $customerBillingData = createCustomerBillingData(); + $ip = '127.0.0.1'; + $origin = 'WEB'; + $customerBillingData = createCustomerBillingData(); $customerShippingData = createCustomerShippingData(); - $item = Item::create( 1, 'Adaptador USB', 10.0, 1 ); - $payment = Payment::create( Payment::BOLETO_BANCARIO, new \DateTime(), 17.5 ); + $item = Item::create(1, 'Adaptador USB', 10.0, 1); + $payment = Payment::create(Payment::BOLETO_BANCARIO, new \DateTime(), 17.5); - $passenger = Passenger::create( 'Fulano da Silva', Passenger::DOCUMENT_TYPE_CPF, '63165236372' ); + $passenger = Passenger::create('Fulano da Silva', Passenger::DOCUMENT_TYPE_CPF, '63165236372'); $connection = createConnection(); // Criar Pedido @@ -72,7 +72,7 @@ ); // Enviar pedido para análise - $response = $clearSale->analysis( $order ); + $response = $clearSale->analysis($order); // Resultado da análise switch ($response) { @@ -91,10 +91,10 @@ echo 'Erro' . PHP_EOL; } - if ($clearSale->updateOrderStatus( $orderId, Analysis::UPDATE_ORDER_STATUS_ORDER_APPROVED ) === true) { + if ($clearSale->updateOrderStatus($orderId, Analysis::UPDATE_ORDER_STATUS_ORDER_APPROVED) === true) { echo 'Status do pedido atualizado'; } -} catch ( Exception $e ) { +} catch (Exception $e) { echo 'ERRO', PHP_EOL, PHP_EOL; // Erro genérico da análise @@ -103,22 +103,22 @@ function createOrderId() { - return sprintf( 'TEST-%s', createSessionId() ); + return \sprintf('TEST-%s', createSessionId()); } function createSessionId() { - return md5( uniqid( rand(), true ) ); + return \md5(\uniqid(\rand(), true)); } function createCustomerBillingData() { - $id = '1'; + $id = '1'; $legalDocument = '63165236372'; - $name = 'Fulano da Silva'; - $address = createAddress(); - $phone = Phone::create( Phone::COMERCIAL, '11', '37288788' ); - $birthDate = new \DateTime( '1980-01-01' ); + $name = 'Fulano da Silva'; + $address = createAddress(); + $phone = Phone::create(Phone::COMERCIAL, '11', '37288788'); + $birthDate = new \DateTime('1980-01-01'); return CustomerBillingData::create( $id, @@ -133,11 +133,11 @@ function createCustomerBillingData() function createCustomerShippingData() { - $id = '1'; + $id = '1'; $legalDocument = '63165236372'; - $name = 'Fulano da Silva'; - $address = createAddress(); - $phone = Phone::create( Phone::COMERCIAL, '11', '37288788' ); + $name = 'Fulano da Silva'; + $address = createAddress(); + $phone = Phone::create(Phone::COMERCIAL, '11', '37288788'); return CustomerShippingData::create( $id, @@ -151,27 +151,27 @@ function createCustomerShippingData() function createAddress() { - $street = 'Rua José de Oliveira Coutinho'; - $number = 151; - $county = 'Barra Funda'; + $street = 'Rua José de Oliveira Coutinho'; + $number = 151; + $county = 'Barra Funda'; $country = 'Brasil'; - $city = 'São Paulo'; - $state = 'SP'; - $zip = '01144020'; + $city = 'São Paulo'; + $state = 'SP'; + $zip = '01144020'; - return Address::create( $street, $number, $county, $country, $city, $state, $zip ); + return Address::create($street, $number, $county, $country, $city, $state, $zip); } function createConnection() { - $company = 'TAM'; - $flightNumber = '3356'; - $flightDate = new \DateTime( '2015-09-14 11:55:00' ); - $class = 'Econômica'; - $from = 'GRU'; - $to = 'JPA'; - $departureDate = new \DateTime( '2015-09-14 11:55:00' ); - $arrivalDate = new \DateTime( '2015-09-14 15:33:00' ); + $company = 'TAM'; + $flightNumber = '3356'; + $flightDate = new \DateTime('2015-09-14 11:55:00'); + $class = 'Econômica'; + $from = 'GRU'; + $to = 'JPA'; + $departureDate = new \DateTime('2015-09-14 11:55:00'); + $arrivalDate = new \DateTime('2015-09-14 15:33:00'); return Connection::create( $company, diff --git a/examples/ecommerce-order-example.php b/examples/ecommerce-order-example.php index bfb3832..c2b5a47 100644 --- a/examples/ecommerce-order-example.php +++ b/examples/ecommerce-order-example.php @@ -1,51 +1,51 @@ '; // ambiente - $environment = new Sandbox( $entityCode, new ExampleLogger ); - $environment->setDebug( true ); + $environment = new Sandbox($entityCode, new ExampleLogger()); + $environment->setDebug(true); // serviços - $connector = new Connector( $environment ); - $integration = new Integration( $connector ); - $clearSale = new Analysis( $integration ); + $connector = new Connector($environment); + $integration = new Integration($connector); + $clearSale = new Analysis($integration); // Dados do Pedido - $fingerPrint = new FingerPrint( createSessionId() ); - $orderId = createOrderId(); - $date = new \DateTime(); - $email = 'cliente@clearsale.com.br'; - $totalItems = 10.0; - $totalOrder = 17.5; + $fingerPrint = new FingerPrint(createSessionId()); + $orderId = createOrderId(); + $date = new \DateTime(); + $email = 'cliente@clearsale.com.br'; + $totalItems = 10.0; + $totalOrder = 17.5; $quantityInstallments = 1; - $ip = '127.0.0.1'; - $origin = 'WEB'; - $customerBillingData = createCustomerBillingData(); + $ip = '127.0.0.1'; + $origin = 'WEB'; + $customerBillingData = createCustomerBillingData(); $customerShippingData = createCustomerShippingData(); - $item = Item::create( 1, 'Adaptador USB', 10.0, 1 ); - $payment = Payment::create( Payment::BOLETO_BANCARIO, new \DateTime(), 17.5 ); + $item = Item::create(1, 'Adaptador USB', 10.0, 1); + $payment = Payment::create(Payment::BOLETO_BANCARIO, new \DateTime(), 17.5); // Criar Pedido $order = Order::createEcommerceOrder( @@ -64,7 +64,7 @@ $item ); - $response = $clearSale->analysis( $order ); + $response = $clearSale->analysis($order); // Resultado da análise switch ($response) { @@ -83,10 +83,10 @@ echo 'Erro' . PHP_EOL; } - if ($clearSale->updateOrderStatus( $orderId, Analysis::UPDATE_ORDER_STATUS_ORDER_APPROVED ) === true) { + if ($clearSale->updateOrderStatus($orderId, Analysis::UPDATE_ORDER_STATUS_ORDER_APPROVED) === true) { echo 'Status do pedido atualizado'; } -} catch ( Exception $e ) { +} catch (Exception $e) { echo 'ERRO', PHP_EOL, PHP_EOL; // Erro genérico da análise @@ -95,22 +95,22 @@ function createOrderId() { - return sprintf( 'TEST-%s', createSessionId() ); + return \sprintf('TEST-%s', createSessionId()); } function createSessionId() { - return md5( uniqid( rand(), true ) ); + return \md5(\uniqid(\rand(), true)); } function createCustomerBillingData() { - $id = '1'; + $id = '1'; $legalDocument = '63165236372'; - $name = 'Fulano da Silva'; - $address = createAddress(); - $phone = Phone::create( Phone::COMERCIAL, '11', '37288788' ); - $birthDate = new \DateTime( '1980-01-01' ); + $name = 'Fulano da Silva'; + $address = createAddress(); + $phone = Phone::create(Phone::COMERCIAL, '11', '37288788'); + $birthDate = new \DateTime('1980-01-01'); return CustomerBillingData::create( $id, @@ -125,11 +125,11 @@ function createCustomerBillingData() function createCustomerShippingData() { - $id = '1'; + $id = '1'; $legalDocument = '63165236372'; - $name = 'Fulano da Silva'; - $address = createAddress(); - $phone = Phone::create( Phone::COMERCIAL, '11', '37288788' ); + $name = 'Fulano da Silva'; + $address = createAddress(); + $phone = Phone::create(Phone::COMERCIAL, '11', '37288788'); return CustomerShippingData::create( $id, @@ -143,15 +143,15 @@ function createCustomerShippingData() function createAddress() { - $street = 'Rua José de Oliveira Coutinho'; - $number = 151; - $county = 'Barra Funda'; + $street = 'Rua José de Oliveira Coutinho'; + $number = 151; + $county = 'Barra Funda'; $country = 'Brasil'; - $city = 'São Paulo'; - $state = 'SP'; - $zip = '01144020'; + $city = 'São Paulo'; + $state = 'SP'; + $zip = '01144020'; - return Address::create( $street, $number, $county, $country, $city, $state, $zip ); + return Address::create($street, $number, $county, $country, $city, $state, $zip); } exit; diff --git a/examples/logger.php b/examples/logger.php index e858425..f70c10b 100644 --- a/examples/logger.php +++ b/examples/logger.php @@ -4,43 +4,43 @@ class ExampleLogger implements LoggerInterface { - public function emergency( $message, array $context = [] ) + public function emergency($message, array $context = []) { } - public function alert( $message, array $context = [] ) + public function alert($message, array $context = []) { } - public function critical( $message, array $context = [] ) + public function critical($message, array $context = []) { } - public function error( $message, array $context = [] ) + public function error($message, array $context = []) { } - public function warning( $message, array $context = [] ) + public function warning($message, array $context = []) { } - public function notice( $message, array $context = [] ) + public function notice($message, array $context = []) { } - public function info( $message, array $context = [] ) + public function info($message, array $context = []) { } - public function debug( $message, array $context = [] ) + public function debug($message, array $context = []) { echo 'DEBUG:', $message, PHP_EOL; - print_r( $context ); + \print_r($context); echo PHP_EOL, PHP_EOL, PHP_EOL; } - public function log( $level, $message, array $context = [] ) + public function log($level, $message, array $context = []) { } } diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..f8d8c2d --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,32 @@ + + + + + + tests + + + + + + src + + tests/ + + + + + + + + + \ No newline at end of file diff --git a/src/ClearSaleID/Entity/Request/AbstractCustomer.php b/src/ClearSaleID/Entity/Request/AbstractCustomer.php index 367d076..ebf6edb 100644 --- a/src/ClearSaleID/Entity/Request/AbstractCustomer.php +++ b/src/ClearSaleID/Entity/Request/AbstractCustomer.php @@ -2,23 +2,22 @@ namespace RodrigoPedra\ClearSaleID\Entity\Request; -use DateTime; -use InvalidArgumentException; use RodrigoPedra\ClearSaleID\Entity\XmlEntityInterface; use RodrigoPedra\ClearSaleID\Exception\RequiredFieldException; -use XMLWriter; abstract class AbstractCustomer implements XmlEntityInterface { - const TYPE_PESSOA_FISICA = 1; - const TYPE_PESSOA_JURIDICA = 2; - const SEX_MASCULINE = 'M'; - const SEX_FEMININE = 'F'; + public const TYPE_PESSOA_FISICA = 1; + public const TYPE_PESSOA_JURIDICA = 2; + public const SEX_MASCULINE = 'M'; + public const SEX_FEMININE = 'F'; + protected static $customerTypes = [ self::TYPE_PESSOA_FISICA, self::TYPE_PESSOA_JURIDICA, ]; - protected static $sexTypes = [ + + protected static $sexTypes = [ self::SEX_MASCULINE, self::SEX_FEMININE, ]; @@ -32,45 +31,72 @@ abstract class AbstractCustomer implements XmlEntityInterface /** @var string */ protected $legalDocument1; - /** @var string */ - protected $legalDocument2; + /** @var string|null */ + protected $legalDocument2 = null; /** @var string */ protected $name; - /** @var string */ - protected $email; + /** @var string|null */ + protected $email = null; - /** @var string */ - protected $sex; + /** @var string|null */ + protected $sex = null; - /** @var \DateTime */ - protected $birthDate; + /** @var \DateTimeInterface|null */ + protected $birthDate = null; /** @var \RodrigoPedra\ClearSaleID\Entity\Request\Address */ protected $address; /** @var \RodrigoPedra\ClearSaleID\Entity\Request\Phone[] */ - protected $phones; + protected $phones = []; + + public function __construct( + string $id, + string $type, + string $legalDocument, + string $name, + Address $address, + Phone $phone + ) { + $this->setId($id); + $this->setType($type); + $this->setLegalDocument1($legalDocument); + $this->setName($name); + $this->setAddress($address); + $this->addPhone($phone); + } - /** - * @return string - */ - public function getId() + public static function create( + string $id, + string $type, + string $legalDocument, + string $name, + Address $address, + Phone $phone, + ?\DateTimeInterface $birthDate = null + ): self { + $instance = new static($id, $type, $legalDocument, $name, $address, $phone); + + if ($birthDate) { + $instance->setBirthDate($birthDate); + } + + return $instance; + } + + public function getId(): string { return $this->id; } - /** - * @param string $id - * - * @return $this - * @throws \InvalidArgumentException - */ - public function setId( $id ) + public function setId(string $id): self { - if (empty( $id )) { - throw new InvalidArgumentException( 'The id value is empty!' ); + $id = \trim($id); + + if (\strlen($id) === 0) { + throw new RequiredFieldException('Customer ID is required'); } $this->id = $id; @@ -78,24 +104,15 @@ public function setId( $id ) return $this; } - /** - * @return string - */ - public function getType() + public function getType(): int { return $this->type; } - /** - * @param int $type - * - * @return $this - * @throws \InvalidArgumentException - */ - public function setType( $type ) + public function setType(int $type): self { - if (!in_array( $type, self::$customerTypes )) { - throw new InvalidArgumentException( sprintf( 'Invalid type (%s)', $type ) ); + if (! \in_array($type, self::$customerTypes)) { + throw new \InvalidArgumentException(\sprintf('Invalid type (%s)', $type)); } $this->type = $type; @@ -103,26 +120,17 @@ public function setType( $type ) return $this; } - /** - * @return string - */ - public function getLegalDocument1() + public function getLegalDocument1(): string { return $this->legalDocument1; } - /** - * @param string $legalDocument1 - * - * @return $this - * @throws \InvalidArgumentException - */ - public function setLegalDocument1( $legalDocument1 ) + public function setLegalDocument1(string $legalDocument1): self { - $legalDocument1 = preg_replace( '/\D/', '', $legalDocument1 ); + $legalDocument1 = \preg_replace('/\D/', '', $legalDocument1); - if (empty( $legalDocument1 )) { - throw new InvalidArgumentException( 'LegalDocument1 is empty!' ); + if (\strlen($legalDocument1) === 0) { + throw new RequiredFieldException('Legal Document is required'); } $this->legalDocument1 = $legalDocument1; @@ -130,51 +138,29 @@ public function setLegalDocument1( $legalDocument1 ) return $this; } - /** - * @return string - */ - public function getLegalDocument2() + public function getLegalDocument2(): ?string { return $this->legalDocument2; } - /** - * @param string $legalDocument2 - * - * @return $this - * @throws \InvalidArgumentException - */ - public function setLegalDocument2( $legalDocument2 ) + public function setLegalDocument2(string $legalDocument2): self { - $legalDocument2 = preg_replace( '/\D/', '', $legalDocument2 ); - - if (empty( $legalDocument2 )) { - throw new InvalidArgumentException( 'LegalDocument2 is empty!' ); - } - - $this->legalDocument2 = $legalDocument2; + $this->legalDocument2 = \preg_replace('/\D/', '', $legalDocument2) ?: null; return $this; } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * @param string $name - * - * @return $this - * @throws \InvalidArgumentException - */ - public function setName( $name ) + public function setName(string $name): self { - if (empty( $name )) { - throw new InvalidArgumentException( 'Name is empty!' ); + $name = \trim($name); + + if (\strlen($name) === 0) { + throw new RequiredFieldException('Name is required'); } $this->name = $name; @@ -182,44 +168,27 @@ public function setName( $name ) return $this; } - /** - * @return string - */ - public function getEmail() + public function getEmail(): ?string { return $this->email; } - /** - * @param string $email - * - * @return $this - */ - public function setEmail( $email ) + public function setEmail(string $email): self { - $this->email = $email; + $this->email = \trim($email) ?: null; return $this; } - /** - * @return string - */ - public function getSex() + public function getSex(): ?string { return $this->sex; } - /** - * @param string $sex - * - * @return $this - * @throws \InvalidArgumentException - */ - public function setSex( $sex ) + public function setSex(string $sex): self { - if (!in_array( $sex, self::$sexTypes )) { - throw new InvalidArgumentException( sprintf( 'Invalid sex (%s)', $sex ) ); + if (! \in_array($sex, self::$sexTypes)) { + throw new \InvalidArgumentException(\sprintf('Invalid sex (%s)', $sex)); } $this->sex = $sex; @@ -227,40 +196,24 @@ public function setSex( $sex ) return $this; } - /** - * @return \DateTime - */ - public function getBirthDate() + public function getBirthDate(): ?\DateTimeInterface { return $this->birthDate; } - /** - * @param \DateTime $birthDate - * - * @return $this - */ - public function setBirthDate( DateTime $birthDate ) + public function setBirthDate(\DateTimeInterface $birthDate): self { $this->birthDate = $birthDate; return $this; } - /** - * @return \RodrigoPedra\ClearSaleID\Entity\Request\Address - */ - public function getAddress() + public function getAddress(): Address { return $this->address; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Address $address - * - * @return $this - */ - public function setAddress( Address $address ) + public function setAddress(Address $address): self { $this->address = $address; @@ -270,102 +223,75 @@ public function setAddress( Address $address ) /** * @return \RodrigoPedra\ClearSaleID\Entity\Request\Phone[] */ - public function getPhones() + public function getPhones(): array { return $this->phones; } /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Phone|\RodrigoPedra\ClearSaleID\Entity\Request\Phone[] $phones - * - * @return $this + * @param \RodrigoPedra\ClearSaleID\Entity\Request\Phone|\RodrigoPedra\ClearSaleID\Entity\Request\Phone[] $phones + * @return self */ - public function setPhones( $phones ) + public function setPhones($phones): self { - $phones = is_array( $phones ) ? $phones : [ $phones ]; + $phones = \is_iterable($phones) ? $phones : [$phones]; foreach ($phones as $phone) { - $this->addPhone( $phone ); + $this->addPhone($phone); + } + + if (\count($this->phones) === 0) { + throw new RequiredFieldException('Customer object requires at least one Phone'); } return $this; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Phone $phone - * - * @return $this - */ - public function addPhone( Phone $phone ) + public function addPhone(Phone $phone): self { $this->phones[] = $phone; return $this; } - /** - * @param \XMLWriter $XMLWriter - * - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - public function toXML( XMLWriter $XMLWriter ) - { - if ($this->id) { - $XMLWriter->writeElement( 'UsuarioID', $this->id ); - } else { - throw new RequiredFieldException( 'Field ID of the Customer object is required' ); - } + abstract protected function getXMLWrapperElement(): string; - if ($this->type) { - $XMLWriter->writeElement( 'TipoUsuario', $this->type ); - } else { - throw new RequiredFieldException( 'Field Type of the Customer object is required' ); - } + public function toXML(\XMLWriter $XMLWriter): void + { + $XMLWriter->startElement($this->getXMLWrapperElement()); - if ($this->legalDocument1) { - $XMLWriter->writeElement( 'DocumentoLegal1', $this->legalDocument1 ); - } else { - throw new RequiredFieldException( 'Field LegalDocument1 of the Customer object is required' ); - } + $XMLWriter->writeElement('UsuarioID', $this->id); + $XMLWriter->writeElement('TipoUsuario', $this->type); + $XMLWriter->writeElement('DocumentoLegal1', $this->legalDocument1); if ($this->legalDocument2) { - $XMLWriter->writeElement( 'DocumentoLegal2', $this->legalDocument2 ); + $XMLWriter->writeElement('DocumentoLegal2', $this->legalDocument2); } - if ($this->name) { - $XMLWriter->writeElement( 'Nome', $this->name ); - } else { - throw new RequiredFieldException( 'Field name of the Customer object is required' ); - } + $XMLWriter->writeElement('Nome', $this->name); if ($this->email) { - $XMLWriter->writeElement( 'Email', $this->email ); + $XMLWriter->writeElement('Email', $this->email); } if ($this->sex) { - $XMLWriter->writeElement( 'Sexo', $this->sex ); + $XMLWriter->writeElement('Sexo', $this->sex); } if ($this->birthDate) { - $XMLWriter->writeElement( 'Nascimento', $this->birthDate->format( self::DATE_TIME_FORMAT ) ); + $XMLWriter->writeElement('Nascimento', $this->birthDate->format(self::DATE_TIME_FORMAT)); } - if ($this->address) { - $this->address->toXML( $XMLWriter ); - } else { - throw new RequiredFieldException( 'Field Address of the Customer object is required' ); - } - - if ($this->phones && count( $this->phones ) > 0) { - $XMLWriter->startElement( 'Telefones' ); + $this->address->toXML($XMLWriter); - foreach ($this->phones as $phone) { - $phone->toXML( $XMLWriter ); - } + $XMLWriter->startElement('Telefones'); - $XMLWriter->endElement(); - } else { - throw new RequiredFieldException( 'Field Phones of the Customer object is required' ); + foreach ($this->phones as $phone) { + $phone->toXML($XMLWriter); } + + $XMLWriter->endElement(); // Telefones + + $XMLWriter->endElement(); // $this->getXMLWrapperElement() } } diff --git a/src/ClearSaleID/Entity/Request/Address.php b/src/ClearSaleID/Entity/Request/Address.php index ffcc279..e193272 100755 --- a/src/ClearSaleID/Entity/Request/Address.php +++ b/src/ClearSaleID/Entity/Request/Address.php @@ -2,21 +2,19 @@ namespace RodrigoPedra\ClearSaleID\Entity\Request; -use InvalidArgumentException; use RodrigoPedra\ClearSaleID\Entity\XmlEntityInterface; use RodrigoPedra\ClearSaleID\Exception\RequiredFieldException; -use XMLWriter; class Address implements XmlEntityInterface { /** @var string */ private $street; - /** @var string */ - private $number; + /** @var string|null */ + private $complement = null; /** @var string */ - private $complement; + private $number; /** @var string */ private $county; @@ -28,59 +26,67 @@ class Address implements XmlEntityInterface private $state; /** @var string */ - private $country; + private $zipCode; /** @var string */ - private $zipCode; + private $country; - /** - * @param string $street - * @param string $number - * @param string $county - * @param string $country - * @param string $city - * @param string $state - * @param string $zipCode - * @param string $complement - * - * @return \RodrigoPedra\ClearSaleID\Entity\Request\Address - */ - public static function create( $street, $number, $county, $country, $city, $state, $zipCode, $complement = '' ) - { - $instance = new self; - - $instance->setStreet( $street ); - $instance->setNumber( $number ); - $instance->setCounty( $county ); - $instance->setCountry( $country ); - $instance->setCity( $city ); - $instance->setState( $state ); - $instance->setZipCode( $zipCode ); - - if (!empty( $complement )) { - $instance->setComplement( $complement ); + public function __construct( + string $street, + string $number, + string $county, + string $city, + string $state, + string $zipCode, + string $country + ) { + $this->setStreet($street); + $this->setNumber($number); + $this->setCounty($county); + $this->setCity($city); + $this->setState($state); + $this->setZipCode($zipCode); + $this->setCountry($country); + } + + public static function create( + string $street, + string $number, + string $county, + string $country, + string $city, + string $state, + string $zipCode, + ?string $complement = null + ): self { + $instance = new self( + $street, + $number, + $county, + $city, + $state, + $zipCode, + $country + ); + + if ($complement) { + $instance->setComplement($complement); } return $instance; } - /** - * @return string - */ - public function getStreet() + public function getStreet(): string { return $this->street; } - /** - * @param string $street - * - * @return $this - */ - public function setStreet( $street ) + public function setStreet(string $street): self { - if (empty( $street )) { - throw new InvalidArgumentException( 'Street is empty!' ); + $street = \trim($street); + + if (\strlen($street) === 0) { + throw new RequiredFieldException('Street is required'); } $this->street = $street; @@ -88,67 +94,47 @@ public function setStreet( $street ) return $this; } - /** - * @return string - */ - public function getNumber() + public function getNumber(): string { return $this->number; } - /** - * @param string $number - * - * @return $this - */ - public function setNumber( $number ) + public function setNumber(string $number): self { - if (empty( $number )) { - throw new InvalidArgumentException( 'Number is empty!' ); + $number = \trim($number); + + if (\strlen($number) === 0) { + throw new RequiredFieldException('Number is required'); } - $this->number = (string)$number; + $this->number = $number; return $this; } - /** - * @return string - */ - public function getComplement() + public function getComplement(): ?string { return $this->complement; } - /** - * @param string $complement - * - * @return $this - */ - public function setComplement( $complement ) + public function setComplement(string $complement): self { - $this->complement = $complement; + $this->complement = \trim($complement) ?: null; return $this; } - /** - * @return string - */ - public function getCounty() + public function getCounty(): string { return $this->county; } - /** - * @param string $county - * - * @return $this - */ - public function setCounty( $county ) + public function setCounty(string $county): self { - if (empty( $county )) { - throw new InvalidArgumentException( 'County is empty!' ); + $county = \trim($county); + + if (\strlen($county) === 0) { + throw new RequiredFieldException('County is required'); } $this->county = $county; @@ -156,23 +142,17 @@ public function setCounty( $county ) return $this; } - /** - * @return string - */ - public function getCity() + public function getCity(): string { return $this->city; } - /** - * @param string $city - * - * @return $this - */ - public function setCity( $city ) + public function setCity(string $city): self { - if (empty( $city )) { - throw new InvalidArgumentException( 'City is empty!' ); + $city = \trim($city); + + if (\strlen($city) === 0) { + throw new RequiredFieldException('City is required'); } $this->city = $city; @@ -180,23 +160,17 @@ public function setCity( $city ) return $this; } - /** - * @return string - */ - public function getState() + public function getState(): string { return $this->state; } - /** - * @param string $state - * - * @return $this - */ - public function setState( $state ) + public function setState(string $state): self { - if (empty( $state )) { - throw new InvalidArgumentException( 'State is empty!' ); + $state = \trim($state); + + if (\strlen($state) === 0) { + throw new RequiredFieldException('State is required'); } $this->state = $state; @@ -204,45 +178,29 @@ public function setState( $state ) return $this; } - /** - * @return string - */ - public function getCountry() + public function getCountry(): string { return $this->country; } - /** - * @param string $country - * - * @return $this - */ - public function setCountry( $country ) + public function setCountry(string $country): self { $this->country = $country; return $this; } - /** - * @return string - */ - public function getZipCode() + public function getZipCode(): string { return $this->zipCode; } - /** - * @param string $zipCode - * - * @return $this - */ - public function setZipCode( $zipCode ) + public function setZipCode(string $zipCode): self { - $zipCode = preg_replace( '/\D/', '', $zipCode ); + $zipCode = \preg_replace('/\D/', '', $zipCode); - if (empty( $zipCode )) { - throw new InvalidArgumentException( 'ZipCode is empty!' ); + if (\strlen($zipCode) === 0) { + throw new RequiredFieldException('ZipCode is required'); } $this->zipCode = $zipCode; @@ -250,61 +208,23 @@ public function setZipCode( $zipCode ) return $this; } - /** - * @param \XMLWriter $XMLWriter - * - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - public function toXML( XMLWriter $XMLWriter ) + public function toXML(\XMLWriter $XMLWriter): void { - $XMLWriter->startElement( 'Endereco' ); + $XMLWriter->startElement('Endereco'); - if ($this->street) { - $XMLWriter->writeElement( 'Logradouro', $this->street ); - } else { - throw new RequiredFieldException( 'Field Street of the Address object is required' ); - } + $XMLWriter->writeElement('Logradouro', $this->street); if ($this->complement) { - $XMLWriter->writeElement( 'Complemento', $this->complement ); - } - - if ($this->number) { - $XMLWriter->writeElement( 'Numero', $this->number ); - } else { - throw new RequiredFieldException( 'Field Number of the Address object is required' ); - } - - if ($this->county) { - $XMLWriter->writeElement( 'Bairro', $this->county ); - } else { - throw new RequiredFieldException( 'Field County of the Address object is required' ); - } - - if ($this->city) { - $XMLWriter->writeElement( 'Cidade', $this->city ); - } else { - throw new RequiredFieldException( 'Field City of the Address object is required' ); - } - - if ($this->state) { - $XMLWriter->writeElement( 'UF', $this->state ); - } else { - throw new RequiredFieldException( 'Field State of the Address object is required' ); + $XMLWriter->writeElement('Complemento', $this->complement); } - if ($this->zipCode) { - $XMLWriter->writeElement( 'CEP', $this->zipCode ); - } else { - throw new RequiredFieldException( 'Field ZipCode of the Address object is required' ); - } - - if ($this->country) { - $XMLWriter->writeElement( 'Pais', $this->country ); - } else { - throw new RequiredFieldException( 'Field Country of the Address object is required' ); - } + $XMLWriter->writeElement('Numero', $this->number); + $XMLWriter->writeElement('Bairro', $this->county); + $XMLWriter->writeElement('Cidade', $this->city); + $XMLWriter->writeElement('UF', $this->state); + $XMLWriter->writeElement('CEP', $this->zipCode); + $XMLWriter->writeElement('Pais', $this->country); - $XMLWriter->endElement(); + $XMLWriter->endElement(); // Endereco } } diff --git a/src/ClearSaleID/Entity/Request/Card.php b/src/ClearSaleID/Entity/Request/Card.php index 842249b..1a207fd 100755 --- a/src/ClearSaleID/Entity/Request/Card.php +++ b/src/ClearSaleID/Entity/Request/Card.php @@ -2,21 +2,19 @@ namespace RodrigoPedra\ClearSaleID\Entity\Request; -use InvalidArgumentException; use RodrigoPedra\ClearSaleID\Entity\XmlEntityInterface; -use XMLWriter; class Card implements XmlEntityInterface { - const DINERS = 1; - const MASTERCARD = 2; - const VISA = 3; - const OUTROS = 4; - const AMERICAN_EXPRESS = 5; - const HIPERCARD = 6; - const AURA = 7; - - private static $cards = [ + public const DINERS = 1; + public const MASTERCARD = 2; + public const VISA = 3; + public const OUTROS = 4; + public const AMERICAN_EXPRESS = 5; + public const HIPERCARD = 6; + public const AURA = 7; + + private static $cardTypes = [ self::DINERS, self::MASTERCARD, self::VISA, @@ -26,71 +24,62 @@ class Card implements XmlEntityInterface self::AURA, ]; - /** @var string */ - private $numberHash; + /** @var string|null */ + private $numberHash = null; - /** @var string */ - private $bin; + /** @var string|null */ + private $bin = null; - /** @var string */ - private $lastDigits; + /** @var string|null */ + private $lastDigits = null; - /** @var string */ - private $type; + /** @var string|null */ + private $type = null; - /** @var string */ - private $expirationDate; + /** @var string|null */ + private $expirationDate = null; - /** @var string */ - private $name; + /** @var string|null */ + private $name = null; - /** - * @return string - */ - public function getNumberHash() + public static function create(): self + { + return new self(); + } + + public function getNumberHash(): ?string { return $this->numberHash; } - /** - * @param string $numberHash - * - * @return $this - */ - public function setNumberHash( $numberHash ) + public function setNumberHash(string $numberHash): self { - $numberHash = trim( $numberHash ); + $numberHash = \trim($numberHash); - if (strlen( $numberHash ) > 40) { - throw new InvalidArgumentException( sprintf( 'Card number hash should be no longer than 40 characters (%s)', - $numberHash ) ); + if (\strlen($numberHash) > 40) { + throw new \InvalidArgumentException( + \sprintf('Card number hash should be no longer than 40 characters (%s)', $numberHash) + ); } - $this->numberHash = $numberHash; + $this->numberHash = $numberHash ?: null; return $this; } - /** - * @return string - */ - public function getBin() + public function getBin(): ?string { return $this->bin; } - /** - * @param string $bin - * - * @return $this - */ - public function setBin( $bin ) + public function setBin(string $bin): self { - $bin = trim( $bin ); + $bin = \trim($bin); - if (strlen( $bin ) !== 6) { - throw new InvalidArgumentException( sprintf( 'Bin number should contain the first 6 characters in the card number (%s)', - $bin ) ); + if (\strlen($bin) !== 6) { + throw new \InvalidArgumentException( + \sprintf('Bin number should contain the first 6 characters in the card number (%s)', $bin) + ); } $this->bin = $bin; @@ -98,26 +87,19 @@ public function setBin( $bin ) return $this; } - /** - * @return string - */ - public function getLastDigits() + public function getLastDigits(): ?string { return $this->lastDigits; } - /** - * @param string $lastDigits - * - * @return $this - */ - public function setLastDigits( $lastDigits ) + public function setLastDigits(string $lastDigits): self { - $lastDigits = trim( $lastDigits ); + $lastDigits = \trim($lastDigits); - if (strlen( $lastDigits ) !== 4) { - throw new InvalidArgumentException( sprintf( 'Last digits should contain the last 4 characters in the card number (%s)', - $lastDigits ) ); + if (\strlen($lastDigits) !== 4) { + throw new \InvalidArgumentException( + \sprintf('Last digits should contain the last 4 characters in the card number (%s)', $lastDigits) + ); } $this->lastDigits = $lastDigits; @@ -125,23 +107,15 @@ public function setLastDigits( $lastDigits ) return $this; } - /** - * @return string - */ - public function getType() + public function getType(): ?string { return $this->type; } - /** - * @param string $type - * - * @return $this - */ - public function setType( $type ) + public function setType(int $type): self { - if (!in_array( $type, self::$cards )) { - throw new InvalidArgumentException( sprintf( 'Invalid type (%s)', $type ) ); + if (! \in_array($type, self::$cardTypes)) { + throw new \InvalidArgumentException(\sprintf('Invalid type (%s)', $type)); } $this->type = $type; @@ -149,73 +123,54 @@ public function setType( $type ) return $this; } - /** - * @return string - */ - public function getExpirationDate() + public function getExpirationDate(): ?string { return $this->expirationDate; } - /** - * @param string $expirationDate - * - * @return $this - */ - public function setExpirationDate( $expirationDate ) + public function setExpirationDate(string $expirationDate): self { - $this->expirationDate = $expirationDate; + $this->expirationDate = \trim($expirationDate) ?: null; return $this; } - /** - * @return string - */ - public function getName() + public function getName(): ?string { return $this->name; } - /** - * @param string $name - * - * @return $this - */ - public function setName( $name ) + public function setName(string $name): self { - $this->name = $name; + $this->name = \trim($name) ?: null; return $this; } - /** - * @param \XMLWriter $XMLWriter - */ - public function toXML( XMLWriter $XMLWriter ) + public function toXML(\XMLWriter $XMLWriter): void { if ($this->numberHash) { - $XMLWriter->writeElement( 'HashNumeroCartao', $this->numberHash ); + $XMLWriter->writeElement('HashNumeroCartao', $this->numberHash); } if ($this->bin) { - $XMLWriter->writeElement( 'BinCartao', $this->bin ); + $XMLWriter->writeElement('BinCartao', $this->bin); } if ($this->lastDigits) { - $XMLWriter->writeElement( 'Cartao4Ultimos', $this->lastDigits ); + $XMLWriter->writeElement('Cartao4Ultimos', $this->lastDigits); } if ($this->type) { - $XMLWriter->writeElement( 'TipoCartao', $this->type ); + $XMLWriter->writeElement('TipoCartao', $this->type); } if ($this->expirationDate) { - $XMLWriter->writeElement( 'DataValidadeCartao', $this->expirationDate ); + $XMLWriter->writeElement('DataValidadeCartao', $this->expirationDate); } if ($this->name) { - $XMLWriter->writeElement( 'NomeTitularCartao', $this->name ); + $XMLWriter->writeElement('NomeTitularCartao', $this->name); } } } diff --git a/src/ClearSaleID/Entity/Request/Connection.php b/src/ClearSaleID/Entity/Request/Connection.php index 436dd70..9db3df6 100644 --- a/src/ClearSaleID/Entity/Request/Connection.php +++ b/src/ClearSaleID/Entity/Request/Connection.php @@ -2,10 +2,8 @@ namespace RodrigoPedra\ClearSaleID\Entity\Request; -use DateTime; use RodrigoPedra\ClearSaleID\Entity\XmlEntityInterface; use RodrigoPedra\ClearSaleID\Exception\RequiredFieldException; -use XMLWriter; class Connection implements XmlEntityInterface { @@ -15,7 +13,7 @@ class Connection implements XmlEntityInterface /** @var string */ private $flightNumber; - /** @var \DateTime */ + /** @var \DateTimeInterface */ private $flightDate; /** @var string */ @@ -27,265 +25,184 @@ class Connection implements XmlEntityInterface /** @var string */ private $to; - /** @var \DateTime */ + /** @var \DateTimeInterface */ private $departureDate; - /** @var \DateTime */ + /** @var \DateTimeInterface */ private $arrivalDate; - /** - * @param string $company - * @param string $flightNumber - * @param \DateTime $flightDate - * @param string $class - * @param string $from - * @param string $to - * @param \DateTime $departureDate - * @param \DateTime $arrivalDate - * - * @return \RodrigoPedra\ClearSaleID\Entity\Request\Connection - */ - public static function create( - $company, - $flightNumber, - DateTime $flightDate, - $class, - $from, - $to, - DateTime $departureDate, - DateTime $arrivalDate + public function __construct( + string $company, + string $flightNumber, + \DateTimeInterface $flightDate, + string $class, + string $from, + string $to, + \DateTimeInterface $departureDate, + \DateTimeInterface $arrivalDate ) { - $instance = new self; - - $instance->setCompany( $company ); - $instance->setFlightNumber( $flightNumber ); - $instance->setFlightDate( $flightDate ); - $instance->setClass( $class ); - $instance->setFrom( $from ); - $instance->setTo( $to ); - $instance->setDepartureDate( $departureDate ); - $instance->setArrivalDate( $arrivalDate ); - - return $instance; + $this->setCompany($company); + $this->setFlightNumber($flightNumber); + $this->setFlightDate($flightDate); + $this->setClass($class); + $this->setFrom($from); + $this->setTo($to); + $this->setDepartureDate($departureDate); + $this->setArrivalDate($arrivalDate); } - /** - * @return string - */ - public function getCompany() + public static function create( + string $company, + string $flightNumber, + \DateTimeInterface $flightDate, + string $class, + string $from, + string $to, + \DateTimeInterface $departureDate, + \DateTimeInterface $arrivalDate + ): self { + return new self($company, $flightNumber, $flightDate, $class, $from, $to, $departureDate, $arrivalDate); + } + + public function getCompany(): string { return $this->company; } - /** - * @param string $company - * - * @return $this - */ - public function setCompany( $company ) + public function setCompany(string $company): self { + $company = \trim($company); + + if (\strlen($company) === 0) { + throw new RequiredFieldException('Company is required'); + } + $this->company = $company; return $this; } - /** - * @return string - */ - public function getFlightNumber() + public function getFlightNumber(): string { return $this->flightNumber; } - /** - * @param string $flightNumber - * - * @return $this - */ - public function setFlightNumber( $flightNumber ) + public function setFlightNumber(string $flightNumber): self { + $flightNumber = \trim($flightNumber); + + if (\strlen($flightNumber) === 0) { + throw new RequiredFieldException('Flight Number is required'); + } + $this->flightNumber = $flightNumber; return $this; } - /** - * @return \DateTime - */ - public function getFlightDate() + public function getFlightDate(): \DateTimeInterface { return $this->flightDate; } - /** - * @param \DateTime $flightDate - * - * @return $this - */ - public function setFlightDate( DateTime $flightDate ) + public function setFlightDate(\DateTimeInterface $flightDate): self { $this->flightDate = $flightDate; return $this; } - /** - * @return string - */ - public function getClass() + public function getClass(): string { return $this->class; } - /** - * @param string $class - * - * @return $this - */ - public function setClass( $class ) + public function setClass(string $class): self { + $class = \trim($class); + + if (\strlen($class) === 0) { + throw new RequiredFieldException('Class is required'); + } + $this->class = $class; return $this; } - /** - * @return string - */ - public function getFrom() + public function getFrom(): string { return $this->from; } - /** - * @param string $from - * - * @return $this - */ - public function setFrom( $from ) + public function setFrom(string $from): self { + $from = \trim($from); + + if (\strlen($from) === 0) { + throw new RequiredFieldException('From is required'); + } + $this->from = $from; return $this; } - /** - * @return string - */ - public function getTo() + public function getTo(): string { return $this->to; } - /** - * @param string $to - * - * @return $this - */ - public function setTo( $to ) + public function setTo(string $to): self { + $to = \trim($to); + + if (\strlen($to) === 0) { + throw new RequiredFieldException('To is required'); + } + $this->to = $to; return $this; } - /** - * @return \DateTime - */ - public function getDepartureDate() + public function getDepartureDate(): \DateTimeInterface { return $this->departureDate; } - /** - * @param \DateTime $departureDate - * - * @return $this - */ - public function setDepartureDate( DateTime $departureDate ) + public function setDepartureDate(\DateTimeInterface $departureDate): self { $this->departureDate = $departureDate; return $this; } - /** - * @return \DateTime - */ - public function getArrivalDate() + public function getArrivalDate(): \DateTimeInterface { return $this->arrivalDate; } - /** - * @param \DateTime $arrivalDate - * - * @return $this - */ - public function setArrivalDate( DateTime $arrivalDate ) + public function setArrivalDate(\DateTimeInterface $arrivalDate): self { $this->arrivalDate = $arrivalDate; return $this; } - /** - * @param \XMLWriter $XMLWriter - * - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - public function toXML( XMLWriter $XMLWriter ) + public function toXML(\XMLWriter $XMLWriter): void { - $XMLWriter->startElement( 'Conexao' ); + $XMLWriter->startElement('Conexao'); - if ($this->company) { - $XMLWriter->writeElement( 'Companhia', $this->company ); - } else { - throw new RequiredFieldException( 'Field Company of the Connection object is required' ); - } - - if ($this->flightNumber) { - $XMLWriter->writeElement( 'NumeroVoo', $this->flightNumber ); - } else { - throw new RequiredFieldException( 'Field FlightNumber of the Connection object is required' ); - } - - if ($this->flightDate) { - $XMLWriter->writeElement( 'DataVoo', $this->flightDate->format( self::DATE_TIME_FORMAT ) ); - } else { - throw new RequiredFieldException( 'Field FlightDate of the Connection object is required' ); - } - - if ($this->class) { - $XMLWriter->writeElement( 'Classe', $this->class ); - } else { - throw new RequiredFieldException( 'Field Class of the Connection object is required' ); - } - - if ($this->from) { - $XMLWriter->writeElement( 'Origem', $this->from ); - } else { - throw new RequiredFieldException( 'Field FROM of the Connection object is required' ); - } - - if ($this->to) { - $XMLWriter->writeElement( 'Destino', $this->to ); - } else { - throw new RequiredFieldException( 'Field To of the Connection object is required' ); - } - - if ($this->departureDate) { - $XMLWriter->writeElement( 'DataPartida', $this->departureDate->format( self::DATE_TIME_FORMAT ) ); - } else { - throw new RequiredFieldException( 'Field DepartureDate of the Connection object is required' ); - } - - if ($this->arrivalDate) { - $XMLWriter->writeElement( 'DataChegada', $this->arrivalDate->format( self::DATE_TIME_FORMAT ) ); - } else { - throw new RequiredFieldException( 'Field ArrivalDate of the Connection object is required' ); - } + $XMLWriter->writeElement('Companhia', $this->company); + $XMLWriter->writeElement('NumeroVoo', $this->flightNumber); + $XMLWriter->writeElement('DataVoo', $this->flightDate->format(self::DATE_TIME_FORMAT)); + $XMLWriter->writeElement('Classe', $this->class); + $XMLWriter->writeElement('Origem', $this->from); + $XMLWriter->writeElement('Destino', $this->to); + $XMLWriter->writeElement('DataPartida', $this->departureDate->format(self::DATE_TIME_FORMAT)); + $XMLWriter->writeElement('DataChegada', $this->arrivalDate->format(self::DATE_TIME_FORMAT)); - $XMLWriter->endElement(); + $XMLWriter->endElement(); // Conexao } } diff --git a/src/ClearSaleID/Entity/Request/CustomerBillingData.php b/src/ClearSaleID/Entity/Request/CustomerBillingData.php index 6e7c008..8f1f9aa 100644 --- a/src/ClearSaleID/Entity/Request/CustomerBillingData.php +++ b/src/ClearSaleID/Entity/Request/CustomerBillingData.php @@ -2,59 +2,12 @@ namespace RodrigoPedra\ClearSaleID\Entity\Request; -use DateTime; use RodrigoPedra\ClearSaleID\Entity\XmlEntityInterface; -use XMLWriter; class CustomerBillingData extends AbstractCustomer implements XmlEntityInterface { - /** - * @param string $id - * @param string $type - * @param string $legalDocument - * @param string $name - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Address $address - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Phone $phone - * @param \DateTime $birthDate - * - * @return \RodrigoPedra\ClearSaleID\Entity\Request\CustomerBillingData - */ - public static function create( - $id, - $type, - $legalDocument, - $name, - Address $address, - $phone, - DateTime $birthDate = null - ) { - $instance = new self; - - $instance->setId( $id ); - $instance->setType( $type ); - $instance->setLegalDocument1( $legalDocument ); - $instance->setName( $name ); - $instance->setAddress( $address ); - $instance->addPhone( $phone ); - - if (!empty( $birthDate )) { - $instance->setBirthDate( $birthDate ); - } - - return $instance; - } - - /** - * @param \XMLWriter $XMLWriter - * - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - public function toXML( XMLWriter $XMLWriter ) + protected function getXMLWrapperElement(): string { - $XMLWriter->startElement( 'DadosCobranca' ); - - parent::toXML( $XMLWriter ); - - $XMLWriter->endElement(); + return 'DadosCobranca'; } } diff --git a/src/ClearSaleID/Entity/Request/CustomerShippingData.php b/src/ClearSaleID/Entity/Request/CustomerShippingData.php index 06f4b4a..53e3e5f 100644 --- a/src/ClearSaleID/Entity/Request/CustomerShippingData.php +++ b/src/ClearSaleID/Entity/Request/CustomerShippingData.php @@ -2,59 +2,12 @@ namespace RodrigoPedra\ClearSaleID\Entity\Request; -use DateTime; use RodrigoPedra\ClearSaleID\Entity\XmlEntityInterface; -use XMLWriter; class CustomerShippingData extends AbstractCustomer implements XmlEntityInterface { - /** - * @param string $id - * @param string $type - * @param string $legalDocument - * @param string $name - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Address $address - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Phone $phone - * @param \DateTime|null $birthDate - * - * @return \RodrigoPedra\ClearSaleID\Entity\Request\CustomerShippingData - */ - public static function create( - $id, - $type, - $legalDocument, - $name, - Address $address, - $phone, - DateTime $birthDate = null - ) { - $instance = new self; - - $instance->setId( $id ); - $instance->setType( $type ); - $instance->setLegalDocument1( $legalDocument ); - $instance->setName( $name ); - $instance->setAddress( $address ); - $instance->addPhone( $phone ); - - if (!empty( $birthDate )) { - $instance->setBirthDate( $birthDate ); - } - - return $instance; - } - - /** - * @param \XMLWriter $XMLWriter - * - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - public function toXML( XMLWriter $XMLWriter ) + protected function getXMLWrapperElement(): string { - $XMLWriter->startElement( 'DadosEntrega' ); - - parent::toXML( $XMLWriter ); - - $XMLWriter->endElement(); + return 'DadosEntrega'; } } diff --git a/src/ClearSaleID/Entity/Request/FingerPrint.php b/src/ClearSaleID/Entity/Request/FingerPrint.php index 76389bc..d6bcdc7 100755 --- a/src/ClearSaleID/Entity/Request/FingerPrint.php +++ b/src/ClearSaleID/Entity/Request/FingerPrint.php @@ -4,54 +4,42 @@ use RodrigoPedra\ClearSaleID\Entity\XmlEntityInterface; use RodrigoPedra\ClearSaleID\Exception\RequiredFieldException; -use XMLWriter; class FingerPrint implements XmlEntityInterface { /** @var string */ private $sessionId; - /** - * FingerPrint constructor. - * - * @param string $sessionId - */ - public function __construct( $sessionId ) + public function __construct(string $sessionId) { - $this->sessionId = $sessionId; + $this->setSessionId($sessionId); + } + + public static function create(string $sessionId): self + { + return new self($sessionId); } - /** - * @return string - */ - public function getSessionId() + public function getSessionId(): string { return $this->sessionId; } - /** - * @param string $sessionId - * - * @return $this - */ - public function setSessionId( $sessionId ) + public function setSessionId(string $sessionId): self { + $sessionId = \trim($sessionId); + + if (\strlen($sessionId) === 0) { + throw new RequiredFieldException('Session ID is required'); + } + $this->sessionId = $sessionId; return $this; } - /** - * @param \XMLWriter $XMLWriter - * - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - public function toXML( XMLWriter $XMLWriter ) + public function toXML(\XMLWriter $XMLWriter): void { - if ($this->sessionId) { - $XMLWriter->writeElement( 'SessionID', $this->sessionId ); - } else { - throw new RequiredFieldException( 'Field SessionID of the FingerPrint object is required' ); - } + $XMLWriter->writeElement('SessionID', $this->sessionId); } } diff --git a/src/ClearSaleID/Entity/Request/Fixtures/AddressFixture.php b/src/ClearSaleID/Entity/Request/Fixtures/AddressFixture.php deleted file mode 100644 index 37f5010..0000000 --- a/src/ClearSaleID/Entity/Request/Fixtures/AddressFixture.php +++ /dev/null @@ -1,22 +0,0 @@ -setId( $id ); - $instance->setName( $name ); - $instance->setValue( $value ); - $instance->setQuantity( $quantity ); + public function __construct(string $id, string $name, float $value, int $quantity) + { + $this->setId($id); + $this->setName($name); + $this->setValue($value); + $this->setQuantity($quantity); + } - return $instance; + public static function create(string $id, string $name, float $value, int $quantity): self + { + return new self($id, $name, $value, $quantity); } - /** - * @return string - */ - public function getId() + public function getId(): string { return $this->id; } - /** - * @param string $id - * - * @return $this - */ - public function setId( $id ) + public function setId(string $id): self { - if (empty( $id )) { - throw new InvalidArgumentException( 'Id is empty!' ); + $id = \trim($id); + + if (\strlen($id) === 0) { + throw new RequiredFieldException('Id is required'); } $this->id = $id; @@ -76,23 +59,17 @@ public function setId( $id ) return $this; } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * @param string $name - * - * @return $this - */ - public function setName( $name ) + public function setName(string $name): self { - if (empty( $name )) { - throw new InvalidArgumentException( 'Name is empty!' ); + $name = \trim($name); + + if (\strlen($name) === 0) { + throw new RequiredFieldException('Name is required'); } $this->name = $name; @@ -100,167 +77,87 @@ public function setName( $name ) return $this; } - /** - * @return string - */ - public function getValue() + public function getValue(): float { return $this->value; } - /** - * @param string $value - * - * @return $this - */ - public function setValue( $value ) + public function setValue(float $value): self { - if (!is_float( $value )) { - throw new InvalidArgumentException( sprintf( 'Invalid value', $value ) ); - } - $this->value = $value; return $this; } - /** - * @return string - */ - public function getQuantity() + public function getQuantity(): int { return $this->quantity; } - /** - * @param string $quantity - * - * @return $this - */ - public function setQuantity( $quantity ) + public function setQuantity(int $quantity): self { - if (!is_int( $quantity )) { - throw new InvalidArgumentException( sprintf( 'Invalid quantity', $quantity ) ); - } - $this->quantity = $quantity; return $this; } - /** - * @return string - */ - public function getNotes() + public function getNotes(): ?string { return $this->notes; } - /** - * @param string $notes - * - * @return $this - */ - public function setNotes( $notes ) + public function setNotes(string $notes): self { - $this->notes = $notes; + $this->notes = \trim($notes) ?: null; return $this; } - /** - * @return string - */ - public function getCategoryId() + public function getCategoryId(): ?int { return $this->categoryId; } - /** - * @param string $categoryId - * - * @return $this - */ - public function setCategoryId( $categoryId ) + public function setCategoryId(int $categoryId): self { - if (!is_int( $categoryId )) { - throw new InvalidArgumentException( sprintf( 'Invalid categoryId', $categoryId ) ); - } - $this->categoryId = $categoryId; return $this; } - /** - * @return string - */ - public function getCategoryName() + public function getCategoryName(): ?string { return $this->categoryName; } - /** - * @param string $categoryName - * - * @return $this - */ - public function setCategoryName( $categoryName ) + public function setCategoryName(string $categoryName): self { - if (empty( $categoryName )) { - throw new InvalidArgumentException( 'Category name is empty!' ); - } - - $this->categoryName = $categoryName; + $this->categoryName = \trim($categoryName) ?: null; return $this; } - /** - * @param \XMLWriter $XMLWriter - * - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - public function toXML( XMLWriter $XMLWriter ) + public function toXML(\XMLWriter $XMLWriter): void { - $XMLWriter->startElement( 'Item' ); + $XMLWriter->startElement('Item'); - if ($this->id) { - $XMLWriter->writeElement( 'CodigoItem', $this->id ); - } else { - throw new RequiredFieldException( 'Field ID of the Item object is required' ); - } - - if ($this->name) { - $XMLWriter->writeElement( 'NomeItem', $this->name ); - } else { - throw new RequiredFieldException( 'Field Name of the Item object is required' ); - } - - if ($this->value) { - $XMLWriter->writeElement( 'ValorItem', $this->value ); - } else { - throw new RequiredFieldException( 'Field ItemValue of the Item object is required' ); - } - - if ($this->quantity) { - $XMLWriter->writeElement( 'Quantidade', $this->quantity ); - } else { - throw new RequiredFieldException( 'Field Quantity of the Item object is required' ); - } + $XMLWriter->writeElement('CodigoItem', $this->id); + $XMLWriter->writeElement('NomeItem', $this->name); + $XMLWriter->writeElement('ValorItem', $this->value); + $XMLWriter->writeElement('Quantidade', $this->quantity); if ($this->notes) { - $XMLWriter->writeElement( 'Generico', $this->notes ); + $XMLWriter->writeElement('Generico', $this->notes); } if ($this->categoryId) { - $XMLWriter->writeElement( 'CodigoCategoria', $this->categoryId ); + $XMLWriter->writeElement('CodigoCategoria', $this->categoryId); } if ($this->categoryName) { - $XMLWriter->writeElement( 'NomeCategoria', $this->categoryName ); + $XMLWriter->writeElement('NomeCategoria', $this->categoryName); } - $XMLWriter->endElement(); + $XMLWriter->endElement(); // Item } } diff --git a/src/ClearSaleID/Entity/Request/Order.php b/src/ClearSaleID/Entity/Request/Order.php index 1f0cf39..c421a8b 100755 --- a/src/ClearSaleID/Entity/Request/Order.php +++ b/src/ClearSaleID/Entity/Request/Order.php @@ -2,20 +2,17 @@ namespace RodrigoPedra\ClearSaleID\Entity\Request; -use DateTime; -use InvalidArgumentException; use RodrigoPedra\ClearSaleID\Entity\XmlEntityInterface; use RodrigoPedra\ClearSaleID\Exception\RequiredFieldException; -use XMLWriter; class Order implements XmlEntityInterface { - const ECOMMERCE_B2B = 'b2b'; - const ECOMMERCE_B2C = 'b2c'; - const STATUS_NEW = 0; - const STATUS_APPROVED = 9; - const STATUS_CANCELLED = 41; - const STATUS_REJECTED = 45; + public const ECOMMERCE_B2B = 'b2b'; + public const ECOMMERCE_B2C = 'b2c'; + public const STATUS_NEW = 0; + public const STATUS_APPROVED = 9; + public const STATUS_CANCELLED = 41; + public const STATUS_REJECTED = 45; private static $ecommerceTypes = [ self::ECOMMERCE_B2B, @@ -35,20 +32,20 @@ class Order implements XmlEntityInterface /** @var string */ private $id; - /** @var \DateTime */ + /** @var \DateTimeInterface */ private $date; - /** @var string */ - private $email; + /** @var string|null */ + private $email = null; - /** @var string */ - private $channel; + /** @var string|null */ + private $channel = null; - /** @var string */ - private $ecommerceType; + /** @var string|null */ + private $ecommerceType = null; - /** @var float */ - private $shippingValue; + /** @var float|null */ + private $shippingValue = null; /** @var float */ private $totalItems; @@ -56,32 +53,32 @@ class Order implements XmlEntityInterface /** @var float */ private $totalOrder; - /** @var int */ - private $quantityInstallments; + /** @var int|null */ + private $quantityInstallments = null; - /** @var string */ - private $deliveryTime; + /** @var string|null */ + private $deliveryTime = null; - /** @var int */ - private $quantityItems; + /** @var int|null */ + private $quantityItems = null; - /** @var int */ - private $quantityPaymentTypes; + /** @var int|null */ + private $quantityPaymentTypes = null; - /** @var string */ - private $ip; + /** @var string|null */ + private $ip = null; - /** @var string */ - private $notes; + /** @var string|null */ + private $notes = null; - /** @var int */ - private $status; + /** @var int|null */ + private $status = null; - /** @var string */ - private $origin; + /** @var string|null */ + private $origin = null; - /** @var \DateTime */ - private $reservationDate; + /** @var \DateTimeInterface|null */ + private $reservationDate = null; /** @var \RodrigoPedra\ClearSaleID\Entity\Request\CustomerBillingData */ private $customerBillingData; @@ -90,103 +87,92 @@ class Order implements XmlEntityInterface private $customerShippingData; /** @var \RodrigoPedra\ClearSaleID\Entity\Request\Payment[] */ - private $payments; + private $payments = []; /** @var \RodrigoPedra\ClearSaleID\Entity\Request\Item[] */ - private $items; + private $items = []; /** @var \RodrigoPedra\ClearSaleID\Entity\Request\Passenger[] */ - private $passengers; + private $passengers = []; /** @var \RodrigoPedra\ClearSaleID\Entity\Request\Connection[] */ - private $connections; + private $connections = []; - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\FingerPrint $fingerPrint - * @param int $id - * @param \DateTime $date - * @param string $email - * @param float $totalItems - * @param float $totalOrder - * @param int $quantityInstallments - * @param string $ip - * @param string $origin - * @param \RodrigoPedra\ClearSaleID\Entity\Request\CustomerBillingData $customerBillingData - * @param \RodrigoPedra\ClearSaleID\Entity\Request\CustomerShippingData $customerShippingData - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Payment $payment - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Item $item - * - * @return \RodrigoPedra\ClearSaleID\Entity\Request\Order - */ - public static function createEcommerceOrder( + public function __construct( FingerPrint $fingerPrint, - $id, - DateTime $date, - $email, - $totalItems, - $totalOrder, - $quantityInstallments, - $ip, - $origin, - CustomerBillingData $customerBillingData, - CustomerShippingData $customerShippingData, + string $id, + \DateTimeInterface $date, + float $totalItems, + float $totalOrder, + CustomerBillingData $billingData, + CustomerShippingData $shippingData, Payment $payment, Item $item ) { - return static::create( + $this->setFingerPrint($fingerPrint); + $this->setId($id); + $this->setDate($date); + $this->setTotalItems($totalItems); + $this->setTotalOrder($totalOrder); + $this->setBillingData($billingData); + $this->setShippingData($shippingData); + $this->addPayment($payment); + $this->addItem($item); + } + + public static function createEcommerceOrder( + FingerPrint $fingerPrint, + string $id, + \DateTimeInterface $date, + string $email, + float $totalItems, + float $totalOrder, + int $quantityInstallments, + string $ip, + string $origin, + CustomerBillingData $billingData, + CustomerShippingData $shippingData, + Payment $payment, + Item $item + ): self { + $instance = new self( $fingerPrint, $id, $date, - $email, $totalItems, $totalOrder, - $quantityInstallments, - $ip, - $origin, - $customerBillingData, - $customerShippingData, + $billingData, + $shippingData, $payment, $item ); + + $instance->setEmail($email); + $instance->setQuantityInstallments($quantityInstallments); + $instance->setIp($ip); + $instance->setOrigin($origin); + + return $instance; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\FingerPrint $fingerPrint - * @param int $id - * @param \DateTime $date - * @param string $email - * @param float $totalItems - * @param float $totalOrder - * @param int $quantityInstallments - * @param string $ip - * @param string $origin - * @param \RodrigoPedra\ClearSaleID\Entity\Request\CustomerBillingData $customerBillingData - * @param \RodrigoPedra\ClearSaleID\Entity\Request\CustomerShippingData $customerShippingData - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Payment $payment - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Item $item - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Passenger $passenger - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Connection $connection - * - * @return \RodrigoPedra\ClearSaleID\Entity\Request\Order - */ public static function createAirlineTicketOrder( FingerPrint $fingerPrint, - $id, - DateTime $date, - $email, - $totalItems, - $totalOrder, - $quantityInstallments, - $ip, - $origin, + string $id, + \DateTimeInterface $date, + string $email, + float $totalItems, + float $totalOrder, + int $quantityInstallments, + string $ip, + string $origin, CustomerBillingData $customerBillingData, CustomerShippingData $customerShippingData, Payment $payment, Item $item, - Passenger $passenger = null, - Connection $connection = null - ) { - return static::create( + Passenger $passenger, + Connection $connection + ): self { + $instance = static::createEcommerceOrder( $fingerPrint, $id, $date, @@ -199,192 +185,92 @@ public static function createAirlineTicketOrder( $customerBillingData, $customerShippingData, $payment, - $item, - $passenger, - $connection + $item ); - } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\FingerPrint $fingerPrint - * @param int $id - * @param \DateTime $date - * @param string $email - * @param float $totalItems - * @param float $totalOrder - * @param int $quantityInstallments - * @param string $ip - * @param string $origin - * @param \RodrigoPedra\ClearSaleID\Entity\Request\CustomerBillingData $customerBillingData - * @param \RodrigoPedra\ClearSaleID\Entity\Request\CustomerShippingData $shippingData - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Payment $payment - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Item $item - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Passenger|null $passenger - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Connection|null $connection - * - * @return \RodrigoPedra\ClearSaleID\Entity\Request\Order - */ - private static function create( - FingerPrint $fingerPrint, - $id, - DateTime $date, - $email, - $totalItems, - $totalOrder, - $quantityInstallments, - $ip, - $origin, - CustomerBillingData $customerBillingData, - CustomerShippingData $shippingData, - Payment $payment, - Item $item, - Passenger $passenger = null, - Connection $connection = null - ) { - $instance = new self; - - $instance->setFingerPrint( $fingerPrint ); - $instance->setId( $id ); - $instance->setDate( $date ); - $instance->setEmail( $email ); - $instance->setTotalItems( $totalItems ); - $instance->setTotalOrder( $totalOrder ); - $instance->setQuantityInstallments( $quantityInstallments ); - $instance->setIp( $ip ); - $instance->setOrigin( $origin ); - $instance->setBillingData( $customerBillingData ); - $instance->setShippingData( $shippingData ); - $instance->addPayment( $payment ); - $instance->addItem( $item ); - - if (null !== $passenger) { - $instance->addPassenger( $passenger ); - } - - if (null !== $connection) { - $instance->addConnection( $connection ); - } + $instance->addPassenger($passenger); + $instance->addConnection($connection); return $instance; } - /** - * @return \RodrigoPedra\ClearSaleID\Entity\Request\FingerPrint - */ - public function getFingerPrint() + public function getFingerPrint(): FingerPrint { return $this->fingerPrint; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\FingerPrint $fingerPrint - * - * @return $this - */ - public function setFingerPrint( FingerPrint $fingerPrint ) + public function setFingerPrint(FingerPrint $fingerPrint): self { $this->fingerPrint = $fingerPrint; return $this; } - /** - * @return string - */ - public function getId() + public function getId(): string { return $this->id; } - /** - * @param int $id - * - * @return $this - */ - public function setId( $id ) + public function setId(string $id): self { + $id = \trim($id); + + if (\strlen($id) === 0) { + throw new RequiredFieldException('Order ID is required'); + } + $this->id = $id; return $this; } - /** - * @return \DateTime - */ - public function getDate() + public function getDate(): \DateTimeInterface { return $this->date; } - /** - * @param \DateTime $date - * - * @return $this - */ - public function setDate( DateTime $date ) + public function setDate(\DateTimeInterface $date): self { $this->date = $date; return $this; } - /** - * @return string - */ - public function getEmail() + public function getEmail(): ?string { return $this->email; } - /** - * @param string $email - * - * @return $this - */ - public function setEmail( $email ) + public function setEmail(string $email): self { - $this->email = $email; + $this->email = \trim($email) ?: null; return $this; } - /** - * @return string - */ - public function getChannel() + public function getChannel(): ?string { return $this->channel; } - /** - * @param string $channel - * - * @return $this - */ - public function setChannel( $channel ) + public function setChannel(string $channel): self { - $this->channel = $channel; + $this->channel = \trim($channel) ?: null; return $this; } - /** - * @return string - */ - public function getEcommerceType() + public function getEcommerceType(): ?string { return $this->ecommerceType; } - /** - * @param string $ecommerceType - * - * @return $this - */ - public function setEcommerceType( $ecommerceType ) + public function setEcommerceType(string $ecommerceType): self { - if (!in_array( $ecommerceType, self::$ecommerceTypes )) { - throw new InvalidArgumentException( sprintf( 'Invalid e-commerce type (%s)', $ecommerceType ) ); + if (! \in_array($ecommerceType, self::$ecommerceTypes)) { + throw new \InvalidArgumentException( + \sprintf('Invalid e-commerce type (%s)', $ecommerceType) + ); } $this->ecommerceType = $ecommerceType; @@ -392,106 +278,77 @@ public function setEcommerceType( $ecommerceType ) return $this; } - /** - * @return float - */ - public function getShippingValue() + public function getShippingValue(): ?float { return $this->shippingValue; } - /** - * @param float $shippingValue - * - * @return $this - */ - public function setShippingValue( $shippingValue ) + public function setShippingValue(float $shippingValue): self { - if (preg_match( '/^(?:\d*\.)?\d+$/', $shippingValue ) !== 1) { - throw new InvalidArgumentException( sprintf( 'Shipping value should be a non-negative number (%s)', - $shippingValue ) ); + if ($shippingValue < 0.0) { + throw new \InvalidArgumentException( + \sprintf('Shipping value value should be a non-negative number (%s)', $shippingValue) + ); } - $this->shippingValue = (float)number_format( $shippingValue, 4, '.', '' ); + $this->shippingValue = \floatval(\number_format($shippingValue, 4, '.', '')); return $this; } - /** - * @return float - */ - public function getTotalItems() + public function getTotalItems(): float { return $this->totalItems; } - /** - * @param float $totalItems - * - * @return $this - */ - public function setTotalItems( $totalItems ) + public function setTotalItems(float $totalItems): self { - if (preg_match( '/^(?:\d*\.)?\d+$/', $totalItems ) !== 1) { - throw new InvalidArgumentException( sprintf( 'Items total value should be a non-negative number (%s)', - $totalItems ) ); + if ($totalItems < 0.0) { + throw new \InvalidArgumentException( + \sprintf('Items total value should be a non-negative number (%s)', $totalItems) + ); } - $this->totalItems = (float)number_format( $totalItems, 4, '.', '' ); + $this->totalItems = \floatval(\number_format($totalItems, 4, '.', '')); return $this; } - /** - * @return float - */ - public function getTotalOrder() + public function getTotalOrder(): float { return $this->totalOrder; } - /** - * @param float $totalOrder - * - * @return $this - */ - public function setTotalOrder( $totalOrder ) + public function setTotalOrder(float $totalOrder): self { - if (preg_match( '/^(?:\d*\.)?\d+$/', $totalOrder ) !== 1) { - throw new InvalidArgumentException( sprintf( 'Order total value should be a non-negative number (%s)', - $totalOrder ) ); + if ($totalOrder < 0.0) { + throw new \InvalidArgumentException( + \sprintf('Order total value should be a non-negative number (%s)', $totalOrder) + ); } - $this->totalOrder = (float)number_format( $totalOrder, 4, '.', '' ); + $this->totalOrder = \floatval(\number_format($totalOrder, 4, '.', '')); return $this; } - /** - * @return int - */ - public function getQuantityInstallments() + public function getQuantityInstallments(): ?int { return $this->quantityInstallments; } - /** - * @param int $quantityInstallments - * - * @return $this - */ - public function setQuantityInstallments( $quantityInstallments ) + public function setQuantityInstallments(int $quantityInstallments): self { - if (preg_match( '/^\d+$/', $quantityInstallments ) !== 1) { - throw new InvalidArgumentException( sprintf( 'Installments quantity should be a non-negative integer (%s)', - $quantityInstallments ) ); + if ($quantityInstallments < 0) { + throw new \InvalidArgumentException( + \sprintf('Installments quantity should be a non-negative integer (%s)', $quantityInstallments) + ); } - $quantityInstallments = intval( $quantityInstallments ); - if ($quantityInstallments > 99) { - throw new InvalidArgumentException( sprintf( 'Installments quantity should be less than 99 (%s)', - $quantityInstallments ) ); + throw new \InvalidArgumentException( + \sprintf('Installments quantity should be less than 99 (%s)', $quantityInstallments) + ); } $this->quantityInstallments = $quantityInstallments; @@ -499,133 +356,87 @@ public function setQuantityInstallments( $quantityInstallments ) return $this; } - /** - * @return string - */ - public function getDeliveryTime() + public function getDeliveryTime(): ?string { return $this->deliveryTime; } - /** - * @param string $deliveryTime - * - * @return $this - */ - public function setDeliveryTime( $deliveryTime ) + public function setDeliveryTime(string $deliveryTime): self { - $this->deliveryTime = $deliveryTime; + $this->deliveryTime = \trim($deliveryTime) ?: null; return $this; } - /** - * @return int - */ - public function getQuantityItems() + public function getQuantityItems(): ?int { return $this->quantityItems; } - /** - * @param int $quantityItems - * - * @return $this - */ - public function setQuantityItems( $quantityItems ) + public function setQuantityItems(int $quantityItems): self { - if (preg_match( '/^\d+$/', $quantityItems ) !== 1) { - throw new InvalidArgumentException( sprintf( 'Items quantity should be a non-negative integer (%s)', - $quantityItems ) ); + if ($quantityItems < 0) { + throw new \InvalidArgumentException( + \sprintf('Items quantity should be a non-negative integer (%s)', $quantityItems) + ); } - $this->quantityItems = intval( $quantityItems ); + $this->quantityItems = $quantityItems; return $this; } - /** - * @return int - */ - public function getQuantityPaymentTypes() + public function getQuantityPaymentTypes(): ?int { return $this->quantityPaymentTypes; } - /** - * @param int $quantityPaymentTypes - * - * @return $this - */ - public function setQuantityPaymentTypes( $quantityPaymentTypes ) + public function setQuantityPaymentTypes(int $quantityPaymentTypes): self { - if (preg_match( '/^\d+$/', $quantityPaymentTypes ) !== 1) { - throw new InvalidArgumentException( sprintf( 'Payment types quantity should be a non-negative integer (%s)', - $quantityPaymentTypes ) ); + if ($quantityPaymentTypes < 0) { + throw new \InvalidArgumentException( + \sprintf('Payment types quantity should be a non-negative integer (%s)', $quantityPaymentTypes) + ); } - $this->quantityPaymentTypes = intval( $quantityPaymentTypes ); + $this->quantityPaymentTypes = $quantityPaymentTypes; return $this; } - /** - * @return string - */ - public function getIp() + public function getIp(): ?string { return $this->ip; } - /** - * @param string $ip - * - * @return $this - */ - public function setIp( $ip ) + public function setIp(string $ip): self { - $this->ip = $ip; + $this->ip = \trim($ip) ?: null; return $this; } - /** - * @return string - */ - public function getNotes() + public function getNotes(): ?string { return $this->notes; } - /** - * @param string $notes - * - * @return $this - */ - public function setNotes( $notes ) + public function setNotes(string $notes): self { - $this->notes = $notes; + $this->notes = \trim($notes) ?: null; return $this; } - /** - * @return int - */ - public function getStatus() + public function getStatus(): ?int { return $this->status; } - /** - * @param int $status - * - * @return $this - */ - public function setStatus( $status ) + public function setStatus(int $status): self { - if (!in_array( intval( $status ), self::$statuses )) { - throw new InvalidArgumentException( sprintf( 'Invalid status (%s)', $status ) ); + if (! \in_array($status, self::$statuses)) { + throw new \InvalidArgumentException(\sprintf('Invalid status (%s)', $status)); } $this->status = $status; @@ -633,80 +444,48 @@ public function setStatus( $status ) return $this; } - /** - * @return string - */ - public function getOrigin() + public function getOrigin(): ?string { return $this->origin; } - /** - * @param string $origin - * - * @return $this - */ - public function setOrigin( $origin ) + public function setOrigin(string $origin): self { - $this->origin = $origin; + $this->origin = \trim($origin) ?: null; return $this; } - /** - * @return \DateTime - */ - public function getReservationDate() + public function getReservationDate(): ?\DateTimeInterface { return $this->reservationDate; } - /** - * @param \DateTime $reservationDate - * - * @return $this - */ - public function setReservationDate( DateTime $reservationDate ) + public function setReservationDate(\DateTimeInterface $reservationDate): self { $this->reservationDate = $reservationDate; return $this; } - /** - * @return \RodrigoPedra\ClearSaleID\Entity\Request\CustomerBillingData - */ - public function getBillingData() + public function getBillingData(): CustomerBillingData { return $this->customerBillingData; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\CustomerBillingData $customerBillingData - * - * @return $this - */ - public function setBillingData( CustomerBillingData $customerBillingData ) + public function setBillingData(CustomerBillingData $customerBillingData): self { $this->customerBillingData = $customerBillingData; return $this; } - /** - * @return \RodrigoPedra\ClearSaleID\Entity\Request\CustomerShippingData - */ - public function getShippingData() + public function getShippingData(): CustomerShippingData { return $this->customerShippingData; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\CustomerShippingData $customerShippingData - * - * @return $this - */ - public function setShippingData( CustomerShippingData $customerShippingData ) + public function setShippingData(CustomerShippingData $customerShippingData): self { $this->customerShippingData = $customerShippingData; @@ -716,52 +495,45 @@ public function setShippingData( CustomerShippingData $customerShippingData ) /** * @return \RodrigoPedra\ClearSaleID\Entity\Request\Payment[] */ - public function getPayments() + public function getPayments(): array { return $this->payments; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Payment[] $payments - * - * @return $this - */ - public function setPayments( $payments ) + public function setPayments(iterable $payments): self { foreach ($payments as $payment) { - $this->addPayment( $payment ); + $this->addPayment($payment); + } + + if (\count($this->payments) === 0) { + throw new RequiredFieldException('Order requires at least one payment'); } return $this; } - /** - * @param int $index - * - * @return \RodrigoPedra\ClearSaleID\Entity\Request\Payment - */ - public function getPayment( $index ) + public function getPayment(int $index): Payment { - return $this->payments[ $index ]; + return $this->payments[$index]; } /** * @return \RodrigoPedra\ClearSaleID\Entity\Request\Item[] */ - public function getItems() + public function getItems(): array { return $this->items; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Item[] $items - * - * @return $this - */ - public function setItems( $items ) + public function setItems(iterable $items): self { foreach ($items as $item) { - $this->addItem( $item ); + $this->addItem($item); + } + + if (\count($this->items) === 0) { + throw new RequiredFieldException('Order requires at least one item'); } return $this; @@ -770,20 +542,15 @@ public function setItems( $items ) /** * @return \RodrigoPedra\ClearSaleID\Entity\Request\Passenger[] */ - public function getPassengers() + public function getPassengers(): array { return $this->passengers; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Passenger[] $passengers - * - * @return $this - */ - public function setPassengers( $passengers ) + public function setPassengers(iterable $passengers): self { foreach ($passengers as $passenger) { - $this->addPassenger( $passenger ); + $this->addPassenger($passenger); } return $this; @@ -792,220 +559,151 @@ public function setPassengers( $passengers ) /** * @return \RodrigoPedra\ClearSaleID\Entity\Request\Connection[] */ - public function getConnections() + public function getConnections(): array { return $this->connections; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Connection[] $connections - * - * @return $this - */ - public function setConnections( $connections ) + public function setConnections(iterable $connections): self { foreach ($connections as $connection) { - $this->addConnection( $connection ); + $this->addConnection($connection); } return $this; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Payment $payment - * - * @return $this - */ - public function addPayment( Payment $payment ) + public function addPayment(Payment $payment): self { $this->payments[] = $payment; return $this; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Item $item - * - * @return $this - */ - public function addItem( Item $item ) + public function addItem(Item $item): self { $this->items[] = $item; return $this; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Passenger $passenger - * - * @return $this - */ - public function addPassenger( Passenger $passenger ) + public function addPassenger(Passenger $passenger): self { $this->passengers[] = $passenger; return $this; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Connection $connection - * - * @return $this - */ - public function addConnection( Connection $connection ) + public function addConnection(Connection $connection): self { $this->connections[] = $connection; return $this; } - /** - * @param \XMLWriter $XMLWriter - * - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - public function toXML( XMLWriter $XMLWriter ) + public function toXML(\XMLWriter $XMLWriter): void { - $XMLWriter->startElement( 'ClearID_Input' ); + $XMLWriter->startElement('ClearID_Input'); - if ($this->fingerPrint) { - $this->fingerPrint->toXML( $XMLWriter ); - } else { - throw new RequiredFieldException( 'Field FingerPrint of the Order object is required' ); - } + $this->fingerPrint->toXML($XMLWriter); - $XMLWriter->startElement( 'Pedido' ); + $XMLWriter->startElement('Pedido'); - if ($this->id) { - $XMLWriter->writeElement( 'PedidoID', $this->id ); - } else { - throw new RequiredFieldException( 'Field ID of the Order object is required' ); - } - - if ($this->date) { - $XMLWriter->writeElement( 'Data', $this->date->format( self::DATE_TIME_FORMAT ) ); - } else { - throw new RequiredFieldException( 'Field Date of the Order object is required' ); - } + $XMLWriter->writeElement('PedidoID', $this->id); + $XMLWriter->writeElement('Data', $this->date->format(self::DATE_TIME_FORMAT)); if ($this->email) { - $XMLWriter->writeElement( 'Email', $this->email ); + $XMLWriter->writeElement('Email', $this->email); } if ($this->channel) { - $XMLWriter->writeElement( 'CanalID', $this->channel ); + $XMLWriter->writeElement('CanalID', $this->channel); } if ($this->ecommerceType) { - $XMLWriter->writeElement( 'B2B_B2C', $this->ecommerceType ); + $XMLWriter->writeElement('B2B_B2C', $this->ecommerceType); } if ($this->shippingValue) { - $XMLWriter->writeElement( 'ValorFrete', $this->shippingValue ); + $XMLWriter->writeElement('ValorFrete', $this->shippingValue); } - if (is_numeric( $this->totalItems )) { - $XMLWriter->writeElement( 'ValorTotalItens', $this->totalItems ); - } else { - throw new RequiredFieldException( 'Field TotalItems of the Order object is required' ); - } - - if (is_numeric( $this->totalOrder )) { - $XMLWriter->writeElement( 'ValorTotalPedido', $this->totalOrder ); - } else { - throw new RequiredFieldException( 'Field TotalOrder of the Order object is required' ); - } + $XMLWriter->writeElement('ValorTotalItens', $this->totalItems); + $XMLWriter->writeElement('ValorTotalPedido', $this->totalOrder); if ($this->quantityInstallments) { - $XMLWriter->writeElement( 'QtdParcelas', $this->quantityInstallments ); + $XMLWriter->writeElement('QtdParcelas', $this->quantityInstallments); } if ($this->deliveryTime) { - $XMLWriter->writeElement( 'PrazoEntrega', $this->deliveryTime ); + $XMLWriter->writeElement('PrazoEntrega', $this->deliveryTime); } if ($this->quantityItems) { - $XMLWriter->writeElement( 'QtdItens', $this->quantityItems ); + $XMLWriter->writeElement('QtdItens', $this->quantityItems); } if ($this->quantityPaymentTypes) { - $XMLWriter->writeElement( 'QtdFormasPagamento', $this->quantityPaymentTypes ); + $XMLWriter->writeElement('QtdFormasPagamento', $this->quantityPaymentTypes); } if ($this->ip) { - $XMLWriter->writeElement( 'IP', $this->ip ); + $XMLWriter->writeElement('IP', $this->ip); } if ($this->notes) { - $XMLWriter->writeElement( 'Observacao', $this->notes ); + $XMLWriter->writeElement('Observacao', $this->notes); } if ($this->status) { - $XMLWriter->writeElement( 'Status', $this->status ); + $XMLWriter->writeElement('Status', $this->status); } if ($this->origin) { - $XMLWriter->writeElement( 'Origem', $this->origin ); + $XMLWriter->writeElement('Origem', $this->origin); } if ($this->reservationDate) { - $XMLWriter->writeElement( 'DataReserva', $this->reservationDate->format( self::DATE_TIME_FORMAT ) ); - } - - if ($this->customerBillingData) { - $this->customerBillingData->toXML( $XMLWriter ); - } else { - throw new RequiredFieldException( 'Field CustomerBillingData of the Order object is required' ); + $XMLWriter->writeElement('DataReserva', $this->reservationDate->format(self::DATE_TIME_FORMAT)); } - if ($this->customerShippingData) { - $this->customerShippingData->toXML( $XMLWriter ); - } else { - throw new RequiredFieldException( 'Field CustomerShippingData of the Order object is required' ); - } - - if ($this->payments && count( $this->payments ) > 0) { - $XMLWriter->startElement( 'Pagamentos' ); + $this->customerBillingData->toXML($XMLWriter); + $this->customerShippingData->toXML($XMLWriter); - foreach ($this->payments as $payment) { - $payment->toXML( $XMLWriter ); - } + $XMLWriter->startElement('Pagamentos'); - $XMLWriter->endElement(); - } else { - throw new RequiredFieldException( 'Field Payments of the Order object is required' ); + foreach ($this->payments as $payment) { + $payment->toXML($XMLWriter); } - if ($this->items && count( $this->items ) > 0) { - $XMLWriter->startElement( 'Itens' ); + $XMLWriter->endElement(); // Pagamentos - foreach ($this->items as $item) { - $item->toXML( $XMLWriter ); - } + $XMLWriter->startElement('Itens'); - $XMLWriter->endElement(); - } else { - throw new RequiredFieldException( 'Field Items of the Order object is required' ); + foreach ($this->items as $item) { + $item->toXML($XMLWriter); } - if ($this->passengers && count( $this->passengers ) > 0) { - $XMLWriter->startElement( 'Passageiros' ); + $XMLWriter->endElement(); // Itens + + if (\count($this->passengers) > 0) { + $XMLWriter->startElement('Passageiros'); foreach ($this->passengers as $passenger) { - $passenger->toXML( $XMLWriter ); + $passenger->toXML($XMLWriter); } - $XMLWriter->endElement(); + $XMLWriter->endElement(); // Passageiros } - if ($this->connections && count( $this->connections ) > 0) { - $XMLWriter->startElement( 'Conexoes' ); + if (\count($this->connections) > 0) { + $XMLWriter->startElement('Conexoes'); foreach ($this->connections as $connection) { - $connection->toXML( $XMLWriter ); + $connection->toXML($XMLWriter); } - $XMLWriter->endElement(); + $XMLWriter->endElement(); // Conexoes } $XMLWriter->endElement(); // Pedido diff --git a/src/ClearSaleID/Entity/Request/Passenger.php b/src/ClearSaleID/Entity/Request/Passenger.php index b1aea55..253f137 100644 --- a/src/ClearSaleID/Entity/Request/Passenger.php +++ b/src/ClearSaleID/Entity/Request/Passenger.php @@ -2,20 +2,18 @@ namespace RodrigoPedra\ClearSaleID\Entity\Request; -use InvalidArgumentException; use RodrigoPedra\ClearSaleID\Entity\XmlEntityInterface; use RodrigoPedra\ClearSaleID\Exception\RequiredFieldException; -use XMLWriter; class Passenger implements XmlEntityInterface { - const DOCUMENT_TYPE_CPF = 1; - const DOCUMENT_TYPE_CNPJ = 2; - const DOCUMENT_TYPE_RG = 3; - const DOCUMENT_TYPE_IE = 4; - const DOCUMENT_TYPE_PASSAPORTE = 5; - const DOCUMENT_TYPE_CTPS = 6; - const DOCUMENT_TYPE_TITULO_ELEITOR = 7; + public const DOCUMENT_TYPE_CPF = 1; + public const DOCUMENT_TYPE_CNPJ = 2; + public const DOCUMENT_TYPE_RG = 3; + public const DOCUMENT_TYPE_IE = 4; + public const DOCUMENT_TYPE_PASSAPORTE = 5; + public const DOCUMENT_TYPE_CTPS = 6; + public const DOCUMENT_TYPE_TITULO_ELEITOR = 7; private $documentTypes = [ self::DOCUMENT_TYPE_CPF, @@ -24,14 +22,14 @@ class Passenger implements XmlEntityInterface self::DOCUMENT_TYPE_IE, self::DOCUMENT_TYPE_PASSAPORTE, self::DOCUMENT_TYPE_CTPS, - self::DOCUMENT_TYPE_TITULO_ELEITOR + self::DOCUMENT_TYPE_TITULO_ELEITOR, ]; /** @var string */ private $name; - /** @var string */ - private $frequentFlyerCard; + /** @var ?string */ + private $frequentFlyerCard = null; /** @var int */ private $legalDocumentType; @@ -39,81 +37,59 @@ class Passenger implements XmlEntityInterface /** @var string */ private $legalDocument; - /** - * @param string $name - * @param int $legalDocumentType - * @param string $legalDocument - * - * @return \RodrigoPedra\ClearSaleID\Entity\Request\Passenger - */ - public static function create( $name, $legalDocumentType, $legalDocument ) + public function __construct(string $name, int $legalDocumentType, string $legalDocument) { - $instance = new self; - - $instance->setName( $name ); - $instance->setLegalDocumentType( $legalDocumentType ); - $instance->setLegalDocument( $legalDocument ); + $this->setName($name); + $this->setLegalDocumentType($legalDocumentType); + $this->setLegalDocument($legalDocument); + } - return $instance; + public static function create(string $name, int $legalDocumentType, string $legalDocument): self + { + return new self($name, $legalDocumentType, $legalDocument); } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * @param string $name - * - * @return $this - */ - public function setName( $name ) + public function setName(string $name): self { + $name = \trim($name); + + if (\strlen($name) === 0) { + throw new RequiredFieldException('Name is required'); + } + $this->name = $name; return $this; } - /** - * @return string - */ - public function getFrequentFlyerCard() + public function getFrequentFlyerCard(): ?string { return $this->frequentFlyerCard; } - /** - * @param string $frequentFlyerCard - * - * @return $this - */ - public function setFrequentFlyerCard( $frequentFlyerCard ) + public function setFrequentFlyerCard(string $frequentFlyerCard): self { - $this->frequentFlyerCard = $frequentFlyerCard; + $this->frequentFlyerCard = \trim($frequentFlyerCard) ?: null; return $this; } - /** - * @return int - */ - public function getLegalDocumentType() + public function getLegalDocumentType(): int { return $this->legalDocumentType; } - /** - * @param int $legalDocumentType - * - * @return $this - */ - public function setLegalDocumentType( $legalDocumentType ) + public function setLegalDocumentType(int $legalDocumentType): self { - if (!in_array( intval( $legalDocumentType ), $this->documentTypes )) { - throw new InvalidArgumentException( sprintf( 'Invalid document type (%s)', $legalDocumentType ) ); + if (! \in_array($legalDocumentType, $this->documentTypes)) { + throw new \InvalidArgumentException( + \sprintf('Invalid document type (%s)', $legalDocumentType) + ); } $this->legalDocumentType = $legalDocumentType; @@ -121,57 +97,37 @@ public function setLegalDocumentType( $legalDocumentType ) return $this; } - /** - * @return string - */ - public function getLegalDocument() + public function getLegalDocument(): string { return $this->legalDocument; } - /** - * @param string $legalDocument - * - * @return $this - */ - public function setLegalDocument( $legalDocument ) + public function setLegalDocument(string $legalDocument): self { + $legalDocument = \trim($legalDocument); + + if (\strlen($legalDocument) === 0) { + throw new RequiredFieldException('Legal Document is required'); + } + $this->legalDocument = $legalDocument; return $this; } - /** - * @param \XMLWriter $XMLWriter - * - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - public function toXML( XMLWriter $XMLWriter ) + public function toXML(\XMLWriter $XMLWriter) { - $XMLWriter->startElement( 'Passageiro' ); + $XMLWriter->startElement('Passageiro'); - if ($this->name) { - $XMLWriter->writeElement( 'Nome', $this->name ); - } else { - throw new RequiredFieldException( 'Field Nome of the Passenger object is required' ); - } + $XMLWriter->writeElement('Nome', $this->name); if ($this->frequentFlyerCard) { - $XMLWriter->writeElement( 'ProgramaFidelidade', $this->frequentFlyerCard ); + $XMLWriter->writeElement('ProgramaFidelidade', $this->frequentFlyerCard); } - if ($this->legalDocumentType) { - $XMLWriter->writeElement( 'TipoDocumentoLegal', $this->legalDocumentType ); - } else { - throw new RequiredFieldException( 'Field LegalDocumentType of the Passenger object is required' ); - } - - if ($this->legalDocument) { - $XMLWriter->writeElement( 'DocumentoLegal', $this->legalDocument ); - } else { - throw new RequiredFieldException( 'Field LegalDocument of the Passenger object is required' ); - } + $XMLWriter->writeElement('TipoDocumentoLegal', $this->legalDocumentType); + $XMLWriter->writeElement('DocumentoLegal', $this->legalDocument); - $XMLWriter->endElement(); + $XMLWriter->endElement(); // Passageiro } } diff --git a/src/ClearSaleID/Entity/Request/Payment.php b/src/ClearSaleID/Entity/Request/Payment.php index 57d7f36..a2a0853 100755 --- a/src/ClearSaleID/Entity/Request/Payment.php +++ b/src/ClearSaleID/Entity/Request/Payment.php @@ -2,28 +2,24 @@ namespace RodrigoPedra\ClearSaleID\Entity\Request; -use DateTime; -use InvalidArgumentException; use RodrigoPedra\ClearSaleID\Entity\XmlEntityInterface; -use RodrigoPedra\ClearSaleID\Exception\RequiredFieldException; -use XMLWriter; class Payment implements XmlEntityInterface { - const CARTAO_CREDITO = 1; - const BOLETO_BANCARIO = 2; - const DEBITO_BANCARIO = 3; - const DEBITO_BANCARIO_DINHEIRO = 4; - const DEBITO_BANCARIO_CHEQUE = 5; - const TRANSFERENCIA_BANCARIA = 6; - const SEDEX_A_COBRAR = 7; - const CHEQUE = 8; - const DINHEIRO = 9; - const FINANCIAMENTO = 10; - const FATURA = 11; - const CUPOM = 12; - const MULTICHEQUE = 13; - const OUTROS = 14; + public const CARTAO_CREDITO = 1; + public const BOLETO_BANCARIO = 2; + public const DEBITO_BANCARIO = 3; + public const DEBITO_BANCARIO_DINHEIRO = 4; + public const DEBITO_BANCARIO_CHEQUE = 5; + public const TRANSFERENCIA_BANCARIA = 6; + public const SEDEX_A_COBRAR = 7; + public const CHEQUE = 8; + public const DINHEIRO = 9; + public const FINANCIAMENTO = 10; + public const FATURA = 11; + public const CUPOM = 12; + public const MULTICHEQUE = 13; + public const OUTROS = 14; private static $paymentTypes = [ self::CARTAO_CREDITO, @@ -45,59 +41,45 @@ class Payment implements XmlEntityInterface /** @var int */ private $type; - /** @var int */ - private $sequential; + /** @var int|null */ + private $sequential = null; - /** @var \DateTime */ + /** @var \DateTimeInterface */ private $date; /** @var float */ private $amount; - /** @var int */ - private $quantityInstallments; - - /** @var \RodrigoPedra\ClearSaleID\Entity\Request\ Card */ - private $card; - - /** @var string */ - private $legalDocument; - - /** - * @param int $type - * @param \DateTime $date - * @param float $amount - * - * @return \RodrigoPedra\ClearSaleID\Entity\Request\Payment - */ - public static function create( $type, DateTime $date, $amount ) - { - $instance = new self; + /** @var int|null */ + private $quantityInstallments = null; + + /** @var \RodrigoPedra\ClearSaleID\Entity\Request\Card|null */ + private $card = null; - $instance->setType( $type ); - $instance->setDate( $date ); - $instance->setAmount( $amount ); + /** @var string|null */ + private $legalDocument = null; + + public function __construct(string $type, \DateTimeInterface $date, float $amount) + { + $this->setType($type); + $this->setDate($date); + $this->setAmount($amount); + } - return $instance; + public static function create(string $type, \DateTimeInterface $date, float $amount): self + { + return new self($type, $date, $amount); } - /** - * @return int - */ - public function getType() + public function getType(): int { return $this->type; } - /** - * @param int $type - * - * @return $this - */ - public function setType( $type ) + public function setType(int $type): self { - if (!array_key_exists( intval( $type ), self::$paymentTypes )) { - throw new InvalidArgumentException( sprintf( 'Invalid payment type (%s)', $type ) ); + if (! \array_key_exists($type, self::$paymentTypes)) { + throw new \InvalidArgumentException(\sprintf('Invalid payment type (%s)', $type)); } $this->type = $type; @@ -105,100 +87,71 @@ public function setType( $type ) return $this; } - /** - * @return int - */ - public function getSequential() + public function getSequential(): ?int { return $this->sequential; } - /** - * @param int $sequential - * - * @return $this - */ - public function setSequential( $sequential ) + public function setSequential(int $sequential): self { - if (preg_match( '/^[1-9]$/', $sequential ) !== 1) { - throw new InvalidArgumentException( sprintf( 'Sequential number should be between 1 and 9 (%s)', - $sequential ) ); + if (! \in_array($sequential, \range(1, 9))) { + throw new \InvalidArgumentException( + \sprintf('Sequential number should be between 1 and 9 (%s)', $sequential) + ); } - $this->sequential = intval( $sequential ); + $this->sequential = $sequential; return $this; } - /** - * @return \DateTime - */ - public function getDate() + public function getDate(): \DateTimeInterface { return $this->date; } - /** - * @param \DateTime $date - * - * @return $this - */ - public function setDate( DateTime $date ) + public function setDate(\DateTimeInterface $date): self { $this->date = $date; return $this; } - /** - * @return float - */ - public function getAmount() + public function getAmount(): float { return $this->amount; } - /** - * @param float $amount - * - * @return $this - */ - public function setAmount( $amount ) + public function setAmount(float $amount): self { - if (preg_match( '/^(?:\d*\.)?\d+$/', $amount ) !== 1) { - throw new InvalidArgumentException( sprintf( 'Amount should be a non-negative number (%s)', $amount ) ); + if ($amount < 0.0) { + throw new \InvalidArgumentException( + \sprintf('Amount should be a non-negative number (%s)', $amount) + ); } - $this->amount = (float)number_format( $amount, 4, '.', '' ); + $this->amount = \floatval(\number_format($amount, 4, '.', '')); return $this; } - /** - * @return int - */ - public function getQtyInstallments() + public function getQtyInstallments(): ?int { return $this->quantityInstallments; } - /** - * @param int $quantityInstallments - * - * @return $this - */ - public function setQtyInstallments( $quantityInstallments ) + public function setQtyInstallments(int $quantityInstallments): self { - if (preg_match( '/^\d+$/', $quantityInstallments ) !== 1) { - throw new InvalidArgumentException( sprintf( 'Installments quantity should be a non-negative integer (%s)', - $quantityInstallments ) ); + if ($quantityInstallments < 0) { + throw new \InvalidArgumentException( + \sprintf('Installments quantity should be a non-negative integer (%s)', $quantityInstallments) + ); } - $quantityInstallments = intval( $quantityInstallments ); - if ($quantityInstallments > 99) { - throw new InvalidArgumentException( sprintf( 'Installments quantity should be less than 99 (%s)', - $quantityInstallments ) ); + throw new \InvalidArgumentException( + \sprintf('Installments quantity should be less than 99 (%s)', $quantityInstallments) + ); } $this->quantityInstallments = $quantityInstallments; @@ -206,89 +159,54 @@ public function setQtyInstallments( $quantityInstallments ) return $this; } - /** - * @return \RodrigoPedra\ClearSaleID\Entity\Request\Card - */ - public function getCard() + public function getCard(): ?Card { return $this->card; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Card $card - * - * @return $this - */ - public function setCard( Card $card ) + public function setCard(Card $card): self { $this->card = $card; return $this; } - /** - * @return string - */ - public function getLegalDocument() + public function getLegalDocument(): ?string { return $this->legalDocument; } - /** - * @param string $legalDocument - * - * @return $this - */ - public function setLegalDocument( $legalDocument ) + public function setLegalDocument(string $legalDocument): self { $this->legalDocument = $legalDocument; return $this; } - /** - * @param \XMLWriter $XMLWriter - * - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - public function toXML( XMLWriter $XMLWriter ) + public function toXML(\XMLWriter $XMLWriter): void { - $XMLWriter->startElement( 'Pagamento' ); + $XMLWriter->startElement('Pagamento'); if ($this->sequential) { - $XMLWriter->writeElement( 'NumeroSequencial', $this->sequential ); - } - - if ($this->date) { - $XMLWriter->writeElement( 'Data', $this->date->format( self::DATE_TIME_FORMAT ) ); - } else { - throw new RequiredFieldException( 'Field Date of the Payment object is required' ); + $XMLWriter->writeElement('NumeroSequencial', $this->sequential); } - if (is_numeric( $this->amount ) && $this->amount >= 0.0) { - $XMLWriter->writeElement( 'Valor', $this->amount ); - } else { - throw new RequiredFieldException( 'Field Amount of the Payment object is required' ); - } - - if ($this->type) { - $XMLWriter->writeElement( 'TipoPagamentoID', $this->type ); - } else { - throw new RequiredFieldException( 'Field PaymentTypeID of the Payment object is required' ); - } + $XMLWriter->writeElement('Data', $this->date->format(self::DATE_TIME_FORMAT)); + $XMLWriter->writeElement('Valor', $this->amount); + $XMLWriter->writeElement('TipoPagamentoID', $this->type); if ($this->quantityInstallments) { - $XMLWriter->writeElement( 'QtdParcelas', $this->quantityInstallments ); + $XMLWriter->writeElement('QtdParcelas', $this->quantityInstallments); } if ($this->card) { - $this->card->toXML( $XMLWriter ); + $this->card->toXML($XMLWriter); } if ($this->legalDocument) { - $XMLWriter->writeElement( 'DocumentoLegal1', $this->legalDocument ); + $XMLWriter->writeElement('DocumentoLegal1', $this->legalDocument); } - $XMLWriter->endElement(); + $XMLWriter->endElement(); // Pagamento } } diff --git a/src/ClearSaleID/Entity/Request/Phone.php b/src/ClearSaleID/Entity/Request/Phone.php index 7f21873..63974ac 100755 --- a/src/ClearSaleID/Entity/Request/Phone.php +++ b/src/ClearSaleID/Entity/Request/Phone.php @@ -2,20 +2,17 @@ namespace RodrigoPedra\ClearSaleID\Entity\Request; -use InvalidArgumentException; use RodrigoPedra\ClearSaleID\Entity\XmlEntityInterface; -use RodrigoPedra\ClearSaleID\Exception\RequiredFieldException; -use XMLWriter; class Phone implements XmlEntityInterface { - const NAO_DEFINIDO = 0; - const RESIDENCIAL = 1; - const COMERCIAL = 2; - const RECADOS = 3; - const COBRANCA = 4; - const TEMPORARIO = 5; - const CELULAR = 6; + public const NAO_DEFINIDO = 0; + public const RESIDENCIAL = 1; + public const COMERCIAL = 2; + public const RECADOS = 3; + public const COBRANCA = 4; + public const TEMPORARIO = 5; + public const CELULAR = 6; private static $types = [ self::NAO_DEFINIDO, @@ -30,8 +27,8 @@ class Phone implements XmlEntityInterface /** @var int */ private $type; - /** @var string */ - private $ddi; + /** @var string|null */ + private $ddi = null; /** @var string */ private $ddd; @@ -39,44 +36,30 @@ class Phone implements XmlEntityInterface /** @var string */ private $number; - /** @var string */ - private $extension; - - /** - * @param int $type - * @param string $ddd - * @param string $number - * - * @return \RodrigoPedra\ClearSaleID\Entity\Request\Phone - */ - public static function create( $type, $ddd, $number ) - { - $instance = new self; + /** @var string|null */ + private $extension = null; - $instance->setType( $type ); - $instance->setDDD( $ddd ); - $instance->setNumber( $number ); + public function __construct(int $type, string $ddd, string $number) + { + $this->setType($type); + $this->setDDD($ddd); + $this->setNumber($number); + } - return $instance; + public static function create(int $type, string $ddd, string $number): self + { + return new self($type, $ddd, $number); } - /** - * @return int - */ - public function getType() + public function getType(): int { return $this->type; } - /** - * @param int $type - * - * @return $this - */ - public function setType( $type ) + public function setType(int $type): self { - if (!in_array( intval( $type ), self::$types )) { - throw new InvalidArgumentException( sprintf( 'Invalid type (%s)', $type ) ); + if (! \in_array($type, self::$types)) { + throw new \InvalidArgumentException(\sprintf('Invalid type (%s)', $type)); } $this->type = $type; @@ -84,25 +67,17 @@ public function setType( $type ) return $this; } - /** - * @return string - */ - public function getDDI() + public function getDDI(): ?string { return $this->ddi; } - /** - * @param string $ddi - * - * @return $this - */ - public function setDDI( $ddi ) + public function setDDI(string $ddi): self { - $ddi = preg_replace( '/^0+|\D/', '', $ddi ); + $ddi = \preg_replace('/^0+|\D/', '', $ddi); - if (strlen( $ddi ) < 1 || strlen( $ddi ) > 3) { - throw new InvalidArgumentException( sprintf( 'Invalid DDI (%s)', $ddi ) ); + if (\strlen($ddi) < 1 || \strlen($ddi) > 3) { + throw new \InvalidArgumentException(\sprintf('Invalid DDI (%s)', $ddi)); } $this->ddi = $ddi; @@ -110,25 +85,17 @@ public function setDDI( $ddi ) return $this; } - /** - * @return string - */ - public function getDDD() + public function getDDD(): string { return $this->ddd; } - /** - * @param string $ddd - * - * @return $this - */ - public function setDDD( $ddd ) + public function setDDD(string $ddd): self { - $ddd = preg_replace( '/^0+|\D/', '', $ddd ); + $ddd = \preg_replace('/^0+|\D/', '', $ddd); - if (strlen( $ddd ) !== 2) { - throw new InvalidArgumentException( sprintf( 'Invalid DDD (%s)', $ddd ) ); + if (\strlen($ddd) !== 2) { + throw new \InvalidArgumentException(\sprintf('Invalid DDD (%s)', $ddd)); } $this->ddd = $ddd; @@ -136,25 +103,17 @@ public function setDDD( $ddd ) return $this; } - /** - * @return string - */ - public function getNumber() + public function getNumber(): string { return $this->number; } - /** - * @param string $number - * - * @return $this - */ - public function setNumber( $number ) + public function setNumber(string $number): self { - $number = preg_replace( '/^0+|\D/', '', $number ); + $number = \preg_replace('/^0+|\D/', '', $number); - if (strlen( $number ) !== 9 && strlen( $number ) !== 8) { - throw new InvalidArgumentException( sprintf( 'Invalid Number (%s)', $number ) ); + if (\strlen($number) !== 9 && \strlen($number) !== 8) { + throw new \InvalidArgumentException(\sprintf('Invalid Number (%s)', $number)); } $this->number = $number; @@ -162,66 +121,43 @@ public function setNumber( $number ) return $this; } - /** - * @return string - */ - public function getExtension() + public function getExtension(): ?string { return $this->extension; } - /** - * @param string $extension - * - * @return $this - */ - public function setExtension( $extension ) + public function setExtension(string $extension): self { - if (strlen( $extension ) > 5) { - throw new InvalidArgumentException( sprintf( 'Extension should be no longer than 5 characters (%s)', - $extension ) ); + $extension = \trim($extension); + + if (\strlen($extension) > 5) { + throw new \InvalidArgumentException( + \sprintf('Extension should be no longer than 5 characters (%s)', $extension) + ); } - $this->extension = $extension; + $this->extension = $extension ?: null; return $this; } - /** - * @param \XMLWriter $XMLWriter - * - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - public function toXML( XMLWriter $XMLWriter ) + public function toXML(\XMLWriter $XMLWriter): void { - $XMLWriter->startElement( 'Telefone' ); + $XMLWriter->startElement('Telefone'); - if (!is_null( $this->type )) { - $XMLWriter->writeElement( 'Tipo', $this->type ); - } else { - throw new RequiredFieldException( 'Field Type of the Phone object is required' ); - } + $XMLWriter->writeElement('Tipo', $this->type); if ($this->ddi) { - $XMLWriter->writeElement( 'DDI', $this->ddi ); + $XMLWriter->writeElement('DDI', $this->ddi); } - if ($this->ddd) { - $XMLWriter->writeElement( 'DDD', $this->ddd ); - } else { - throw new RequiredFieldException( 'Field DDD of the Phone object is required' ); - } - - if ($this->number) { - $XMLWriter->writeElement( 'Numero', $this->number ); - } else { - throw new RequiredFieldException( 'Field Number of the Phone object is required' ); - } + $XMLWriter->writeElement('DDD', $this->ddd); + $XMLWriter->writeElement('Numero', $this->number); if ($this->extension) { - $XMLWriter->writeElement( 'Ramal', $this->extension ); + $XMLWriter->writeElement('Ramal', $this->extension); } - $XMLWriter->endElement(); + $XMLWriter->endElement(); // Telefone } } diff --git a/src/ClearSaleID/Entity/Response/Order.php b/src/ClearSaleID/Entity/Response/Order.php index a8efa57..fea66a1 100755 --- a/src/ClearSaleID/Entity/Response/Order.php +++ b/src/ClearSaleID/Entity/Response/Order.php @@ -4,114 +4,80 @@ class Order { - const STATUS_APPROVED_AUTOMATICALLY = 'APA'; - const STATUS_REJECTED_BY_POLITICS = 'RPP'; - const STATUS_REJECTED_AUTOMATICALLY = 'RPA'; + public const STATUS_APPROVED_AUTOMATICALLY = 'APA'; + public const STATUS_REJECTED_BY_POLITICS = 'RPP'; + public const STATUS_REJECTED_AUTOMATICALLY = 'RPA'; /** @var string */ private $id; - /** @var int */ + /** @var float */ private $score; /** @var string */ private $status; - /** @var string */ + /** @var string|null */ private $quizURL; - /** - * Order constructor. - * - * @param int $id - * @param string $score - * @param string $status - * @param string $quizURL - */ - public function __construct( $id, $score, $status, $quizURL = '' ) + public function __construct(string $id, float $score, string $status, $quizURL = null) { - $this->id = $id; - $this->score = $score; + $this->id = $id; + $this->score = $score; $this->status = $status; - $this->setQuizURL( $quizURL ); + $this->setQuizURL($quizURL); } - /** - * @param string $value - */ - private function setQuizURL( $value ) + private function setQuizURL($value): void { - $value = (array)$value; - - if (count( $value ) === 0) { - $this->quizURL = ''; + $value = (array) $value; - return; + if (\count($value) === 0) { + $this->quizURL = null; + } else { + $this->quizURL = \trim($value[0]) ?: null; } - - $this->quizURL = trim( $value[ 0 ] ); } - /** - * @return string - */ - public function getId() + public function getId(): string { return $this->id; } - /** - * @return float - */ - public function getScore() + public function getScore(): float { - return floatval( $this->score ); + return $this->score; } - /** - * @return string - */ - public function getQuizURL() + public function getQuizURL(): ?string { return $this->quizURL; } - /** - * @return bool - */ - public function isApproved() + public function isApproved(): bool { - return in_array( $this->getStatus(), [ self::STATUS_APPROVED_AUTOMATICALLY ] ); + return $this->getStatus() === self::STATUS_APPROVED_AUTOMATICALLY; } - /** - * @return string - */ - public function getStatus() + public function getStatus(): string { return $this->status; } - /** - * @return bool - */ - public function isRejected() + public function isRejected(): bool { - return in_array( $this->getStatus(), [ + return \in_array($this->getStatus(), [ self::STATUS_REJECTED_BY_POLITICS, self::STATUS_REJECTED_AUTOMATICALLY, - ] ); + ]); } - /** - * @return bool - */ - public function hasValidStatus() + public function hasValidStatus(): bool { - return in_array( $this->getStatus(), [ + return \in_array($this->getStatus(), [ self::STATUS_APPROVED_AUTOMATICALLY, self::STATUS_REJECTED_BY_POLITICS, self::STATUS_REJECTED_AUTOMATICALLY, - ] ); + ]); } } diff --git a/src/ClearSaleID/Entity/Response/PackageStatus.php b/src/ClearSaleID/Entity/Response/PackageStatus.php index 81a8942..7ab1783 100755 --- a/src/ClearSaleID/Entity/Response/PackageStatus.php +++ b/src/ClearSaleID/Entity/Response/PackageStatus.php @@ -2,7 +2,6 @@ namespace RodrigoPedra\ClearSaleID\Entity\Response; -use Exception; use RodrigoPedra\ClearSaleID\Exception\EntityCodeNotFoundException; use RodrigoPedra\ClearSaleID\Exception\OrderAlreadySentException; use RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException; @@ -11,14 +10,14 @@ class PackageStatus { - const STATUS_CODE_SUCCESS = 0; - const STATUS_CODE_ENTITY_CODE_NOT_FOUND = 1; - const STATUS_CODE_INVALID_XML = 2; - const STATUS_CODE_XML_TRANSFORM_ERROR = 3; - const STATUS_CODE_INTERNAL_ERROR_4 = 4; - const STATUS_CODE_ORDER_ALREADY_SENT = 5; - const STATUS_CODE_INTERNAL_ERROR_6 = 6; - const STATUS_CODE_INTERNAL_ERROR_7 = 7; + public const STATUS_CODE_SUCCESS = 0; + public const STATUS_CODE_ENTITY_CODE_NOT_FOUND = 1; + public const STATUS_CODE_INVALID_XML = 2; + public const STATUS_CODE_XML_TRANSFORM_ERROR = 3; + public const STATUS_CODE_INTERNAL_ERROR_4 = 4; + public const STATUS_CODE_ORDER_ALREADY_SENT = 5; + public const STATUS_CODE_INTERNAL_ERROR_6 = 6; + public const STATUS_CODE_INTERNAL_ERROR_7 = 7; private static $statusCodesList = [ self::STATUS_CODE_SUCCESS, @@ -33,12 +32,12 @@ class PackageStatus private static $statusCodeExceptions = [ self::STATUS_CODE_ENTITY_CODE_NOT_FOUND => EntityCodeNotFoundException::class, - self::STATUS_CODE_INVALID_XML => XmlValidationException::class, - self::STATUS_CODE_XML_TRANSFORM_ERROR => XmlTransformException::class, - self::STATUS_CODE_INTERNAL_ERROR_4 => UnexpectedErrorException::class, - self::STATUS_CODE_ORDER_ALREADY_SENT => OrderAlreadySentException::class, - self::STATUS_CODE_INTERNAL_ERROR_6 => UnexpectedErrorException::class, - self::STATUS_CODE_INTERNAL_ERROR_7 => UnexpectedErrorException::class, + self::STATUS_CODE_INVALID_XML => XmlValidationException::class, + self::STATUS_CODE_XML_TRANSFORM_ERROR => XmlTransformException::class, + self::STATUS_CODE_INTERNAL_ERROR_4 => UnexpectedErrorException::class, + self::STATUS_CODE_ORDER_ALREADY_SENT => OrderAlreadySentException::class, + self::STATUS_CODE_INTERNAL_ERROR_6 => UnexpectedErrorException::class, + self::STATUS_CODE_INTERNAL_ERROR_7 => UnexpectedErrorException::class, ]; /** @var string */ @@ -50,73 +49,74 @@ class PackageStatus /** @var string */ private $message; - /** @var \RodrigoPedra\ClearSaleID\Entity\Response\Order */ - private $order; - - /** - * PackageStatus constructor. - * - * @param string $xml - * - * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException - * @throws \Exception - */ - public function __construct( $xml ) + /** @var \RodrigoPedra\ClearSaleID\Entity\Response\Order|null */ + private $order = null; + + public function __construct(string $xml) { try { // FIX PHP Warning: Parser error : Document labelled UTF-16 but has UTF-8 content - $xml = preg_replace( '/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $xml ); - - // Convert string to SimpleXMLElement - $object = simplexml_load_string( $xml ); + $xml = \preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $xml); - // Convert SimpleXMLElement to stdClass - $object = json_decode( json_encode( $object ) ); + $object = \simplexml_load_string($xml); + $object = \json_decode(\json_encode($object)); - $packageStatusObject = isset( $object->PackageStatus ) ? $object->PackageStatus : null; + $packageStatusObject = isset($object->PackageStatus) ? $object->PackageStatus : null; - if (is_null( $packageStatusObject )) { - throw new UnexpectedErrorException( 'Invalid response from webservice', 0 ); + if (\is_null($packageStatusObject)) { + throw new UnexpectedErrorException('Invalid response from webservice', 0); } - $this->setTransactionId( $packageStatusObject->TransactionID ); - $this->setStatusCode( $packageStatusObject->StatusCode ); - $this->setMessage( $packageStatusObject->Message ); + $this->setTransactionId($packageStatusObject->TransactionID); + $this->setStatusCode($packageStatusObject->StatusCode); + $this->setMessage($packageStatusObject->Message); - if (isset( $packageStatusObject->Pedidos )) { - $this->setOrder( $packageStatusObject->Pedidos ); + if (isset($packageStatusObject->Pedidos)) { + $this->setOrder($packageStatusObject->Pedidos); } - } catch ( Exception $ex ) { - throw new UnexpectedErrorException( 'Invalid response from webservice', 0, $ex ); + } catch (\Throwable $exception) { + throw new UnexpectedErrorException('Invalid response from webservice', 0, $exception); } - $this->validateStatusCode(); + $this->guardStatusCode(); + } + + public function getStatusCode(): int + { + return $this->statusCode; + } + + public function getMessage(): string + { + return $this->message; + } + + public function getTransactionId(): string + { + return $this->transactionId; + } + + public function getOrder(): ?Order + { + return $this->order; + } + + public function isSuccessful(): bool + { + return $this->getStatusCode() === self::STATUS_CODE_SUCCESS; } - /** - * @param string $transactionId - * - * @return $this - */ - private function setTransactionId( $transactionId ) + private function setTransactionId(string $transactionId): self { $this->transactionId = $transactionId; return $this; } - /** - * @param int $statusCode - * - * @return $this - * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException - */ - private function setStatusCode( $statusCode ) + private function setStatusCode(int $statusCode): self { - $statusCode = intval( $statusCode ); - - if (!in_array( $statusCode, self::$statusCodesList )) { - throw new UnexpectedErrorException( sprintf( 'Invalid Status Code (%s)', $statusCode ) ); + if (! \in_array($statusCode, self::$statusCodesList)) { + throw new UnexpectedErrorException(\sprintf('Invalid Status Code (%s)', $statusCode)); } $this->statusCode = $statusCode; @@ -124,24 +124,14 @@ private function setStatusCode( $statusCode ) return $this; } - /** - * @param string $message - * - * @return $this - */ - private function setMessage( $message ) + private function setMessage(string $message): self { - $this->message = trim( $message ); + $this->message = \trim($message); return $this; } - /** - * @param $orderObject - * - * @return $this - */ - private function setOrder( $orderObject ) + private function setOrder($orderObject): self { $this->order = new Order( $orderObject->Pedido->ID, @@ -153,61 +143,18 @@ private function setOrder( $orderObject ) return $this; } - /** - * @throws \Exception - */ - private function validateStatusCode() + private function guardStatusCode(): void { if (self::STATUS_CODE_SUCCESS === $this->getStatusCode()) { return; } if (self::STATUS_CODE_ENTITY_CODE_NOT_FOUND === $this->getStatusCode()) { - $this->setMessage( 'entity code not found' ); + $this->setMessage('entity code not found'); } - $exceptionClass = static::$statusCodeExceptions[ $this->getStatusCode() ]; - - throw new $exceptionClass( $this->getMessage(), $this->getStatusCode() ); - } - - /** - * @return int - */ - public function getStatusCode() - { - return intval( $this->statusCode ); - } - - /** - * @return string - */ - public function getMessage() - { - return $this->message; - } - - /** - * @return string - */ - public function getTransactionId() - { - return $this->transactionId; - } - - /** - * @return \RodrigoPedra\ClearSaleID\Entity\Response\Order - */ - public function getOrder() - { - return $this->order; - } + $exceptionClass = static::$statusCodeExceptions[$this->getStatusCode()]; - /** - * @return bool - */ - public function isSuccessful() - { - return $this->getStatusCode() === self::STATUS_CODE_SUCCESS; + throw new $exceptionClass($this->getMessage(), $this->getStatusCode()); } } diff --git a/src/ClearSaleID/Entity/Response/UpdateOrderStatus.php b/src/ClearSaleID/Entity/Response/UpdateOrderStatus.php index 4ef64bd..ff503f9 100755 --- a/src/ClearSaleID/Entity/Response/UpdateOrderStatus.php +++ b/src/ClearSaleID/Entity/Response/UpdateOrderStatus.php @@ -2,13 +2,12 @@ namespace RodrigoPedra\ClearSaleID\Entity\Response; -use Exception; use RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException; use RodrigoPedra\ClearSaleID\Exception\UpdateOrderStatusException; class UpdateOrderStatus { - const STATUS_CODE_OK = 'OK'; + public const STATUS_CODE_OK = 'OK'; /** @var string */ private $statusCode; @@ -16,96 +15,63 @@ class UpdateOrderStatus /** @var string */ private $message; - /** - * UpdateOrderStatus constructor. - * - * @param string $xml - * - * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException - * @throws \RodrigoPedra\ClearSaleID\Exception\UpdateOrderStatusException - */ - public function __construct( $xml ) + public function __construct(string $xml) { try { // FIX PHP Warning: Parser error : Document labelled UTF-16 but has UTF-8 content - $xml = preg_replace( '/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $xml ); + $xml = \preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $xml); - // Convert string to SimpleXMLElement - $object = simplexml_load_string( $xml ); + $object = \simplexml_load_string($xml); + $updateOrderStatusObject = \json_decode(\json_encode($object)); - // Convert SimpleXMLElement to stdClass - $updateOrderStatusObject = json_decode( json_encode( $object ) ); - - if (is_null( $updateOrderStatusObject )) { - throw new UnexpectedErrorException( sprintf( 'Invalid response from webservice (%s)', $xml ), 0 ); + if (\is_null($updateOrderStatusObject)) { + throw new UnexpectedErrorException(\sprintf('Invalid response from webservice (%s)', $xml), 0); } - $this->setStatusCode( $updateOrderStatusObject->StatusCode ); - $this->setMessage( $updateOrderStatusObject->Message ); - } catch ( Exception $ex ) { - throw new UnexpectedErrorException( sprintf( 'Invalid response from webservice (%s)', $xml ), 0, $ex ); + $this->setStatusCode($updateOrderStatusObject->StatusCode); + $this->setMessage($updateOrderStatusObject->Message); + } catch (\Throwable $exception) { + throw new UnexpectedErrorException(\sprintf('Invalid response from webservice (%s)', $xml), 0, $exception); } - $this->validateStatusCode(); + $this->guardStatusCode(); } - /** - * @param int $statusCode - * - * @return $this - */ - private function setStatusCode( $statusCode ) + public function getStatusCode(): string { - $this->statusCode = $statusCode; - - return $this; + return $this->statusCode; } - /** - * @param string $message - * - * @return $this - */ - private function setMessage( $message ) + public function getMessage(): string { - $this->message = trim( $message ); - - return $this; + return $this->message; } - /** - * @throws \RodrigoPedra\ClearSaleID\Exception\UpdateOrderStatusException - */ - private function validateStatusCode() + public function isSuccessful(): bool { - if ($this->getStatusCode() === self::STATUS_CODE_OK) { - return; - } - - throw new UpdateOrderStatusException( sprintf( 'Update order status failed (%s)', $this->getStatusCode() ) ); + return $this->getStatusCode() === self::STATUS_CODE_OK; } - /** - * @return string - */ - public function getStatusCode() + private function setStatusCode(string $statusCode): self { - return $this->statusCode; + $this->statusCode = $statusCode; + + return $this; } - /** - * @return string - */ - public function getMessage() + private function setMessage(string $message): self { - return $this->message; + $this->message = \trim($message); + + return $this; } - /** - * @return bool - */ - public function isSuccessful() + private function guardStatusCode(): void { - return $this->getStatusCode() === self::STATUS_CODE_OK; + if ($this->getStatusCode() === self::STATUS_CODE_OK) { + return; + } + + throw new UpdateOrderStatusException(\sprintf('Update order status failed (%s)', $this->getStatusCode())); } } diff --git a/src/ClearSaleID/Entity/XmlEntityInterface.php b/src/ClearSaleID/Entity/XmlEntityInterface.php index 0dcaf30..4455971 100644 --- a/src/ClearSaleID/Entity/XmlEntityInterface.php +++ b/src/ClearSaleID/Entity/XmlEntityInterface.php @@ -2,14 +2,9 @@ namespace RodrigoPedra\ClearSaleID\Entity; -use XMLWriter; - interface XmlEntityInterface { - const DATE_TIME_FORMAT = 'Y-m-d\TH:i:s'; + public const DATE_TIME_FORMAT = 'Y-m-d\TH:i:s'; - /** - * @param \XMLWriter $XMLWriter - */ - public function toXML( XMLWriter $XMLWriter ); + public function toXML(\XMLWriter $XMLWriter); } diff --git a/src/ClearSaleID/Environment/AbstractEnvironment.php b/src/ClearSaleID/Environment/AbstractEnvironment.php index cbde4c2..b837186 100644 --- a/src/ClearSaleID/Environment/AbstractEnvironment.php +++ b/src/ClearSaleID/Environment/AbstractEnvironment.php @@ -21,74 +21,51 @@ abstract class AbstractEnvironment /** @var \Psr\Log\LoggerInterface|null */ private $logger; - /** - * AbstractEnvironment constructor. - * - * @param string $entityCode - * @param \Psr\Log\LoggerInterface|null $logger - */ - public function __construct( $entityCode, LoggerInterface $logger = null ) - { + public function __construct( + string $regularEndpoint, + string $extendedEnpoint, + string $entityCode, + ?LoggerInterface $logger + ) { + $this->regularEndpoint = $regularEndpoint; + $this->extendedEnpoint = $extendedEnpoint; $this->entityCode = $entityCode; - $this->logger = $logger; - $this->debug = false; + $this->logger = $logger; + $this->debug = false; } - /** - * @return string - */ - public function getEntityCode() + public function getEntityCode(): string { return $this->entityCode; } - /** - * @return string - */ - public function getRegularEndpoint() + public function getRegularEndpoint(): string { return $this->regularEndpoint; } - /** - * @return string - */ - public function getExtendedEndpoint() + public function getExtendedEndpoint(): string { return $this->extendedEnpoint; } - /** - * @param string $message - * @param array $context - */ - public function log( $message, array $context = [] ) + public function log(string $message, array $context = []): void { - if (!$this->isDebug()) { + if (! $this->isDebug()) { return; } - if (!$this->logger) { - return; + if ($this->logger) { + $this->logger->debug($message, $context); } - - $this->logger->debug( $message, $context ); } - /** - * @return bool - */ - public function isDebug() + public function isDebug(): bool { - return (bool)$this->debug; + return $this->debug; } - /** - * @param bool $debug - * - * @return $this - */ - public function setDebug( $debug = true ) + public function setDebug(bool $debug = true): self { $this->debug = $debug; diff --git a/src/ClearSaleID/Environment/Production.php b/src/ClearSaleID/Environment/Production.php index c29b081..6628046 100644 --- a/src/ClearSaleID/Environment/Production.php +++ b/src/ClearSaleID/Environment/Production.php @@ -6,17 +6,13 @@ class Production extends AbstractEnvironment { - /** - * Production constructor. - * - * @param string $entityCode - * @param \Psr\Log\LoggerInterface|null $logger - */ - public function __construct( $entityCode, LoggerInterface $logger = null ) + public function __construct(string $entityCode, ?LoggerInterface $logger = null) { - parent::__construct( $entityCode, $logger ); - - $this->regularEndpoint = 'https://integracao.clearsale.com.br/service.asmx'; - $this->extendedEnpoint = 'https://integracao.clearsale.com.br/ExtendedService.asmx'; + parent::__construct( + 'https://integracao.clearsale.com.br/service.asmx', + 'https://integracao.clearsale.com.br/ExtendedService.asmx', + $entityCode, + $logger + ); } } diff --git a/src/ClearSaleID/Environment/Sandbox.php b/src/ClearSaleID/Environment/Sandbox.php index 273e371..4e8ff3a 100644 --- a/src/ClearSaleID/Environment/Sandbox.php +++ b/src/ClearSaleID/Environment/Sandbox.php @@ -6,17 +6,13 @@ class Sandbox extends AbstractEnvironment { - /** - * Sandbox constructor. - * - * @param string $entityCode - * @param \Psr\Log\LoggerInterface|null $logger - */ - public function __construct( $entityCode, LoggerInterface $logger = null ) + public function __construct(string $entityCode, ?LoggerInterface $logger = null) { - parent::__construct( $entityCode, $logger ); - - $this->regularEndpoint = 'https://homologacao.clearsale.com.br/integracaov2/service.asmx'; - $this->extendedEnpoint = 'https://homologacao.clearsale.com.br/integracaov2/ExtendedService.asmx'; + parent::__construct( + 'https://homologacao.clearsale.com.br/integracaov2/service.asmx', + 'https://homologacao.clearsale.com.br/integracaov2/ExtendedService.asmx', + $entityCode, + $logger + ); } } diff --git a/src/ClearSaleID/Exception/EntityCodeNotFoundException.php b/src/ClearSaleID/Exception/EntityCodeNotFoundException.php index 6dca170..197f0a3 100644 --- a/src/ClearSaleID/Exception/EntityCodeNotFoundException.php +++ b/src/ClearSaleID/Exception/EntityCodeNotFoundException.php @@ -2,9 +2,6 @@ namespace RodrigoPedra\ClearSaleID\Exception; -use Exception; - -class EntityCodeNotFoundException extends Exception +class EntityCodeNotFoundException extends \RuntimeException { - } diff --git a/src/ClearSaleID/Exception/OrderAlreadySentException.php b/src/ClearSaleID/Exception/OrderAlreadySentException.php index c292477..f20e9c3 100644 --- a/src/ClearSaleID/Exception/OrderAlreadySentException.php +++ b/src/ClearSaleID/Exception/OrderAlreadySentException.php @@ -2,9 +2,6 @@ namespace RodrigoPedra\ClearSaleID\Exception; -use Exception; - -class OrderAlreadySentException extends Exception +class OrderAlreadySentException extends \RuntimeException { - } diff --git a/src/ClearSaleID/Exception/RequiredFieldException.php b/src/ClearSaleID/Exception/RequiredFieldException.php index 4e1488a..e5d94f3 100644 --- a/src/ClearSaleID/Exception/RequiredFieldException.php +++ b/src/ClearSaleID/Exception/RequiredFieldException.php @@ -2,9 +2,6 @@ namespace RodrigoPedra\ClearSaleID\Exception; -use Exception; - -class RequiredFieldException extends Exception +class RequiredFieldException extends \RuntimeException { - } diff --git a/src/ClearSaleID/Exception/TransactionFailedException.php b/src/ClearSaleID/Exception/TransactionFailedException.php new file mode 100644 index 0000000..0655a8e --- /dev/null +++ b/src/ClearSaleID/Exception/TransactionFailedException.php @@ -0,0 +1,7 @@ +integration = $integration; } @@ -43,35 +39,35 @@ public function __construct( Integration $integration ) /** * Método para envio de pedidos e retorno do status * - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Order $order - * + * @param \RodrigoPedra\ClearSaleID\Entity\Request\Order $order * @return string - * @throws \Exception + * @throws \SoapFault */ - public function analysis( OrderRequest $order ) + public function analysis(OrderRequest $order): string { - $packageStatus = $this->integration->sendOrder( $order ); + $packageStatus = $this->integration->sendOrder($order); - if (!$packageStatus->isSuccessful()) { - throw new Exception( sprintf( 'Transaction Failed! (statusCode: %s)', $packageStatus->getStatusCode() ) ); + if (! $packageStatus->isSuccessful()) { + throw new TransactionFailedException( + \sprintf('Transaction Failed! (statusCode: %s)', $packageStatus->getStatusCode()) + ); } - return $this->checkOrderStatus( $order->getId() ); + return $this->checkOrderStatus($order->getId()); } /** * Retorna o status de aprovação de um pedido * - * @param string $orderId - * + * @param string $orderId * @return string - * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException + * @throws \SoapFault */ - public function checkOrderStatus( $orderId ) + public function checkOrderStatus(string $orderId): string { - $this->packageStatusResponse = $this->integration->checkOrderStatus( $orderId ); + $this->packageStatusResponse = $this->integration->checkOrderStatus($orderId); - if (!$this->packageStatusResponse->getOrder()) { + if (! $this->packageStatusResponse->getOrder()) { // no order returned return self::ORDER_STATUS_NO_ORDER_RETURNED; } @@ -91,21 +87,19 @@ public function checkOrderStatus( $orderId ) /** * Método para atualizar o pedido com o status do pagamento * - * @param string $orderId - * @param string $newStatusCode - * @param string $notes - * + * @param string $orderId + * @param int $newStatusCode + * @param string $notes * @return boolean - * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException - * @throws \RodrigoPedra\ClearSaleID\Exception\UpdateOrderStatusException + * @throws \SoapFault */ - public function updateOrderStatus( $orderId, $newStatusCode, $notes = '' ) + public function updateOrderStatus(string $orderId, int $newStatusCode, string $notes = ''): bool { - if (!in_array( $newStatusCode, self::$updateOrderStatusList )) { - throw new InvalidArgumentException( sprintf( 'Invalid new status code (%s)', $newStatusCode ) ); + if (! \in_array($newStatusCode, self::$updateOrderStatusList)) { + throw new \InvalidArgumentException(\sprintf('Invalid new status code (%s)', $newStatusCode)); } - $this->updateOrderStatusResponse = $this->integration->updateOrderStatus( $orderId, $newStatusCode, $notes ); + $this->updateOrderStatusResponse = $this->integration->updateOrderStatus($orderId, $newStatusCode, $notes); return true; } @@ -115,7 +109,7 @@ public function updateOrderStatus( $orderId, $newStatusCode, $notes = '' ) * * @return \RodrigoPedra\ClearSaleID\Entity\Response\PackageStatus */ - public function getPackageStatus() + public function getPackageStatus(): PackageStatus { return $this->packageStatusResponse; } @@ -125,7 +119,7 @@ public function getPackageStatus() * * @return \RodrigoPedra\ClearSaleID\Entity\Response\UpdateOrderStatus */ - public function getUpdateOrderStatus() + public function getUpdateOrderStatus(): UpdateOrderStatus { return $this->updateOrderStatusResponse; } diff --git a/src/ClearSaleID/Service/Connector.php b/src/ClearSaleID/Service/Connector.php index d9375f7..fd25f2b 100755 --- a/src/ClearSaleID/Service/Connector.php +++ b/src/ClearSaleID/Service/Connector.php @@ -3,7 +3,6 @@ namespace RodrigoPedra\ClearSaleID\Service; use RodrigoPedra\ClearSaleID\Environment\AbstractEnvironment; -use SoapClient; class Connector { @@ -16,59 +15,52 @@ class Connector /** @var boolean */ private $usesRegularEndpoint; - /** - * Connector constructor. - * - * @param \RodrigoPedra\ClearSaleID\Environment\AbstractEnvironment $environment - */ - public function __construct( AbstractEnvironment $environment ) + public function __construct(AbstractEnvironment $environment) { - $this->environment = $environment; + $this->environment = $environment; $this->usesRegularEndpoint = true; - $this->client = null; + $this->client = null; } /** - * @param string $function + * @param string $function * @param $parameters - * @param bool $usesRegularEndpoint - * + * @param bool $usesRegularEndpoint * @return mixed + * @throws \SoapFault */ - public function doRequest( $function, $parameters, $usesRegularEndpoint = true ) + public function doRequest(string $function, $parameters, bool $usesRegularEndpoint = true) { - $client = ( $usesRegularEndpoint === true ) + $client = $usesRegularEndpoint ? $this->useRegularEndpoint()->getClient() : $this->useExtendedEndpoint()->getClient(); - $arguments = [ $function => $parameters ]; - $options = [ 'location' => $this->getEndpoint() ]; + $arguments = [$function => $parameters]; + $options = ['location' => $this->getEndpoint()]; - $this->environment->log( 'Connector@doRequest: Request', compact( 'arguments', 'options' ) ); + $this->environment->log('Connector@doRequest: Request', \compact('arguments', 'options')); - $response = $client->__soapCall( $function, $arguments, $options ); + $response = $client->__soapCall($function, $arguments, $options); - $this->environment->log( 'Connector@doRequest: Response', compact( 'response' ) ); + $this->environment->log('Connector@doRequest: Response', \compact('response')); return $response; } /** * @return \SoapClient + * @throws \SoapFault */ - private function getClient() + private function getClient(): \SoapClient { - if (is_null( $this->client )) { - $this->client = new SoapClient( $this->getEndpoint() . '?WSDL' ); + if (\is_null($this->client)) { + $this->client = new \SoapClient($this->getEndpoint() . '?WSDL'); } return $this->client; } - /** - * @return string - */ - private function getEndpoint() + private function getEndpoint(): string { if ($this->usesRegularEndpoint) { return $this->environment->getRegularEndpoint(); @@ -77,12 +69,9 @@ private function getEndpoint() return $this->environment->getExtendedEndpoint(); } - /** - * @return $this - */ - private function useRegularEndpoint() + private function useRegularEndpoint(): self { - if ($this->usesRegularEndpoint === false) { + if (! $this->usesRegularEndpoint) { $this->client = null; } @@ -91,12 +80,9 @@ private function useRegularEndpoint() return $this; } - /** - * @return $this - */ - private function useExtendedEndpoint() + private function useExtendedEndpoint(): self { - if ($this->usesRegularEndpoint === true) { + if ($this->usesRegularEndpoint) { $this->client = null; } @@ -105,20 +91,13 @@ private function useExtendedEndpoint() return $this; } - /** - * @return string - */ - public function getEntityCode() + public function getEntityCode(): string { return $this->environment->getEntityCode(); } - /** - * @param string $message - * @param array $context - */ - public function log( $message, array $context = [] ) + public function log(string $message, array $context = []): void { - $this->environment->log( $message, $context ); + $this->environment->log($message, $context); } } diff --git a/src/ClearSaleID/Service/Integration.php b/src/ClearSaleID/Service/Integration.php index 0ed8821..ebf7a9d 100755 --- a/src/ClearSaleID/Service/Integration.php +++ b/src/ClearSaleID/Service/Integration.php @@ -5,19 +5,13 @@ use RodrigoPedra\ClearSaleID\Entity\Request\Order as OrderRequest; use RodrigoPedra\ClearSaleID\Entity\Response\PackageStatus; use RodrigoPedra\ClearSaleID\Entity\Response\UpdateOrderStatus; -use XMLWriter; class Integration { /** @var \RodrigoPedra\ClearSaleID\Service\Connector */ protected $connector; - /** - * Construtor para gerar a integração com a ClearSale - * - * @param \RodrigoPedra\ClearSaleID\Service\Connector $connector - */ - public function __construct( Connector $connector ) + public function __construct(Connector $connector) { $this->connector = $connector; } @@ -25,103 +19,91 @@ public function __construct( Connector $connector ) /** * Método para envio de um pedido * - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Order $order - * + * @param \RodrigoPedra\ClearSaleID\Entity\Request\Order $order * @return \RodrigoPedra\ClearSaleID\Entity\Response\PackageStatus - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException + * @throws \SoapFault */ - public function sendOrder( OrderRequest $order ) + public function sendOrder(OrderRequest $order): PackageStatus { - - $function = 'SubmitInfo'; + $function = 'SubmitInfo'; $parameters = [ 'entityCode' => $this->connector->getEntityCode(), - 'xmlDados' => $this->createRequestOrderXML( $order ), + 'xmlDados' => $this->createRequestOrderXML($order), ]; - $response = $this->connector->doRequest( $function, $parameters ); + $response = $this->connector->doRequest($function, $parameters); - $packageStatusResponse = new PackageStatus( $response->SubmitInfoResult ); + $packageStatusResponse = new PackageStatus($response->SubmitInfoResult); - $this->connector->log( 'Integration@sendOrder', compact( 'packageStatusResponse' ) ); + $this->connector->log('Integration@sendOrder', \compact('packageStatusResponse')); return $packageStatusResponse; } - /** - * @param \RodrigoPedra\ClearSaleID\Entity\Request\Order $order - * - * @return string - * @throws \RodrigoPedra\ClearSaleID\Exception\RequiredFieldException - */ - private function createRequestOrderXML( OrderRequest $order ) - { - $xmlWriter = new XMLWriter; - - $xmlWriter->openMemory(); - $xmlWriter->startDocument( '1.0', 'UTF-8' ); - - $order->toXML( $xmlWriter ); - - $xmlWriter->endDocument(); - - return $xmlWriter->outputMemory( true ); - } - /** * Retorna o status de um pedido * - * @param string $orderId - * + * @param string $orderId * @return \RodrigoPedra\ClearSaleID\Entity\Response\PackageStatus - * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException + * @throws \SoapFault */ - public function checkOrderStatus( $orderId ) + public function checkOrderStatus(string $orderId): PackageStatus { - $function = 'CheckOrderStatus'; + $function = 'CheckOrderStatus'; $parameters = [ - 'entityCode' => $this->connector->getEntityCode(), - 'pedidoIDCliente' => $orderId + 'entityCode' => $this->connector->getEntityCode(), + 'pedidoIDCliente' => $orderId, ]; - $response = $this->connector->doRequest( $function, $parameters ); + $response = $this->connector->doRequest($function, $parameters); - $packageStatusResponse = new PackageStatus( $response->CheckOrderStatusResult ); + $packageStatusResponse = new PackageStatus($response->CheckOrderStatusResult); - $this->connector->log( 'Integration@checkOrderStatus', compact( 'packageStatusResponse' ) ); + $this->connector->log('Integration@checkOrderStatus', \compact('packageStatusResponse')); return $packageStatusResponse; } /** - * Método que atualiza o status do pedido para o status recebido no parametro statusPedido - * - * @param string $orderId - * @param int $newStatusId - * @param string $notes + * Método que atualiza o status do pedido para o status recebido no parâmetro statusPedido * + * @param string $orderId + * @param int $newStatusId + * @param string $notes * @return \RodrigoPedra\ClearSaleID\Entity\Response\UpdateOrderStatus - * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException - * @throws \RodrigoPedra\ClearSaleID\Exception\UpdateOrderStatusException + * @throws \SoapFault */ - public function updateOrderStatus( $orderId, $newStatusId, $notes = '' ) + public function updateOrderStatus(string $orderId, int $newStatusId, string $notes = ''): UpdateOrderStatus { - $function = 'UpdateOrderStatus'; + $function = 'UpdateOrderStatus'; $parameters = [ - 'entityCode' => $this->connector->getEntityCode(), - 'orderId' => $orderId, + 'entityCode' => $this->connector->getEntityCode(), + 'orderId' => $orderId, 'newStatusId' => $newStatusId, - 'obs' => substr( trim( $notes ), 0, 50 ), + 'obs' => \substr(\trim($notes), 0, 50), ]; // false indicates this method uses extended endpoint - $response = $this->connector->doRequest( $function, $parameters, false ); + $response = $this->connector->doRequest($function, $parameters, false); - $updateOrderStatusResponse = new UpdateOrderStatus( $response->UpdateOrderStatusResult ); + $updateOrderStatusResponse = new UpdateOrderStatus($response->UpdateOrderStatusResult); - $this->connector->log( 'Integration@updateOrderStatus', compact( 'updateOrderStatusResponse' ) ); + $this->connector->log('Integration@updateOrderStatus', \compact('updateOrderStatusResponse')); return $updateOrderStatusResponse; } + + private function createRequestOrderXML(OrderRequest $order): string + { + $xmlWriter = new \XMLWriter(); + + $xmlWriter->openMemory(); + $xmlWriter->startDocument('1.0', 'UTF-8'); + + $order->toXML($xmlWriter); + + $xmlWriter->endDocument(); + + return $xmlWriter->outputMemory(true); + } } diff --git a/tests/ClearSale/Entity/Request/AddressTest.php b/tests/ClearSale/Entity/Request/AddressTest.php deleted file mode 100644 index 6f3b61e..0000000 --- a/tests/ClearSale/Entity/Request/AddressTest.php +++ /dev/null @@ -1,58 +0,0 @@ -address = AddressFixture::createAddress(); - } - - protected function tearDown() - { - parent::tearDown(); - - $this->address = null; - } - - /** @test */ - public function testAddress() - { - $this->assertSame( 'Rua José de Oliveira Coutinho', $this->address->getStreet() ); - $this->assertSame( 'apto. 500', $this->address->getComplement() ); - $this->assertSame( '151', $this->address->getNumber() ); - $this->assertSame( 'Barra Funda', $this->address->getCounty() ); - $this->assertSame( 'Brasil', $this->address->getCountry() ); - $this->assertSame( 'São Paulo', $this->address->getCity() ); - $this->assertSame( 'SP', $this->address->getState() ); - $this->assertSame( '01144020', $this->address->getZipCode() ); - } - - /** @test */ - public function testAddressToXml() - { - $outputXML = $this->generateXML( $this->address ); - $expectedXmlFile = __DIR__ . '/../../../data/address.xml'; - - $this->assertXmlStringEqualsXmlFile( $expectedXmlFile, $outputXML ); - } - - private function generateXML( XmlEntityInterface $xmlEntity ) - { - $xmlWriter = new \XMLWriter(); - $xmlWriter->openMemory(); - $xmlWriter->setIndent( false ); - - $xmlEntity->toXML( $xmlWriter ); - - return $xmlWriter->outputMemory( true ); - } -} diff --git a/tests/ClearSale/Entity/Request/ItemTest.php b/tests/ClearSale/Entity/Request/ItemTest.php deleted file mode 100644 index 896177e..0000000 --- a/tests/ClearSale/Entity/Request/ItemTest.php +++ /dev/null @@ -1,54 +0,0 @@ -item = ItemFixture::createItem(); - } - - protected function tearDown() - { - parent::tearDown(); - - $this->item = null; - } - - /** @test */ - public function testItem() - { - $this->assertSame( 1, $this->item->getId() ); - $this->assertSame( 'Adaptador USB', $this->item->getName() ); - $this->assertSame( 10.0, $this->item->getValue() ); - $this->assertSame( 1, $this->item->getQuantity() ); - } - - /** @test */ - public function testItemToXml() - { - $outputXML = $this->generateXML( $this->item ); - $expectedXmlFile = __DIR__ . '/../../../data/item.xml'; - - $this->assertXmlStringEqualsXmlFile( $expectedXmlFile, $outputXML ); - } - - private function generateXML( XmlEntityInterface $xmlEntity ) - { - $xmlWriter = new \XMLWriter(); - $xmlWriter->openMemory(); - $xmlWriter->setIndent( false ); - - $xmlEntity->toXML( $xmlWriter ); - - return $xmlWriter->outputMemory( true ); - } -} diff --git a/tests/ClearSale/Entity/Response/OrderTest.php b/tests/ClearSale/Entity/Response/OrderTest.php deleted file mode 100644 index 268fb84..0000000 --- a/tests/ClearSale/Entity/Response/OrderTest.php +++ /dev/null @@ -1,54 +0,0 @@ -responseOrder = null; - } - - /** @test */ - public function testOrderResponseIdAndScore() - { - $id = '123'; - $score = 43.100; - - $this->responseOrder = new ResponseOrder( $id, 43.100, ResponseOrder::STATUS_APPROVED_AUTOMATICALLY ); - - $this->assertSame( $id, $this->responseOrder->getId() ); - $this->assertSame( $score, $this->responseOrder->getScore() ); - } - - /** - * @test - * - * @dataProvider statusProvider - * - * @param $status - * @param $expectedStatus - */ - public function testOrderResponseStatus( $status, $expectedStatus ) - { - $this->responseOrder = new ResponseOrder( '123', 43.100, $status ); - - $this->assertSame( $expectedStatus, $this->responseOrder->getStatus() ); - } - - public function statusProvider() - { - return [ - [ 'APA', ResponseOrder::STATUS_APPROVED_AUTOMATICALLY ], - [ 'RPP', ResponseOrder::STATUS_REJECTED_BY_POLITICS ], - [ 'RPA', ResponseOrder::STATUS_REJECTED_AUTOMATICALLY ], - ]; - } -} diff --git a/tests/ClearSale/Entity/Response/PackageStatusTest.php b/tests/ClearSale/Entity/Response/PackageStatusTest.php deleted file mode 100644 index 0f3b0bf..0000000 --- a/tests/ClearSale/Entity/Response/PackageStatusTest.php +++ /dev/null @@ -1,55 +0,0 @@ -packageStatusResponse = null; - $this->orderResponse = null; - } - - /** - * @test - * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException - */ - public function testCreateFromXML() - { - $responseXmlFile = __DIR__ . '/../../../data/package-status.xml'; - $xml = file_get_contents( $responseXmlFile ); - - $this->packageStatusResponse = new PackageStatus( $xml ); - - $this->assertSame( '55929546-3c1e-4be0-b561-03ab72e74b32', $this->packageStatusResponse->getTransactionId() ); - $this->assertSame( PackageStatus::STATUS_CODE_SUCCESS, $this->packageStatusResponse->getStatusCode() ); - $this->assertSame( 'OK', $this->packageStatusResponse->getMessage() ); - } - - /** - * @test - * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException - */ - public function testOrderResponse() - { - $responseXmlFile = __DIR__ . '/../../../data/package-status.xml'; - $xml = file_get_contents( $responseXmlFile ); - - $this->packageStatusResponse = new PackageStatus( $xml ); - $this->orderResponse = $this->packageStatusResponse->getOrder(); - - $this->assertSame( 'TEST-0A44444E6CEA465E85737421E651C70B', $this->orderResponse->getId() ); - $this->assertSame( Order::STATUS_APPROVED_AUTOMATICALLY, $this->orderResponse->getStatus() ); - $this->assertSame( 79.94, $this->orderResponse->getScore() ); - $this->assertEmpty( $this->orderResponse->getQuizURL() ); - } -} diff --git a/tests/ClearSale/Environment/AbstractEnvironmentTest.php b/tests/ClearSale/Environment/AbstractEnvironmentTest.php deleted file mode 100644 index 1cb735e..0000000 --- a/tests/ClearSale/Environment/AbstractEnvironmentTest.php +++ /dev/null @@ -1,69 +0,0 @@ -environment = $this->getMockBuilder( AbstractEnvironment::class ) - ->disableOriginalConstructor() - ->setMethods( [ 'getEntityCode', 'getRegularEndpoint', 'getExtendedEndpoint', 'isDebug' ] ) - ->getMockForAbstractClass(); - - $this->environment->expects( $this->any() ) - ->method( 'getEntityCode' ) - ->will( $this->returnValue( 'EC-123456' ) ); - - $this->environment->expects( $this->any() ) - ->method( 'getRegularEndpoint' ) - ->will( $this->returnValue( 'http://localhost/service.asmx' ) ); - - $this->environment->expects( $this->any() ) - ->method( 'getExtendedEndpoint' ) - ->will( $this->returnValue( 'http://localhost/extended.asmx' ) ); - - $this->environment->expects( $this->any() ) - ->method( 'isDebug' ) - ->will( $this->returnValue( true ) ); - } - - protected function tearDown() - { - parent::tearDown(); - - $this->environment = null; - } - - /** @test */ - public function testEntityCode() - { - $this->assertSame( 'EC-123456', $this->environment->getEntityCode() ); - } - - /** @test */ - public function testWebServiceRegularUrl() - { - $this->assertSame( 'http://localhost/service.asmx', $this->environment->getRegularEndpoint() ); - } - - /** @test */ - public function testWebServiceExtendedUrl() - { - $this->assertSame( 'http://localhost/extended.asmx', $this->environment->getExtendedEndpoint() ); - } - - /** @test */ - public function testIsDebugTrue() - { - $this->assertTrue( $this->environment->isDebug() ); - } -} diff --git a/tests/ClearSaleID/Entity/Request/AddressTest.php b/tests/ClearSaleID/Entity/Request/AddressTest.php new file mode 100644 index 0000000..a15824d --- /dev/null +++ b/tests/ClearSaleID/Entity/Request/AddressTest.php @@ -0,0 +1,58 @@ +address = AddressFixture::createAddress(); + } + + protected function tearDown() + { + parent::tearDown(); + + $this->address = null; + } + + /** @test */ + public function testAddress() + { + $this->assertSame('Rua José de Oliveira Coutinho', $this->address->getStreet()); + $this->assertSame('apto. 500', $this->address->getComplement()); + $this->assertSame('151', $this->address->getNumber()); + $this->assertSame('Barra Funda', $this->address->getCounty()); + $this->assertSame('Brasil', $this->address->getCountry()); + $this->assertSame('São Paulo', $this->address->getCity()); + $this->assertSame('SP', $this->address->getState()); + $this->assertSame('01144020', $this->address->getZipCode()); + } + + /** @test */ + public function testAddressToXml() + { + $outputXML = $this->generateXML($this->address); + $expectedXmlFile = __DIR__ . '/../../../data/address.xml'; + + $this->assertXmlStringEqualsXmlFile($expectedXmlFile, $outputXML); + } + + private function generateXML(XmlEntityInterface $xmlEntity) + { + $xmlWriter = new \XMLWriter(); + $xmlWriter->openMemory(); + $xmlWriter->setIndent(false); + + $xmlEntity->toXML($xmlWriter); + + return $xmlWriter->outputMemory(true); + } +} diff --git a/tests/ClearSale/Entity/Request/CustomerBillingDataTest.php b/tests/ClearSaleID/Entity/Request/CustomerBillingDataTest.php similarity index 50% rename from tests/ClearSale/Entity/Request/CustomerBillingDataTest.php rename to tests/ClearSaleID/Entity/Request/CustomerBillingDataTest.php index e3e2c04..b764e39 100644 --- a/tests/ClearSale/Entity/Request/CustomerBillingDataTest.php +++ b/tests/ClearSaleID/Entity/Request/CustomerBillingDataTest.php @@ -1,14 +1,14 @@ customer->getPhones(); - $phone = $phones[ 0 ]; - - $this->assertSame( '1', $this->customer->getId() ); - $this->assertSame( AbstractCustomer::TYPE_PESSOA_FISICA, $this->customer->getType() ); - $this->assertSame( 'Fulano da Silva', $this->customer->getName() ); - $this->assertInstanceOf( Address::class, $this->customer->getAddress() ); - $this->assertInstanceOf( Phone::class, $phone ); - $this->assertInstanceOf( DateTime::class, $this->customer->getBirthDate() ); + $phone = $phones[0]; + + $this->assertSame('1', $this->customer->getId()); + $this->assertSame(AbstractCustomer::TYPE_PESSOA_FISICA, $this->customer->getType()); + $this->assertSame('Fulano da Silva', $this->customer->getName()); + $this->assertInstanceOf(Address::class, $this->customer->getAddress()); + $this->assertInstanceOf(Phone::class, $phone); + $this->assertInstanceOf(DateTime::class, $this->customer->getBirthDate()); } /** @test */ public function testCustomerBillingDataToXml() { - $outputXML = $this->generateXML( $this->customer ); + $outputXML = $this->generateXML($this->customer); $expectedXmlFile = __DIR__ . '/../../../data/customer-billing-data.xml'; - $this->assertXmlStringEqualsXmlFile( $expectedXmlFile, $outputXML ); + $this->assertXmlStringEqualsXmlFile($expectedXmlFile, $outputXML); } - private function generateXML( XmlEntityInterface $xmlEntity ) + private function generateXML(XmlEntityInterface $xmlEntity) { $xmlWriter = new \XMLWriter(); $xmlWriter->openMemory(); - $xmlWriter->setIndent( false ); + $xmlWriter->setIndent(false); - $xmlEntity->toXML( $xmlWriter ); + $xmlEntity->toXML($xmlWriter); - return $xmlWriter->outputMemory( true ); + return $xmlWriter->outputMemory(true); } } diff --git a/tests/ClearSale/Entity/Request/CustomerShippingDataTest.php b/tests/ClearSaleID/Entity/Request/CustomerShippingDataTest.php similarity index 54% rename from tests/ClearSale/Entity/Request/CustomerShippingDataTest.php rename to tests/ClearSaleID/Entity/Request/CustomerShippingDataTest.php index 7b280be..f3edc91 100644 --- a/tests/ClearSale/Entity/Request/CustomerShippingDataTest.php +++ b/tests/ClearSaleID/Entity/Request/CustomerShippingDataTest.php @@ -1,13 +1,13 @@ customer->getPhones(); - $phone = $phones[ 0 ]; + $phone = $phones[0]; - $this->assertSame( '1', $this->customer->getId() ); - $this->assertSame( AbstractCustomer::TYPE_PESSOA_FISICA, $this->customer->getType() ); - $this->assertSame( 'Fulano da Silva', $this->customer->getName() ); - $this->assertInstanceOf( Address::class, $this->customer->getAddress() ); - $this->assertInstanceOf( Phone::class, $phone ); + $this->assertSame('1', $this->customer->getId()); + $this->assertSame(AbstractCustomer::TYPE_PESSOA_FISICA, $this->customer->getType()); + $this->assertSame('Fulano da Silva', $this->customer->getName()); + $this->assertInstanceOf(Address::class, $this->customer->getAddress()); + $this->assertInstanceOf(Phone::class, $phone); } /** @test */ public function testCustomerShippingDataToXml() { - $outputXML = $this->generateXML( $this->customer ); + $outputXML = $this->generateXML($this->customer); $expectedXmlFile = __DIR__ . '/../../../data/customer-shipping-data.xml'; - $this->assertXmlStringEqualsXmlFile( $expectedXmlFile, $outputXML ); + $this->assertXmlStringEqualsXmlFile($expectedXmlFile, $outputXML); } - private function generateXML( XmlEntityInterface $xmlEntity ) + private function generateXML(XmlEntityInterface $xmlEntity) { $xmlWriter = new \XMLWriter(); $xmlWriter->openMemory(); - $xmlWriter->setIndent( false ); + $xmlWriter->setIndent(false); - $xmlEntity->toXML( $xmlWriter ); + $xmlEntity->toXML($xmlWriter); - return $xmlWriter->outputMemory( true ); + return $xmlWriter->outputMemory(true); } } diff --git a/tests/ClearSale/Entity/Request/FingerPrintTest.php b/tests/ClearSaleID/Entity/Request/FingerPrintTest.php similarity index 57% rename from tests/ClearSale/Entity/Request/FingerPrintTest.php rename to tests/ClearSaleID/Entity/Request/FingerPrintTest.php index 3cbcfd0..3026926 100644 --- a/tests/ClearSale/Entity/Request/FingerPrintTest.php +++ b/tests/ClearSaleID/Entity/Request/FingerPrintTest.php @@ -1,10 +1,10 @@ assertSame( 'session-id-1234', $this->fingerPrint->getSessionId() ); + $this->assertSame('session-id-1234', $this->fingerPrint->getSessionId()); } /** @test */ public function testFingerPrintToXml() { - $outputXML = $this->generateXML( $this->fingerPrint ); + $outputXML = $this->generateXML($this->fingerPrint); $expectedXmlFile = __DIR__ . '/../../../data/fingerprint.xml'; - $this->assertXmlStringEqualsXmlFile( $expectedXmlFile, $outputXML ); + $this->assertXmlStringEqualsXmlFile($expectedXmlFile, $outputXML); } - private function generateXML( XmlEntityInterface $xmlEntity ) + private function generateXML(XmlEntityInterface $xmlEntity) { $xmlWriter = new \XMLWriter(); $xmlWriter->openMemory(); - $xmlWriter->setIndent( false ); + $xmlWriter->setIndent(false); - $xmlEntity->toXML( $xmlWriter ); + $xmlEntity->toXML($xmlWriter); - return $xmlWriter->outputMemory( true ); + return $xmlWriter->outputMemory(true); } } diff --git a/tests/ClearSaleID/Entity/Request/Fixtures/AddressFixture.php b/tests/ClearSaleID/Entity/Request/Fixtures/AddressFixture.php new file mode 100644 index 0000000..2a2a554 --- /dev/null +++ b/tests/ClearSaleID/Entity/Request/Fixtures/AddressFixture.php @@ -0,0 +1,22 @@ +item = ItemFixture::createItem(); + } + + protected function tearDown() + { + parent::tearDown(); + + $this->item = null; + } + + /** @test */ + public function testItem() + { + $this->assertSame('1', $this->item->getId()); + $this->assertSame('Adaptador USB', $this->item->getName()); + $this->assertSame(10.0, $this->item->getValue()); + $this->assertSame(1, $this->item->getQuantity()); + } + + /** @test */ + public function testItemToXml() + { + $outputXML = $this->generateXML($this->item); + $expectedXmlFile = __DIR__ . '/../../../data/item.xml'; + + $this->assertXmlStringEqualsXmlFile($expectedXmlFile, $outputXML); + } + + private function generateXML(XmlEntityInterface $xmlEntity) + { + $xmlWriter = new \XMLWriter(); + $xmlWriter->openMemory(); + $xmlWriter->setIndent(false); + + $xmlEntity->toXML($xmlWriter); + + return $xmlWriter->outputMemory(true); + } +} diff --git a/tests/ClearSale/Entity/Request/OrderTest.php b/tests/ClearSaleID/Entity/Request/OrderTest.php similarity index 59% rename from tests/ClearSale/Entity/Request/OrderTest.php rename to tests/ClearSaleID/Entity/Request/OrderTest.php index ce39493..2ee7570 100644 --- a/tests/ClearSale/Entity/Request/OrderTest.php +++ b/tests/ClearSaleID/Entity/Request/OrderTest.php @@ -1,10 +1,10 @@ generateXML( $this->ecommerceOrder ); + $outputXML = $this->generateXML($this->ecommerceOrder); $expectedXmlFile = __DIR__ . '/../../../data/order-ecommerce.xml'; - $this->assertXmlStringEqualsXmlFile( $expectedXmlFile, $outputXML ); + $this->assertXmlStringEqualsXmlFile($expectedXmlFile, $outputXML); } - private function generateXML( XmlEntityInterface $xmlEntity ) + private function generateXML(XmlEntityInterface $xmlEntity) { $xmlWriter = new \XMLWriter(); $xmlWriter->openMemory(); - $xmlWriter->setIndent( false ); + $xmlWriter->setIndent(false); - $xmlEntity->toXML( $xmlWriter ); + $xmlEntity->toXML($xmlWriter); - return $xmlWriter->outputMemory( true ); + return $xmlWriter->outputMemory(true); } } diff --git a/tests/ClearSale/Entity/Request/PaymentTest.php b/tests/ClearSaleID/Entity/Request/PaymentTest.php similarity index 52% rename from tests/ClearSale/Entity/Request/PaymentTest.php rename to tests/ClearSaleID/Entity/Request/PaymentTest.php index 9a745a0..2c315d2 100644 --- a/tests/ClearSale/Entity/Request/PaymentTest.php +++ b/tests/ClearSaleID/Entity/Request/PaymentTest.php @@ -1,12 +1,12 @@ assertInstanceOf( DateTime::class, $this->payment->getDate() ); - $this->assertSame( 17.5, $this->payment->getAmount() ); - $this->assertSame( Payment::BOLETO_BANCARIO, $this->payment->getType() ); + $this->assertInstanceOf(DateTime::class, $this->payment->getDate()); + $this->assertSame(17.5, $this->payment->getAmount()); + $this->assertSame(Payment::BOLETO_BANCARIO, $this->payment->getType()); } /** @test */ public function testPaymentToXml() { - $outputXML = $this->generateXML( $this->payment ); + $outputXML = $this->generateXML($this->payment); $expectedXmlFile = __DIR__ . '/../../../data/payment.xml'; - $this->assertXmlStringEqualsXmlFile( $expectedXmlFile, $outputXML ); + $this->assertXmlStringEqualsXmlFile($expectedXmlFile, $outputXML); } - private function generateXML( XmlEntityInterface $xmlEntity ) + private function generateXML(XmlEntityInterface $xmlEntity) { $xmlWriter = new \XMLWriter(); $xmlWriter->openMemory(); - $xmlWriter->setIndent( false ); + $xmlWriter->setIndent(false); - $xmlEntity->toXML( $xmlWriter ); + $xmlEntity->toXML($xmlWriter); - return $xmlWriter->outputMemory( true ); + return $xmlWriter->outputMemory(true); } } diff --git a/tests/ClearSale/Entity/Request/PhoneTest.php b/tests/ClearSaleID/Entity/Request/PhoneTest.php similarity index 51% rename from tests/ClearSale/Entity/Request/PhoneTest.php rename to tests/ClearSaleID/Entity/Request/PhoneTest.php index 4965ec0..82f8e6f 100644 --- a/tests/ClearSale/Entity/Request/PhoneTest.php +++ b/tests/ClearSaleID/Entity/Request/PhoneTest.php @@ -1,11 +1,11 @@ assertSame( Phone::COMERCIAL, $this->phone->getType() ); - $this->assertSame( '11', $this->phone->getDDD() ); - $this->assertSame( '37288788', $this->phone->getNumber() ); + $this->assertSame(Phone::COMERCIAL, $this->phone->getType()); + $this->assertSame('11', $this->phone->getDDD()); + $this->assertSame('37288788', $this->phone->getNumber()); } /** @test */ public function testPhoneToXml() { - $outputXML = $this->generateXML( $this->phone ); + $outputXML = $this->generateXML($this->phone); $expectedXmlFile = __DIR__ . '/../../../data/phone.xml'; - $this->assertXmlStringEqualsXmlFile( $expectedXmlFile, $outputXML ); + $this->assertXmlStringEqualsXmlFile($expectedXmlFile, $outputXML); } - private function generateXML( XmlEntityInterface $xmlEntity ) + private function generateXML(XmlEntityInterface $xmlEntity) { $xmlWriter = new \XMLWriter(); $xmlWriter->openMemory(); - $xmlWriter->setIndent( false ); + $xmlWriter->setIndent(false); - $xmlEntity->toXML( $xmlWriter ); + $xmlEntity->toXML($xmlWriter); - return $xmlWriter->outputMemory( true ); + return $xmlWriter->outputMemory(true); } } diff --git a/tests/ClearSaleID/Entity/Response/OrderTest.php b/tests/ClearSaleID/Entity/Response/OrderTest.php new file mode 100644 index 0000000..9824baa --- /dev/null +++ b/tests/ClearSaleID/Entity/Response/OrderTest.php @@ -0,0 +1,52 @@ +responseOrder = null; + } + + /** @test */ + public function testOrderResponseIdAndScore() + { + $id = '123'; + $score = 43.100; + + $this->responseOrder = new ResponseOrder($id, 43.100, ResponseOrder::STATUS_APPROVED_AUTOMATICALLY); + + $this->assertSame($id, $this->responseOrder->getId()); + $this->assertSame($score, $this->responseOrder->getScore()); + } + + /** + * @test + * @dataProvider statusProvider + * @param $status + * @param $expectedStatus + */ + public function testOrderResponseStatus($status, $expectedStatus) + { + $this->responseOrder = new ResponseOrder('123', 43.100, $status); + + $this->assertSame($expectedStatus, $this->responseOrder->getStatus()); + } + + public function statusProvider() + { + return [ + ['APA', ResponseOrder::STATUS_APPROVED_AUTOMATICALLY], + ['RPP', ResponseOrder::STATUS_REJECTED_BY_POLITICS], + ['RPA', ResponseOrder::STATUS_REJECTED_AUTOMATICALLY], + ]; + } +} diff --git a/tests/ClearSaleID/Entity/Response/PackageStatusTest.php b/tests/ClearSaleID/Entity/Response/PackageStatusTest.php new file mode 100644 index 0000000..ed706a0 --- /dev/null +++ b/tests/ClearSaleID/Entity/Response/PackageStatusTest.php @@ -0,0 +1,55 @@ +packageStatusResponse = null; + $this->orderResponse = null; + } + + /** + * @test + * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException + */ + public function testCreateFromXML() + { + $responseXmlFile = __DIR__ . '/../../../data/package-status.xml'; + $xml = \file_get_contents($responseXmlFile); + + $this->packageStatusResponse = new PackageStatus($xml); + + $this->assertSame('55929546-3c1e-4be0-b561-03ab72e74b32', $this->packageStatusResponse->getTransactionId()); + $this->assertSame(PackageStatus::STATUS_CODE_SUCCESS, $this->packageStatusResponse->getStatusCode()); + $this->assertSame('OK', $this->packageStatusResponse->getMessage()); + } + + /** + * @test + * @throws \RodrigoPedra\ClearSaleID\Exception\UnexpectedErrorException + */ + public function testOrderResponse() + { + $responseXmlFile = __DIR__ . '/../../../data/package-status.xml'; + $xml = \file_get_contents($responseXmlFile); + + $this->packageStatusResponse = new PackageStatus($xml); + $this->orderResponse = $this->packageStatusResponse->getOrder(); + + $this->assertSame('TEST-0A44444E6CEA465E85737421E651C70B', $this->orderResponse->getId()); + $this->assertSame(Order::STATUS_APPROVED_AUTOMATICALLY, $this->orderResponse->getStatus()); + $this->assertSame(79.94, $this->orderResponse->getScore()); + $this->assertEmpty($this->orderResponse->getQuizURL()); + } +} diff --git a/tests/ClearSaleID/Environment/AbstractEnvironmentTest.php b/tests/ClearSaleID/Environment/AbstractEnvironmentTest.php new file mode 100644 index 0000000..ca8b223 --- /dev/null +++ b/tests/ClearSaleID/Environment/AbstractEnvironmentTest.php @@ -0,0 +1,69 @@ +environment = $this->getMockBuilder(AbstractEnvironment::class) + ->disableOriginalConstructor() + ->setMethods(['getEntityCode', 'getRegularEndpoint', 'getExtendedEndpoint', 'isDebug']) + ->getMockForAbstractClass(); + + $this->environment->expects($this->any()) + ->method('getEntityCode') + ->will($this->returnValue('EC-123456')); + + $this->environment->expects($this->any()) + ->method('getRegularEndpoint') + ->will($this->returnValue('http://localhost/service.asmx')); + + $this->environment->expects($this->any()) + ->method('getExtendedEndpoint') + ->will($this->returnValue('http://localhost/extended.asmx')); + + $this->environment->expects($this->any()) + ->method('isDebug') + ->will($this->returnValue(true)); + } + + protected function tearDown() + { + parent::tearDown(); + + $this->environment = null; + } + + /** @test */ + public function testEntityCode() + { + $this->assertSame('EC-123456', $this->environment->getEntityCode()); + } + + /** @test */ + public function testWebServiceRegularUrl() + { + $this->assertSame('http://localhost/service.asmx', $this->environment->getRegularEndpoint()); + } + + /** @test */ + public function testWebServiceExtendedUrl() + { + $this->assertSame('http://localhost/extended.asmx', $this->environment->getExtendedEndpoint()); + } + + /** @test */ + public function testIsDebugTrue() + { + $this->assertTrue($this->environment->isDebug()); + } +} diff --git a/tests/ClearSale/Environment/ProductionTest.php b/tests/ClearSaleID/Environment/ProductionTest.php similarity index 59% rename from tests/ClearSale/Environment/ProductionTest.php rename to tests/ClearSaleID/Environment/ProductionTest.php index 3531a9a..3391609 100644 --- a/tests/ClearSale/Environment/ProductionTest.php +++ b/tests/ClearSaleID/Environment/ProductionTest.php @@ -1,13 +1,13 @@ environment = new Production( self::ENTITY_CODE ); + $this->environment = new Production(self::ENTITY_CODE); } protected function tearDown() @@ -29,32 +29,32 @@ protected function tearDown() /** @test */ public function testEntityCode() { - $this->assertSame( self::ENTITY_CODE, $this->environment->getEntityCode() ); + $this->assertSame(self::ENTITY_CODE, $this->environment->getEntityCode()); } /** @test */ public function testRegularWebServiceUrl() { - $this->assertSame( self::REGULAR_WEBSERVICE_URL, $this->environment->getRegularEndpoint() ); + $this->assertSame(self::REGULAR_WEBSERVICE_URL, $this->environment->getRegularEndpoint()); } /** @test */ public function testExtendedWebServiceUrl() { - $this->assertSame( self::EXTENDED_WEBSERICE_URL, $this->environment->getExtendedEndpoint() ); + $this->assertSame(self::EXTENDED_WEBSERICE_URL, $this->environment->getExtendedEndpoint()); } /** @test */ public function testDebug() { - $this->assertFalse( $this->environment->isDebug() ); + $this->assertFalse($this->environment->isDebug()); } /** @test */ public function testDebugTrue() { - $this->environment->setDebug( true ); + $this->environment->setDebug(true); - $this->assertTrue( $this->environment->isDebug() ); + $this->assertTrue($this->environment->isDebug()); } } diff --git a/tests/ClearSale/Environment/SandboxTest.php b/tests/ClearSaleID/Environment/SandboxTest.php similarity index 60% rename from tests/ClearSale/Environment/SandboxTest.php rename to tests/ClearSaleID/Environment/SandboxTest.php index 0c188b5..cca6d48 100644 --- a/tests/ClearSale/Environment/SandboxTest.php +++ b/tests/ClearSaleID/Environment/SandboxTest.php @@ -1,13 +1,13 @@ environment = new Sandbox( self::ENTITY_CODE ); + $this->environment = new Sandbox(self::ENTITY_CODE); } protected function tearDown() @@ -29,32 +29,32 @@ protected function tearDown() /** @test */ public function testEntityCode() { - $this->assertSame( self::ENTITY_CODE, $this->environment->getEntityCode() ); + $this->assertSame(self::ENTITY_CODE, $this->environment->getEntityCode()); } /** @test */ public function testRegularWebServiceUrl() { - $this->assertSame( self::REGULAR_WEBSERVICE_URL, $this->environment->getRegularEndpoint() ); + $this->assertSame(self::REGULAR_WEBSERVICE_URL, $this->environment->getRegularEndpoint()); } /** @test */ public function testExtendedWebServiceUrl() { - $this->assertSame( self::EXTENDED_WEBSERICE_URL, $this->environment->getExtendedEndpoint() ); + $this->assertSame(self::EXTENDED_WEBSERICE_URL, $this->environment->getExtendedEndpoint()); } /** @test */ public function testDebug() { - $this->assertFalse( $this->environment->isDebug() ); + $this->assertFalse($this->environment->isDebug()); } /** @test */ public function testDebugTrue() { - $this->environment->setDebug( true ); + $this->environment->setDebug(true); - $this->assertTrue( $this->environment->isDebug() ); + $this->assertTrue($this->environment->isDebug()); } }