Skip to content

Commit

Permalink
Merge pull request #5 from Sysvale/hotfix/version-xsd
Browse files Browse the repository at this point in the history
Corrige erro de validação quando não é passsado versão na regra ZipHasValidCnesXML
  • Loading branch information
jedsonmelo authored Apr 6, 2021
2 parents 4a1135e + e39cd0e commit 6ae766b
Show file tree
Hide file tree
Showing 10 changed files with 191 additions and 80 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "1.3.0",
"version": "1.3.1",
"name": "sysvale/validation-rules",
"description": "A Laravel library with useful custom rules",
"type": "library",
Expand Down
3 changes: 2 additions & 1 deletion resources/lang/pt_BR/messages.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
'max_in_the_zip_file' => 'O arquivo zip deve ter no máximo :quantity arquivo(s).',
'not_empty_zip' => 'O arquivo zip não pode está vazio.',
'zip_has_xml_file' => 'O arquivo zip deve conter um XML.',
'cnes_xml_identification' => 'XML com formato inválido. Por favor, verifique o código do IBGE, o campo de ORIGEM, o campo de DESTINO e a se a versão do XML compatível é a :version_xsd', // phpcs:ignore
'cnes_xml_identification' => 'XML com formato inválido. Por favor, verifique o código do IBGE, o campo de ORIGEM e o campo de DESTINO.', // phpcs:ignore
'cnes_xml_structure' => 'A estrutura do arquivo XML está inválida.',
'cnes_xml_date' => 'A competência do XML deve ser posterior a data :date.',
'cnes_xml_version_xsd' => 'A versão do XML deve ser compatível com a :version_xsd',
];
14 changes: 2 additions & 12 deletions src/Rules/CnesXMLDate.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@

use SimpleXMLElement;
use Illuminate\Contracts\Validation\Rule;
use Sysvale\ValidationRules\Rules\CnesXMLRule;
use Sysvale\ValidationRules\Support\ZipWithXMLHandler;

class CnesXMLDate implements Rule
class CnesXMLDate extends CnesXMLRule implements Rule
{
private $date;

Expand Down Expand Up @@ -46,17 +47,6 @@ public function message()
]);
}

private function getIdentificationAttributes($xml)
{
$identification = $xml->{'IDENTIFICACAO'};

if (empty($identification)) {
return [];
}

return array_values((array) $identification->attributes())[0];
}

protected function hasValidDate(SimpleXMLElement $xml)
{
$identification = $this->getIdentificationAttributes($xml);
Expand Down
31 changes: 10 additions & 21 deletions src/Rules/CnesXMLIdentification.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@

use SimpleXMLElement;
use Illuminate\Contracts\Validation\Rule;
use Sysvale\ValidationRules\Rules\CnesXMLRule;
use Sysvale\ValidationRules\Support\ZipWithXMLHandler;

class CnesXMLIdentification implements Rule
class CnesXMLIdentification extends CnesXMLRule implements Rule
{
private $expected_ibge_code;

public function __construct($expected_ibge_code, $version_xsd = '2.1')
public function __construct($expected_ibge_code, $version_xsd = null)
{
$this->expected_ibge_code = $expected_ibge_code;
$this->version_xsd = $version_xsd;
Expand Down Expand Up @@ -47,28 +48,16 @@ public function message()
]);
}


protected function hasValidIdentification(SimpleXMLElement $xml)
{
foreach ($xml->children() as $key => $identification) {
if ($key !== 'IDENTIFICACAO') {
return false;
}

$origin = (string) $identification['ORIGEM'];
$target = (string) $identification['DESTINO'];
$ibge_code = (string) $identification['CO_IBGE_MUN'];
$version_xsd = (string) $identification['VERSION_XSD'];
$identification = $this->getIdentificationAttributes($xml);

if ($origin === 'PORTAL'
&& $target === 'ESUS_AB'
&& $ibge_code === $this->expected_ibge_code
&& $version_xsd === $this->version_xsd
) {
return true;
}
}
$origin = (string) $identification['ORIGEM'] ?? '';
$target = (string) $identification['DESTINO'] ?? '';
$ibge_code = (string) $identification['CO_IBGE_MUN'] ?? '';

return false;
return $origin === 'PORTAL'
&& $target === 'ESUS_AB'
&& $ibge_code === $this->expected_ibge_code;
}
}
17 changes: 17 additions & 0 deletions src/Rules/CnesXMLRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Sysvale\ValidationRules\Rules;

