diff --git a/core/lib/Drupal/Component/Datetime/DateTimePlus.php b/core/lib/Drupal/Component/Datetime/DateTimePlus.php index fff7c71..2e9bc02 100644 --- a/core/lib/Drupal/Component/Datetime/DateTimePlus.php +++ b/core/lib/Drupal/Component/Datetime/DateTimePlus.php @@ -306,8 +306,25 @@ public function render() { * Implements the magic __call method. * * Passes through all unknown calls onto the DateTime object. + * + * @param string $method + * The method to call on the decorated object. + * @param array $args + * Call arguments. + * + * @return mixed + * The return value from the method on the decorated object. If the proxied + * method call returns a DateTime object, then return the original + * DateTimePlus object, which allows function chaining to work properly. + * Otherwise, the value from the proxied method call is returned. + * + * @throws \Exception + * Thrown when the DateTime object is not set. + * @throws \BadMethodCallException + * Thrown when there is no corresponding method on the DateTime object to + * call. */ - public function __call($method, $args) { + public function __call($method, array $args) { // @todo consider using assert() as per https://www.drupal.org/node/2451793. if (!isset($this->dateTimeObject)) { throw new \Exception('DateTime object not set.'); @@ -316,17 +333,9 @@ public function __call($method, $args) { throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_class($this), $method)); } - $val = call_user_func_array([$this->dateTimeObject, $method], $args); + $result = call_user_func_array([$this->dateTimeObject, $method], $args); - // If the proxied function call returns a DateTime object, then return - // the original DateTimePlus object, which allows function chaining to - // work properly. - if (is_object($val) && get_class($val) === 'DateTime') { - return $this; - } - else { - return $val; - } + return $result === $this->dateTimeObject ? $this : $result; } /** diff --git a/core/tests/Drupal/Tests/Component/Datetime/DateTimePlusTest.php b/core/tests/Drupal/Tests/Component/Datetime/DateTimePlusTest.php index c6fcc40..2eab8db 100644 --- a/core/tests/Drupal/Tests/Component/Datetime/DateTimePlusTest.php +++ b/core/tests/Drupal/Tests/Component/Datetime/DateTimePlusTest.php @@ -831,6 +831,13 @@ public function testChainable() { $date->setTimestamp(23456789); $rendered = $date->setTimezone(new \DateTimeZone('America/New_York'))->render(); $this->assertEquals('1970-09-29 07:46:29 America/New_York', $rendered); + + $date = DateTimePlus::createFromFormat('Y-m-d H:i:s', '1970-05-24 07:21:18', new \DateTimeZone('Australia/Sydney')) + ->setTimezone(new \DateTimeZone('America/New_York')); + $rendered = $date->render(); + $this->assertInstanceOf(DateTimePlus::class, $date); + $this->assertEquals(12345678, $date->getTimestamp()); + $this->assertEquals('1970-05-23 17:21:18 America/New_York', $rendered); } /**