Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Adds extend method

  • Loading branch information...
commit 7367dca50e98dbcecd5744c8a8108ca5a3dcdc88 1 parent 321db91
@davedevelopment davedevelopment authored
Showing with 51 additions and 0 deletions.
  1. +26 −0 lib/Pimple.php
  2. +25 −0 tests/Pimple/Tests/PimpleTest.php
View
26 lib/Pimple.php
@@ -157,4 +157,30 @@ function raw($id)
return $this->values[$id];
}
+
+ /**
+ * Extends an object (in place)
+ *
+ * Useful when you want to extend an existing objects Closure definition,
+ * without necessarily loading that object
+ *
+ * @param string $id The unique identifier for the object
+ *
+ * @param Closure $callable A closure to extend the original
+ *
+ * @return Closure The wrapped closure
+ *
+ * @throws InvalidArgumentException if the identifier is not defined
+ */
+ function extend($id, Closure $callable)
+ {
+ if (!array_key_exists($id, $this->values)) {
+ throw new InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
+ }
+
+ $factory = $this->values[$id];
+ return $this->values[$id] = function ($c) use ($callable, $factory) {
+ return $callable($factory($c), $c);
+ };
+ }
}
View
25 tests/Pimple/Tests/PimpleTest.php
@@ -190,4 +190,29 @@ public function testRawValidatesKeyIsPresent()
$pimple = new Pimple();
$pimple->raw('foo');
}
+
+ public function testExtend()
+ {
+ $pimple = new Pimple();
+ $pimple['shared_service'] = $pimple->share(function () {
+ return new Service();
+ });
+
+ $value = 12345;
+
+ $pimple->extend('shared_service', function($sharedService) use ($value) {
+ $sharedService->value = $value;
+ return $sharedService;
+ });
+
+ $serviceOne = $pimple['shared_service'];
+ $this->assertInstanceOf('Pimple\Tests\Service', $serviceOne);
+ $this->assertEquals($value, $serviceOne->value);
+
+ $serviceTwo = $pimple['shared_service'];
+ $this->assertInstanceOf('Pimple\Tests\Service', $serviceTwo);
+ $this->assertEquals($value, $serviceTwo->value);
+
+ $this->assertSame($serviceOne, $serviceTwo);
+ }
}
Please sign in to comment.
Something went wrong with that request. Please try again.