Created
July 5, 2015 13:40
-
-
Save SebLours/ec58671d524f8f8c92cd to your computer and use it in GitHub Desktop.
Symfony2 duration datatransformer
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
<?php | |
namespace AppBundle\Form\DataTransformer; | |
use Symfony\Component\Form\DataTransformerInterface; | |
use Symfony\Component\Form\Exception\TransformationFailedException; | |
class DurationTransformer implements DataTransformerInterface | |
{ | |
/** | |
* Transform seconds in duration | |
* 4340 => 1h12m20s | |
* | |
* @param integer $seconds | |
* | |
* @return string | |
*/ | |
public function transform($seconds) | |
{ | |
return ltrim(gmdate("H\hi\ms\s", $seconds), "0hm"); | |
} | |
/** | |
* Tranform a duration in seconds | |
* 1h12m20s => 4340 | |
* | |
* @param string $duration | |
* | |
* @return integer | |
*/ | |
public function reverseTransform($duration) | |
{ | |
$pattern = '/^(?:([\d]{1,2})h)?(?:([\d]{1,2})m)?(?:([\d]{1,2})s)?$/'; | |
preg_match($pattern , $duration, $matches); | |
$seconds = @$matches[1] * 3600 + @$matches[2] * 60 + @$matches[3]; | |
return $seconds; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment