3v4l.org

run code in 300+ PHP versions simultaneously
<?php class MyEntity { const STATE_NEW = 'new'; const STATE_IN_PROGRESS = 'in_progress'; const STATE_COMPLETE = 'complete'; const CONFIG_STATES = array( self::STATE_NEW, self::STATE_IN_PROGRESS, self::STATE_COMPLETE ); /** * @var \DateTime|null * @ORM\Column(type="datetime", nullable=true) */ private $dateStarted; /** * @var string|null * @ORM\Column(type="string", nullable=true) */ private $state = self::STATE_NEW; /** * @var string|null $state */ public function setState($state = null) { $this->validateState($state); $this->updateStateDate($state); $this->state = $state; return $this; } public function getState() { return $this->state; } public function getDateStarted() { return $this->dateStarted; } /** * used to update the started date when the state changes to in_progress * @var string $state */ protected function updateStateDate($state) { if ($this->state !== $state && $state === self::STATE_IN_PROGRESS && $this->dateStarted === null) { $this->dateStarted = new \DateTime(); } return $this; } protected function validateState($state) { if (!in_array($state, self::CONFIG_STATES, true)) { throw new \InvalidArgumentException( sprintf('Unknown state "%s". Expected one of: "%s"', $state, implode('", "', self::CONFIG_STATES) ) ); } if ($this->state === self::STATE_NEW && $state !== self::STATE_IN_PROGRESS) { throw new \InvalidArgumentException( sprintf('Invalid state "%s" specified, Expected: %s', $state, self::STATE_IN_PROGRESS ) ); } return $this; } } $entity = new \MyEntity; var_dump($entity); echo \PHP_EOL . '----' . \PHP_EOL; echo 'set State as in progress and set the initial date'. \PHP_EOL; $entity->setState(MyEntity::STATE_IN_PROGRESS); var_dump($entity); echo \PHP_EOL . '----' . \PHP_EOL; echo 'set State as complete and leave date unchanged'. \PHP_EOL; $entity->setState(MyEntity::STATE_COMPLETE); var_dump($entity); echo \PHP_EOL . '----' . \PHP_EOL; echo 'change the state back to in progress and leave the date unchanged'. \PHP_EOL; $entity->setState(MyEntity::STATE_IN_PROGRESS); var_dump($entity); echo \PHP_EOL . '----' . \PHP_EOL; echo 'use an invalid state string'. \PHP_EOL; $entity->setState('Wrong State');

preferences:
39.48 ms | 402 KiB | 5 Q