Created
April 19, 2012 08:09
-
-
Save Burgov/2419554 to your computer and use it in GitHub Desktop.
Data transformer for week data
This file contains hidden or 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 Samson\TRSBundle\Form\DataTransformer; | |
use Symfony\Component\Form\DataTransformerInterface; | |
use Symfony\Component\Form\Exception\TransformationFailedException; | |
class LabourWeekTransformer implements DataTransformerInterface | |
{ | |
private $week; | |
private $year; | |
public function __construct($year, $week) | |
{ | |
$this->week = $week; | |
$this->year = $year; | |
} | |
public function transform($value) | |
{ | |
// norm to client | |
if (null === $value) { | |
return; | |
} | |
$start = new \DateTime; | |
$start->setISODate($this->year, $this->week, 0); | |
$end = clone $start; | |
$end->modify('next sunday 23:59'); | |
foreach($value as $labour) { | |
if (null === $labour->getDate()) { | |
throw new TransformationFailedException('The labour entity has no date!'); | |
} | |
if ($labour->getDate() < $start || $labour->getDate() > $end) { | |
throw new TransformationFailedException('The labour entity date '.$labour->getDate()->format('Y-m-d H:i:s').' is not in week '.$this->week.' of year '.$this->year); | |
} | |
} | |
usort($value, function($a, $b) { | |
return $a->getStart() < $b->getStart() ? -1 : ($a->getStart() == $b->getStart() ? 0 : 1); | |
}); | |
$return = array( | |
'Mon' => array(), | |
'Tue' => array(), | |
'Wed' => array(), | |
'Thu' => array(), | |
'Fri' => array(), | |
'Sat' => array(), | |
'Sun' => array(), | |
); | |
foreach($value as $labour) { | |
$return[$labour->getDate()->format('D')][] = $labour; | |
} | |
return $return; | |
} | |
public function reverseTransform($value) | |
{ | |
$labour = array(); | |
foreach ($value as $day => $dayLabour) { | |
foreach($dayLabour as $labourEntity) { | |
if (null !== $labourEntity->getDate()) { | |
$labour[] = $labourEntity; | |
} | |
} | |
} | |
return $labour; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment