Skip to content

Commit

Permalink
Merge pull request #27 from ArondeParon/develop
Browse files Browse the repository at this point in the history
Implement CarbonDateSanitizer
  • Loading branch information
arondeparon authored Dec 15, 2021
2 parents 22ef167 + 7dfec39 commit 3a2244b
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Sanitizers/CarbonDateSanitizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace ArondeParon\RequestSanitizer\Sanitizers;

use ArondeParon\RequestSanitizer\Contracts\Sanitizer;
use Carbon\Carbon;

class CarbonDateSanitizer implements Sanitizer
{
public function sanitize($input)
{
try {
return Carbon::parse($input);
} catch (\Exception $e) {
return null;
}
}
}
40 changes: 40 additions & 0 deletions tests/Sanitizers/CarbonDateSanitizerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace ArondeParon\RequestSanitizer\Tests\Sanitizers;

use ArondeParon\RequestSanitizer\Sanitizers\CarbonDateSanitizer;
use ArondeParon\RequestSanitizer\Tests\TestCase;
use Carbon\Carbon;

class CarbonDateSanitizerTest extends TestCase
{
public function test_it_will_cast_a_valid_date_to_carbon()
{
$dateFormats = [
'2021-12-15',
'2021-12-15 12:00:00',
'2021-12-15 12:00:00.000000',
];

$sanitizer = new CarbonDateSanitizer();

foreach ($dateFormats as $dateFormat) {
$this->assertInstanceOf(Carbon::class, $sanitizer->sanitize($dateFormat));
}
}

public function test_it_will_return_null_if_the_date_is_invalid()
{
$invalidDateFormats = [
'derp',
'May 33',
'2021-13-30'
];

$sanitizer = new CarbonDateSanitizer();

foreach ($invalidDateFormats as $dateFormat) {
$this->assertNull($sanitizer->sanitize($dateFormat), "It will not parse {$dateFormat}");
}
}
}

0 comments on commit 3a2244b

Please sign in to comment.