abstract class CnesXMLRule
{
protected function getIdentificationAttributes($xml)
{
$identification = $xml->{'IDENTIFICACAO'};

if (empty($identification)) {
return [];
}

return array_values((array) $identification->attributes())[0];
}
}
57 changes: 57 additions & 0 deletions src/Rules/CnesXMLVersionXSD.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace Sysvale\ValidationRules\Rules;

use SimpleXMLElement;
use Illuminate\Contracts\Validation\Rule;
use Sysvale\ValidationRules\Rules\CnesXMLRule;
use Sysvale\ValidationRules\Support\ZipWithXMLHandler;

class CnesXMLVersionXSD extends CnesXMLRule implements Rule
{
private $version;

public function __construct($version)
{
$this->version = $version;
}

/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$zip_handler = resolve(ZipWithXMLHandler::class)
->buildZip($value->path());

$passes = $this->hasValidVersion($zip_handler->getSimpleXMLElement());

$zip_handler->closeZip();

return $passes;
}

/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return __('SysvaleValidationRules::messages.cnes_xml_version_xsd', [
'version_xsd' => $this->version,
]);
}

protected function hasValidVersion(SimpleXMLElement $xml)
{
$identification = $this->getIdentificationAttributes($xml);
$current_version_xsd = $identification['VERSION_XSD'] ?? null;

return $current_version_xsd === $this->version;
}
}
11 changes: 11 additions & 0 deletions src/Rules/ZipHasValidCnesXML.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ public function passes($attribute, $value)
$passes = $passes && $this->hasValidDate($attribute, $value);
}

if (isset($this->version_xsd)) {
$passes = $passes && $this->hasValidVersion($attribute, $value);
}

return $passes;
}

Expand Down Expand Up @@ -69,6 +73,13 @@ protected function hasValidDate($attribute, $value)
return $this->validateWithRule($rule, $attribute, $value);
}

protected function hasValidVersion($attribute, $value)
{
$rule = new CnesXMLVersionXSD($this->version_xsd);

return $this->validateWithRule($rule, $attribute, $value);
}

private function validateWithRule($rule, $attribute, $value)
{
$passes = $rule->passes($attribute, $value);
Expand Down
42 changes: 1 addition & 41 deletions tests/Unit/Rules/CnesXMLIdentificationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,46 +19,6 @@ public function testPasses()

$this->mockXmlContents(['ibge_code' => $ibge_code]);

$rule = new CnesXMLIdentification($ibge_code, '2.1');

$this->assertTrue($rule->passes('file', UploadedFile::fake()->create('xml.zip')));
}

public function testNotPassesVersionXSD()
{
$ibge_code = '12345';

$this->mockXmlContents(['ibge_code' => $ibge_code, 'version_xsd' => '']);

$rule = new CnesXMLIdentification($ibge_code, '2.1');

$this->assertFalse($rule->passes('file', UploadedFile::fake()->create('xml.zip')));
}

public function testNotPassesVersionXSDDiff21()
{
$ibge_code = '12345';
$version_xsd = '3.0';

$this->mockXmlContents([
'ibge_code' => $ibge_code,
'version_xsd' => "VERSION_XSD=\"$version_xsd\""
]);

$rule = new CnesXMLIdentification($ibge_code, '2.1');

$this->assertFalse($rule->passes('file', UploadedFile::fake()->create('xml.zip')));
}

