Skip to content

Commit

Permalink
[MOD] add data transformer
Browse files Browse the repository at this point in the history
  • Loading branch information
lcp0578 committed May 29, 2019
1 parent 0a65e93 commit df5ba7a
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
44 changes: 44 additions & 0 deletions Form/DataTransformer/DateTransformer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php
namespace Kit\FormBundle\Form\DateTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class DateTransformer implements DataTransformerInterface
{
/**
* Transforms an object (DateTime) to a string (date).
*
* @param \DateTime|string $dateTime
* @return string
*/
public function transform($dateTime)
{
if($dateTime instanceof \DateTime){
return $dateTime->format('Y-m-d H:i:s');
}

return $dateTime;
}

/**
* Transforms a string (date) to an object (DateTime).
*
* @param string $dateStr
* @return string
* @throws TransformationFailedException if object (issue) is not found.
*/
public function reverseTransform($dateStr)
{
try{
$dateTime = new \DateTime($dateStr);
}catch (\Exception $e) {
throw new TransformationFailedException(sprintf(
'DateTime convert error!',
$e->getMessage()
));
}

return $dateTime;
}
}
3 changes: 3 additions & 0 deletions Resources/config/services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@ services:
# kit_form.example:
# class: Kit\FormBundle\Example
# arguments: ["@service_id", "plain_value", "%parameter%"]
kit_form.form.data_transformer_date:
class: Kit\FormBundle\Form\DateTransformer\DateTransformer
Kit\FormBundle\Form\DateTransformer\DateTransformer: "@kit_form.data_transformer_date"

0 comments on commit df5ba7a

Please sign in to comment.