-
-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #27 from ArondeParon/develop
Implement CarbonDateSanitizer
- Loading branch information
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}"); | ||
} | ||
} | ||
} |