public function testSecondArgumentIsntPassed()
{
$ibge_code = '12345';

$this->mockXmlContents([
'ibge_code' => $ibge_code,
'version_xsd' => "VERSION_XSD=\"2.1\""
]);

$rule = new CnesXMLIdentification($ibge_code);

$this->assertTrue($rule->passes('file', UploadedFile::fake()->create('xml.zip')));
Expand All @@ -70,7 +30,7 @@ public function testSecondArgumentIsntPassed()
public function testIdentificationErrorMessage()
{
$this->assertSame(
'XML com formato inválido. Por favor, verifique o código do IBGE, o campo de ORIGEM, o campo de DESTINO e a se a versão do XML compatível é a 2.1',
'XML com formato inválido. Por favor, verifique o código do IBGE, o campo de ORIGEM e o campo de DESTINO.',
$this->getErrorMessage(CnesXMLIdentification::class, ['0000', '2.1'])
);
}
Expand Down
46 changes: 46 additions & 0 deletions tests/Unit/Rules/CnesXMLVersionXSDTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace Sysvale\ValidationRules\Tests\Unit\Rules;

use Illuminate\Http\UploadedFile;
use Sysvale\ValidationRules\Tests\TestCase;
use Sysvale\ValidationRules\Rules\CnesXMLVersionXSD;
use Sysvale\ValidationRules\Rules\CnesXMLIdentification;
use Sysvale\ValidationRules\Tests\Support\CnesXMLContentsHandler;
use Sysvale\ValidationRules\Tests\Support\RuleErrorMessageHandler;

class CnesXMLVersionXSDTest extends TestCase
{
use RuleErrorMessageHandler;
use CnesXMLContentsHandler;

public function testPasses()
{
$version = '2.1';

$this->mockXmlContents(['version_xsd' => "VERSION_XSD=\"$version\""]);

$rule = new CnesXMLVersionXSD('2.1');

$this->assertTrue($rule->passes('file', UploadedFile::fake()->create('xml.zip')));
}

public function testNotPasses()
{
$version = '2';

$this->mockXmlContents(['version_xsd' => "VERSION_XSD=\"$version\""]);

$rule = new CnesXMLVersionXSD('2.1');

$this->assertFalse($rule->passes('file', UploadedFile::fake()->create('xml.zip')));
}

public function testIdentificationErrorMessage()
{
$this->assertSame(
'A versão do XML deve ser compatível com a 2.1',
$this->getErrorMessage(CnesXMLVersionXSD::class, ['2.1'])
);
}
}
48 changes: 44 additions & 4 deletions tests/Unit/Rules/ZipHasValidCnesXMLTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,29 @@ public function testFileWithInvalidIdentification()

$this->assertFalse($passes);
$this->assertEquals(
'XML com formato inválido. Por favor, verifique o código do IBGE, o campo de ORIGEM, o campo de DESTINO e a se a versão do XML compatível é a 2.1', //phpcs:ignore
'XML com formato inválido. Por favor, verifique o código do IBGE, o campo de ORIGEM e o campo de DESTINO.', //phpcs:ignore
$validator->errors()->first('file')
);
}

public function testFileWithInvalidVersion()
{
$this->mockXmlContents([
'ibge_code' => '1234',
'version_xsd' => 'VERSION_XSD="2"'
]);

$validator = Validator::make([
'file' => UploadedFile::fake()->create('xml.zip'),
], [
'file' => [new ZipHasValidCnesXML('1234', null, '2.1')],
]);

$passes = $validator->passes();

$this->assertFalse($passes);
$this->assertEquals(
'A versão do XML deve ser compatível com a 2.1',
$validator->errors()->first('file')
);
}
Expand All @@ -75,14 +97,13 @@ public function testFileWithInvalidDate()
{
$this->mockXmlContents([
'ibge_code' => '',
'date' =>'2020-10-10',
'version_xsd' => 'VERSION_XSD="2.1"'
'date' =>'2020-10-10'
]);

$validator = Validator::make([
'file' => UploadedFile::fake()->create('xml.zip'),
], [
'file' => [new ZipHasValidCnesXML('', '2020-10-10', $version_xsd = '2.1')],
'file' => [new ZipHasValidCnesXML('', '2020-10-10')],
]);

$passes = $validator->passes();
Expand All @@ -94,6 +115,25 @@ public function testFileWithInvalidDate()
);
}

public function testPassesWithoutVersionXSD()
{
$this->mockXmlContents([
'ibge_code' => '',
'date' =>'2020-10-11',
'version_xsd' => ''
]);

$validator = Validator::make([
'file' => UploadedFile::fake()->create('xml.zip'),
], [
'file' => [new ZipHasValidCnesXML('', '2020-10-10')],
]);

$passes = $validator->passes();

$this->assertTrue($passes);
}

public function testValidFilePasses()
{
$this->mockXmlContents(['ibge_code' => '123456', 'date' => '2020-10-10']);
Expand Down

0 comments on commit 6ae766b

Please sign in to comment.