From dd662675bf74f4161850f8cc0738312876694561 Mon Sep 17 00:00:00 2001 From: Olivier Laviale Date: Tue, 3 Sep 2013 17:45:28 +0200 Subject: [PATCH] Added from() --- lib/timezone.php | 2 +- lib/timezonelocation.php | 21 +++++++++++++++++++++ tests/TimeZoneLocationTest.php | 17 +++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/lib/timezone.php b/lib/timezone.php index d1a2b78..75036e8 100644 --- a/lib/timezone.php +++ b/lib/timezone.php @@ -87,7 +87,7 @@ public function __get($property) if (!$this->location) { - $this->location = new TimeZoneLocation($this->getLocation()); + $this->location = TimeZoneLocation::from($this); } return $this->location; diff --git a/lib/timezonelocation.php b/lib/timezonelocation.php index 4eb9848..d6c9835 100644 --- a/lib/timezonelocation.php +++ b/lib/timezonelocation.php @@ -37,6 +37,27 @@ */ class TimeZoneLocation { + static private $cache; + + /** + * Creates an instance from a {@link \DateTimeZone} instance. + * + * @param \DateTimeZone $zone + * + * @return \ICanBoogie\TimeZoneLocation + */ + static public function from(\DateTimeZone $zone) + { + $hash = spl_object_hash($zone); + + if (empty(self::$cache[$hash])) + { + self::$cache[$hash] = new static($zone->getLocation()); + } + + return self::$cache[$hash]; + } + private $location; /** diff --git a/tests/TimeZoneLocationTest.php b/tests/TimeZoneLocationTest.php index dad7ba0..105cf66 100644 --- a/tests/TimeZoneLocationTest.php +++ b/tests/TimeZoneLocationTest.php @@ -15,6 +15,23 @@ class TimeZoneLocationTest extends \PHPUnit_Framework_TestCase { + public function test_from() + { + $zone = new \DateTimeZone('Europe/Paris'); + $location = TimeZoneLocation::from($zone); + + $this->assertInstanceOf('ICanBoogie\TimeZoneLocation', $location); + } + + public function test_from_cache() + { + $zone = new \DateTimeZone('Europe/Paris'); + $location = TimeZoneLocation::from($zone); + $cached = TimeZoneLocation::from($zone); + + $this->assertEquals(spl_object_hash($location), spl_object_hash($cached)); + } + public function test_location() { $zone = new \DateTimeZone('Europe/Paris');