silverstripe-framework/tests/injector/AopProxyTest.php

108 lines
2.2 KiB
PHP
Raw Normal View History

<?php
/**
2014-08-15 08:53:05 +02:00
*
*
* @author <marcus@silverstripe.com.au>
* @license BSD License http://www.silverstripe.org/bsd-license
*/
class AopProxyTest extends SapphireTest {
public function testBeforeMethodsCalled() {
$proxy = new AopProxyService();
$aspect = new BeforeAfterCallTestAspect();
$proxy->beforeCall = array(
'myMethod' => $aspect
);
$proxy->proxied = new ProxyTestObject();
2014-08-15 08:53:05 +02:00
$result = $proxy->myMethod();
2014-08-15 08:53:05 +02:00
$this->assertEquals('myMethod', $aspect->called);
$this->assertEquals(42, $result);
}
2014-08-15 08:53:05 +02:00
public function testBeforeMethodBlocks() {
$proxy = new AopProxyService();
$aspect = new BeforeAfterCallTestAspect();
$aspect->block = true;
2014-08-15 08:53:05 +02:00
$proxy->beforeCall = array(
'myMethod' => $aspect
);
$proxy->proxied = new ProxyTestObject();
2014-08-15 08:53:05 +02:00
$result = $proxy->myMethod();
2014-08-15 08:53:05 +02:00
$this->assertEquals('myMethod', $aspect->called);
2014-08-15 08:53:05 +02:00
// the actual underlying method will NOT have been called
$this->assertNull($result);
2014-08-15 08:53:05 +02:00
// set up an alternative return value
$aspect->alternateReturn = 84;
2014-08-15 08:53:05 +02:00
$result = $proxy->myMethod();
2014-08-15 08:53:05 +02:00
$this->assertEquals('myMethod', $aspect->called);
2014-08-15 08:53:05 +02:00
// the actual underlying method will NOT have been called,
// instead the alternative return value
$this->assertEquals(84, $result);
}
2014-08-15 08:53:05 +02:00
public function testAfterCall() {
$proxy = new AopProxyService();
$aspect = new BeforeAfterCallTestAspect();
2014-08-15 08:53:05 +02:00
$proxy->afterCall = array(
'myMethod' => $aspect
);
$proxy->proxied = new ProxyTestObject();
2014-08-15 08:53:05 +02:00
$aspect->modifier = function ($value) {
return $value * 2;
};
2014-08-15 08:53:05 +02:00
$result = $proxy->myMethod();
$this->assertEquals(84, $result);
}
2014-08-15 08:53:05 +02:00
}
class ProxyTestObject {
public function myMethod() {
return 42;
}
}
class BeforeAfterCallTestAspect implements BeforeCallAspect, AfterCallAspect {
public $block = false;
2014-08-15 08:53:05 +02:00
public $called;
2014-08-15 08:53:05 +02:00
public $alternateReturn;
2014-08-15 08:53:05 +02:00
public $modifier;
public function beforeCall($proxied, $method, $args, &$alternateReturn) {
$this->called = $method;
2014-08-15 08:53:05 +02:00
if ($this->block) {
if ($this->alternateReturn) {
$alternateReturn = $this->alternateReturn;
}
return false;
}
}
public function afterCall($proxied, $method, $args, $result) {
if ($this->modifier) {
$modifier = $this->modifier;
return $modifier($result);
}
}
2014-08-15 08:53:05 +02:00
}